{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Quantization-aware training a ResNet18\n\nPost-training quantization measures a model's activation ranges from a handful\nof batches and changes no weights. Quantization-aware training instead trains\nthe model with quantization simulated in the forward pass, so the weights adapt\nto the quantizer -- and the quantizer's own step sizes are learned against the\ntask loss rather than measured from data.\n\nThis tutorial runs both on a pretrained ResNet18 over ImageNette and exports\nthe fine-tuned model to ONNX. It is a walk through the mechanics: which call\ndoes what, and what state the model is in between them.\n\nInstall dependencies:\n\n```bash\npip install --upgrade --extra-index-url https://deploy.embedl.com/downloads/         \"embedl-deploy[tensorrt]\"\npip install torchvision onnx\n```\nThe Embedl wheels come from the Embedl package index rather than PyPI, so the\ninstall needs an Embedl Hub API key: put it in ``~/.netrc`` as the password for\n``machine deploy.embedl.com`` with login ``hub``, or write the index URL as\n``https://hub:<API_KEY>@deploy.embedl.com/downloads/``.\n\n<div class=\"alert alert-info\"><h4>Note</h4>\n\nFine-tuning needs a GPU to be practical. On CPU a single epoch over\nImageNette takes about eight minutes.\n\n</div>\n\nThis tutorial imports :download:`_imagenette_data.py\n</tutorials/_imagenette_data.py>`, which the download buttons at the bottom of\nthis page do not bundle -- they ship this script alone. Fetch the companion\nthrough that link and keep it in the same directory as the script.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Setup\n\nImageNette is a ten-class subset of ImageNet. Its classes keep their original\nImageNet indices, so a pretrained classifier can be evaluated on it without\nretraining the head -- the label remap below is the whole adaptation.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from pathlib import Path\n\nimport torch\nimport torchvision\nfrom torch import nn\nfrom torch.utils.data import DataLoader\nfrom torchvision.models import ResNet18_Weights, resnet18\n\ntorch.manual_seed(0)\n\ntry:\n    from _imagenette_data import (\n        IMAGENETTE_DIR,\n        download_imagenette,\n        remap,\n    )\nexcept ImportError:\n    raise ImportError(\n        \"This tutorial requires _imagenette_data.py beside it, \"\n        \"providing the utilities it does not restate. Download \"\n        \"from the links in this tutorial's introduction, into this \"\n        \"directory.\"\n    ) from None\n\n\nOUT_DIR = Path(\"artifacts/resnet18_qat\")\n\n\ndownload_imagenette()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The model carries its own preprocessing transform. Using it rather than a\nhand-written ``Resize``/``CenterCrop`` pair guarantees the pixels the network\nsees match the ones it was trained on, which matters more than usual here:\ncalibration and fine-tuning both measure the model through this pipeline.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "weights = ResNet18_Weights.IMAGENET1K_V1\npreprocess = weights.transforms()\nmodel = resnet18(weights=weights).eval()\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel.to(device)\n\n\ndef loader(\n    split: str, *, shuffle: bool\n) -> DataLoader[tuple[torch.Tensor, torch.Tensor]]:\n    \"\"\"Build a data loader over one ImageNette `split`.\n\n    :param split:\n        Either ``\"train\"`` or ``\"val\"``.\n    :param shuffle:\n        Whether to shuffle, which training needs and evaluation does not.\n    :returns:\n        A ``DataLoader`` yielding preprocessed batches with ImageNet labels.\n    \"\"\"\n    dataset = torchvision.datasets.ImageFolder(\n        str(IMAGENETTE_DIR / split),\n        transform=preprocess,\n        target_transform=remap,\n    )\n    return DataLoader(dataset, batch_size=32, shuffle=shuffle)\n\n\ntrain_loader = loader(\"train\", shuffle=True)\nval_loader = loader(\"val\", shuffle=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Evaluation\n\nOne accuracy function, used for every number in this tutorial. Each model is\nmeasured the same way, so the comparisons at the end mean something.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def accuracy(\n    module: nn.Module,\n    data: DataLoader[tuple[torch.Tensor, torch.Tensor]],\n) -> float:\n    \"\"\"Top-1 accuracy of `module` over `data`.\n\n    The training mode of every submodule is restored on return, so measuring\n    part-way through a run does not disturb it. Restoring is per submodule\n    rather than one ``train()`` on the root, because ``train()`` recurses and\n    would put back any BatchNorm the caller is holding in eval.\n\n    :param module:\n        The model to evaluate. Its training mode is left as it was found.\n    :param data:\n        The batches to evaluate over.\n    :returns:\n        The fraction of correctly classified samples.\n    \"\"\"\n    was_training = {sub: sub.training for sub in module.modules()}\n    module.eval()\n    correct = 0\n    total = 0\n    try:\n        with torch.no_grad():\n            for images, labels in data:\n                inputs, targets = images.to(device), labels.to(device)\n                predicted = module(inputs).argmax(dim=1)\n                correct += int((predicted == targets).sum())\n                total += targets.numel()\n    finally:\n        for sub, training in was_training.items():\n            sub.training = training\n    return correct / total"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Transformation\n\n:func:`~embedl_deploy.transform` rewrites the graph into the fused\nmodules the backend expects -- here, folding each ``Conv2d`` and its\n``BatchNorm2d`` and activation into one quantizable unit. Quantization\nalways follows transformation; the fused boundaries are what the Q/DQ\nstubs attach to.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from embedl_deploy import transform\nfrom embedl_deploy.backend import set_backend\n\nset_backend(\"tensorrt\")\n\nexample_input = torch.randn(1, 3, 224, 224, device=device)\nfused = transform(model, (example_input,)).model\n\nfloat_accuracy = accuracy(fused, val_loader)\nprint(f\"float32 baseline:      {float_accuracy:.2%}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Post-training quantization\n\nThe comparison point. A ``forward_loop`` feeds a few batches through the\nmodel so each stub can observe the range of the activations reaching it;\nthose ranges become the quantization scales. No weight is touched.\n\nCalibrating also bakes the weight scales into constant buffers, which ONNX\nexport requires: ``freeze_weights`` follows ``forward_loop`` unless it is\ngiven, so passing one is enough.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import copy\nimport itertools\n\nfrom embedl_deploy.quantize import quantize\n\ncalibration_batches = list(itertools.islice(train_loader, 8))\n\n\ndef calibration_loop(module: nn.Module) -> None:\n    \"\"\"Feed a few representative batches through `module`.\"\"\"\n    with torch.no_grad():\n        for images, _ in calibration_batches:\n            module(images.to(device))\n\n\nptq_model = quantize(\n    copy.deepcopy(fused),\n    (example_input,),\n    forward_loop=calibration_loop,\n)\n\nptq_accuracy = accuracy(ptq_model, val_loader)\nprint(f\"INT8 after PTQ:        {ptq_accuracy:.2%}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Quantization-aware training\n\nCalling :func:`~embedl_deploy.quantize.quantize` **without** a\n``forward_loop`` is the QAT entry point. The stubs are inserted and\nconfigured, and their quantization parameters are left for training to\ndetermine rather than being measured from data.\n\n:func:`~embedl_deploy.quantize.prepare_qat` makes those parameters learnable\nand puts the model in training mode. From here the model trains like any\nother: the quantization parameters are in ``parameters()``, so the optimizer\nupdates them alongside the weights.\n\nA QAT run can start from PTQ instead, by passing the same\n``calibration_loop`` used above: the activation stubs then begin at ranges\nmeasured from data rather than at the seed. Pass ``freeze_weights=False``\nexplicitly if you do. The argument defaults to whether a ``forward_loop``\nwas given, so adding one silently freezes the weight scales at their\ncalibrated values, and QAT wants them tracking the weights it is changing.\n:func:`~embedl_deploy.quantize.prepare_export` freezes them at the end\neither way.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from embedl_deploy.quantize import prepare_export, prepare_qat\n\nqat_model = quantize(copy.deepcopy(fused), (example_input,))\nprepare_qat(qat_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "A fine-tune, not a training run: the model is already trained, and the job is\nto let it settle around the quantizer. The learning rate is accordingly about\na hundredth of what the original training used, over a small number of\nepochs.\n\nPartway through, the BatchNorm running statistics stop tracking, so they\nsettle rather than chase a forward pass whose numerics are still shifting.\nThe convention is to freeze early -- torchvision's reference recipe allows\nthree epochs out of ninety. Freezing is putting the layers in eval mode;\nnothing in the library does it, because where in the loop it happens is the\nwhole of the problem. ``nn.Module.train()`` recurses into every submodule,\nso a freeze does not survive one, and ``accuracy`` above is careful to\nrestore each submodule's mode rather than call ``train()`` on the root.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# ``SyncBatchNorm`` derives from a private base rather than from the three\n# concrete classes, so a model converted for distributed training needs it\n# named separately or it goes on tracking through the freeze.\nBATCH_NORMS = (\n    nn.BatchNorm1d,\n    nn.BatchNorm2d,\n    nn.BatchNorm3d,\n    nn.SyncBatchNorm,\n)\nFREEZE_BN_AFTER = 1\n\n\ndef freeze_bn_stats(module: nn.Module) -> None:\n    \"\"\"Stop every BatchNorm in `module` updating its running statistics.\n\n    The affine parameters go on training; only ``running_mean`` and\n    ``running_var`` are held still.\n\n    :param module:\n        The model whose BatchNorm layers to freeze, in place.\n    \"\"\"\n    for sub in module.modules():\n        if isinstance(sub, BATCH_NORMS):\n            sub.eval()\n\n\nEPOCHS = 3\n\noptimizer = torch.optim.SGD(\n    qat_model.parameters(), lr=1e-4, momentum=0.9, weight_decay=1e-4\n)\nscheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)\ncriterion = nn.CrossEntropyLoss()\n\nfor epoch in range(EPOCHS):\n    if epoch == FREEZE_BN_AFTER:\n        freeze_bn_stats(qat_model)\n\n    for images, labels in train_loader:\n        inputs, targets = images.to(device), labels.to(device)\n        optimizer.zero_grad()\n        criterion(qat_model(inputs), targets).backward()\n        optimizer.step()\n    scheduler.step()\n\n    print(f\"  epoch {epoch}: {accuracy(qat_model, val_loader):.2%}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Results\n\nThe three accuracies print below. Two things are worth knowing before\nreading them.\n\nINT8 costs this model nothing: PTQ scores about what float32 does, so there\nis no quantization loss here for QAT to recover. And most of what\nfine-tuning gains is not a quantization effect at all -- ImageNette is ten\nclasses scored against a 1000-class head, so a few hundred gradient steps\nbuy a large jump by teaching the model to stop considering the other 990.\nThe same run on the float model, with no quantizers anywhere, gains about as\nmuch.\n\nSo this is not a measurement of what QAT is worth. What it does show is that\nthe quantized model trains: gradients reach the weights through the\nstraight-through estimator, and the step sizes move with them. Whether QAT\nbuys accuracy over PTQ depends on the model, the precision and the budget,\nand is worth measuring on your own workload rather than inferring from this\none.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "qat_accuracy = accuracy(qat_model, val_loader)\nprint(f\"float32 baseline:      {float_accuracy:.2%}\")\nprint(f\"INT8 after PTQ:        {ptq_accuracy:.2%}\")\nprint(f\"INT8 after QAT:        {qat_accuracy:.2%}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Export\n\n:func:`~embedl_deploy.quantize.prepare_export` ends training: the learned\nquantization parameters become constants, the weight quantizers freeze, and\nthe model leaves training mode. It is the one-way door before export -- to\nevaluate mid-training, call ``eval()`` as the loop above does, not this.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "prepare_export(qat_model)\n\nOUT_DIR.mkdir(parents=True, exist_ok=True)\nonnx_path = OUT_DIR / \"resnet18_qat.onnx\"\ntorch.onnx.export(\n    qat_model,\n    (example_input,),\n    str(onnx_path),\n    dynamo=False,\n)\nprint(f\"wrote {onnx_path}\")"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}