# Copyright (C) 2026 Embedl AB

"""
Quantization-aware training a ResNet18
======================================

Post-training quantization measures a model's activation ranges from a handful
of batches and changes no weights. Quantization-aware training instead trains
the model with quantization simulated in the forward pass, so the weights adapt
to the quantizer -- and the quantizer's own step sizes are learned against the
task loss rather than measured from data.

This tutorial runs both on a pretrained ResNet18 over ImageNette and exports
the fine-tuned model to ONNX. It is a walk through the mechanics: which call
does what, and what state the model is in between them.

Install dependencies:

.. code-block:: bash

    pip install --upgrade --extra-index-url https://deploy.embedl.com/downloads/ \
        "embedl-deploy[tensorrt]"
    pip install torchvision onnx

The Embedl wheels come from the Embedl package index rather than PyPI, so the
install needs an Embedl Hub API key: put it in ``~/.netrc`` as the password for
``machine deploy.embedl.com`` with login ``hub``, or write the index URL as
``https://hub:<API_KEY>@deploy.embedl.com/downloads/``.

.. note::

   Fine-tuning needs a GPU to be practical. On CPU a single epoch over
   ImageNette takes about eight minutes.

This tutorial imports :download:`_imagenette_data.py
</tutorials/_imagenette_data.py>`, which the download buttons at the bottom of
this page do not bundle -- they ship this script alone. Fetch the companion
through that link and keep it in the same directory as the script.
"""

# %%
# Setup
# -----
#
# ImageNette is a ten-class subset of ImageNet. Its classes keep their original
# ImageNet indices, so a pretrained classifier can be evaluated on it without
# retraining the head -- the label remap below is the whole adaptation.

from pathlib import Path

import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torchvision.models import ResNet18_Weights, resnet18

torch.manual_seed(0)

try:
    from _imagenette_data import (
        IMAGENETTE_DIR,
        download_imagenette,
        remap,
    )
except ImportError:
    raise ImportError(
        "This tutorial requires _imagenette_data.py beside it, "
        "providing the utilities it does not restate. Download "
        "from the links in this tutorial's introduction, into this "
        "directory."
    ) from None


OUT_DIR = Path("artifacts/resnet18_qat")


download_imagenette()

# %%
# The model carries its own preprocessing transform. Using it rather than a
# hand-written ``Resize``/``CenterCrop`` pair guarantees the pixels the network
# sees match the ones it was trained on, which matters more than usual here:
# calibration and fine-tuning both measure the model through this pipeline.

weights = ResNet18_Weights.IMAGENET1K_V1
preprocess = weights.transforms()
model = resnet18(weights=weights).eval()

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)


def loader(
    split: str, *, shuffle: bool
) -> DataLoader[tuple[torch.Tensor, torch.Tensor]]:
    """Build a data loader over one ImageNette `split`.

    :param split:
        Either ``"train"`` or ``"val"``.
    :param shuffle:
        Whether to shuffle, which training needs and evaluation does not.
    :returns:
        A ``DataLoader`` yielding preprocessed batches with ImageNet labels.
    """
    dataset = torchvision.datasets.ImageFolder(
        str(IMAGENETTE_DIR / split),
        transform=preprocess,
        target_transform=remap,
    )
    return DataLoader(dataset, batch_size=32, shuffle=shuffle)


train_loader = loader("train", shuffle=True)
val_loader = loader("val", shuffle=False)

# %%
# Evaluation
# ----------
#
# One accuracy function, used for every number in this tutorial. Each model is
# measured the same way, so the comparisons at the end mean something.


def accuracy(
    module: nn.Module,
    data: DataLoader[tuple[torch.Tensor, torch.Tensor]],
) -> float:
    """Top-1 accuracy of `module` over `data`.

    The training mode of every submodule is restored on return, so measuring
    part-way through a run does not disturb it. Restoring is per submodule
    rather than one ``train()`` on the root, because ``train()`` recurses and
    would put back any BatchNorm the caller is holding in eval.

    :param module:
        The model to evaluate. Its training mode is left as it was found.
    :param data:
        The batches to evaluate over.
    :returns:
        The fraction of correctly classified samples.
    """
    was_training = {sub: sub.training for sub in module.modules()}
    module.eval()
    correct = 0
    total = 0
    try:
        with torch.no_grad():
            for images, labels in data:
                inputs, targets = images.to(device), labels.to(device)
                predicted = module(inputs).argmax(dim=1)
                correct += int((predicted == targets).sum())
                total += targets.numel()
    finally:
        for sub, training in was_training.items():
            sub.training = training
    return correct / total


# %%
# Transformation
# --------------
#
# :func:`~embedl_deploy.transform` rewrites the graph into the fused
# modules the backend expects -- here, folding each ``Conv2d`` and its
# ``BatchNorm2d`` and activation into one quantizable unit. Quantization
# always follows transformation; the fused boundaries are what the Q/DQ
# stubs attach to.

from embedl_deploy import transform
from embedl_deploy.backend import set_backend

set_backend("tensorrt")

example_input = torch.randn(1, 3, 224, 224, device=device)
fused = transform(model, (example_input,)).model

float_accuracy = accuracy(fused, val_loader)
print(f"float32 baseline:      {float_accuracy:.2%}")

# %%
# Post-training quantization
# --------------------------
#
# The comparison point. A ``forward_loop`` feeds a few batches through the
# model so each stub can observe the range of the activations reaching it;
# those ranges become the quantization scales. No weight is touched.
#
# Calibrating also bakes the weight scales into constant buffers, which ONNX
# export requires: ``freeze_weights`` follows ``forward_loop`` unless it is
# given, so passing one is enough.

import copy
import itertools

from embedl_deploy.quantize import quantize

calibration_batches = list(itertools.islice(train_loader, 8))


def calibration_loop(module: nn.Module) -> None:
    """Feed a few representative batches through `module`."""
    with torch.no_grad():
        for images, _ in calibration_batches:
            module(images.to(device))


ptq_model = quantize(
    copy.deepcopy(fused),
    (example_input,),
    forward_loop=calibration_loop,
)

ptq_accuracy = accuracy(ptq_model, val_loader)
print(f"INT8 after PTQ:        {ptq_accuracy:.2%}")

# %%
# Quantization-aware training
# ---------------------------
#
# Calling :func:`~embedl_deploy.quantize.quantize` **without** a
# ``forward_loop`` is the QAT entry point. The stubs are inserted and
# configured, and their quantization parameters are left for training to
# determine rather than being measured from data.
#
# :func:`~embedl_deploy.quantize.prepare_qat` makes those parameters learnable
# and puts the model in training mode. From here the model trains like any
# other: the quantization parameters are in ``parameters()``, so the optimizer
# updates them alongside the weights.
#
# A QAT run can start from PTQ instead, by passing the same
# ``calibration_loop`` used above: the activation stubs then begin at ranges
# measured from data rather than at the seed. Pass ``freeze_weights=False``
# explicitly if you do. The argument defaults to whether a ``forward_loop``
# was given, so adding one silently freezes the weight scales at their
# calibrated values, and QAT wants them tracking the weights it is changing.
# :func:`~embedl_deploy.quantize.prepare_export` freezes them at the end
# either way.

from embedl_deploy.quantize import prepare_export, prepare_qat

qat_model = quantize(copy.deepcopy(fused), (example_input,))
prepare_qat(qat_model)

# %%
# A fine-tune, not a training run: the model is already trained, and the job is
# to let it settle around the quantizer. The learning rate is accordingly about
# a hundredth of what the original training used, over a small number of
# epochs.
#
# Partway through, the BatchNorm running statistics stop tracking, so they
# settle rather than chase a forward pass whose numerics are still shifting.
# The convention is to freeze early -- torchvision's reference recipe allows
# three epochs out of ninety. Freezing is putting the layers in eval mode;
# nothing in the library does it, because where in the loop it happens is the
# whole of the problem. ``nn.Module.train()`` recurses into every submodule,
# so a freeze does not survive one, and ``accuracy`` above is careful to
# restore each submodule's mode rather than call ``train()`` on the root.

# ``SyncBatchNorm`` derives from a private base rather than from the three
# concrete classes, so a model converted for distributed training needs it
# named separately or it goes on tracking through the freeze.
BATCH_NORMS = (
    nn.BatchNorm1d,
    nn.BatchNorm2d,
    nn.BatchNorm3d,
    nn.SyncBatchNorm,
)
FREEZE_BN_AFTER = 1


def freeze_bn_stats(module: nn.Module) -> None:
    """Stop every BatchNorm in `module` updating its running statistics.

    The affine parameters go on training; only ``running_mean`` and
    ``running_var`` are held still.

    :param module:
        The model whose BatchNorm layers to freeze, in place.
    """
    for sub in module.modules():
        if isinstance(sub, BATCH_NORMS):
            sub.eval()


EPOCHS = 3

optimizer = torch.optim.SGD(
    qat_model.parameters(), lr=1e-4, momentum=0.9, weight_decay=1e-4
)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)
criterion = nn.CrossEntropyLoss()

for epoch in range(EPOCHS):
    if epoch == FREEZE_BN_AFTER:
        freeze_bn_stats(qat_model)

    for images, labels in train_loader:
        inputs, targets = images.to(device), labels.to(device)
        optimizer.zero_grad()
        criterion(qat_model(inputs), targets).backward()
        optimizer.step()
    scheduler.step()

    print(f"  epoch {epoch}: {accuracy(qat_model, val_loader):.2%}")

# %%
# Results
# -------
#
# The three accuracies print below. Two things are worth knowing before
# reading them.
#
# INT8 costs this model nothing: PTQ scores about what float32 does, so there
# is no quantization loss here for QAT to recover. And most of what
# fine-tuning gains is not a quantization effect at all -- ImageNette is ten
# classes scored against a 1000-class head, so a few hundred gradient steps
# buy a large jump by teaching the model to stop considering the other 990.
# The same run on the float model, with no quantizers anywhere, gains about as
# much.
#
# So this is not a measurement of what QAT is worth. What it does show is that
# the quantized model trains: gradients reach the weights through the
# straight-through estimator, and the step sizes move with them. Whether QAT
# buys accuracy over PTQ depends on the model, the precision and the budget,
# and is worth measuring on your own workload rather than inferring from this
# one.

qat_accuracy = accuracy(qat_model, val_loader)
print(f"float32 baseline:      {float_accuracy:.2%}")
print(f"INT8 after PTQ:        {ptq_accuracy:.2%}")
print(f"INT8 after QAT:        {qat_accuracy:.2%}")

# %%
# Export
# ------
#
# :func:`~embedl_deploy.quantize.prepare_export` ends training: the learned
# quantization parameters become constants, the weight quantizers freeze, and
# the model leaves training mode. It is the one-way door before export -- to
# evaluate mid-training, call ``eval()`` as the loop above does, not this.

prepare_export(qat_model)

OUT_DIR.mkdir(parents=True, exist_ok=True)
onnx_path = OUT_DIR / "resnet18_qat.onnx"
torch.onnx.export(
    qat_model,
    (example_input,),
    str(onnx_path),
    dynamo=False,
)
print(f"wrote {onnx_path}")
