|
| 1 | +# Copyright 2026 Mwaniki Njagi. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | +# |
| 7 | +# SPDX-License-Identifier: BSD-3-Clause |
| 8 | + |
| 9 | +""" |
| 10 | +Quantize a torchvision ImageNet classifier for the camera demo and lower it |
| 11 | +to an ExecuTorch program (.pte) with ESP-NN delegates. |
| 12 | +
|
| 13 | +Calibrates on an image folder, optionally fine-tunes with quantization-aware |
| 14 | +training (distillation from the float model, no labels needed), and reports |
| 15 | +top-1 accuracy of the lowered program as the board computes it. Also writes |
| 16 | +<output>.ops.txt, the CPU operators to select when building the runtime. |
| 17 | +
|
| 18 | + python export_model.py --calib-dir imagenette2-160/train \\ |
| 19 | + --eval-dir imagenette2-160/val --qat-epochs 5 --qat-lr 1e-3 \\ |
| 20 | + --output models/mobilenet_v3_small_224.pte |
| 21 | +
|
| 22 | +MobileNetV3-Small needs QAT; plain PTQ loses most of its accuracy. |
| 23 | +""" |
| 24 | + |
| 25 | +from __future__ import annotations |
| 26 | + |
| 27 | +import argparse |
| 28 | +import copy |
| 29 | +import random |
| 30 | +from pathlib import Path |
| 31 | + |
| 32 | +import torch |
| 33 | +import torch.nn.functional as F |
| 34 | +from executorch.backends.espressif import EspNNQuantizer, to_espnn_edge |
| 35 | +from executorch.backends.espressif.reference import ProgramEmulator |
| 36 | +from torchao.quantization.pt2e import ( |
| 37 | + disable_observer, |
| 38 | + move_exported_model_to_eval, |
| 39 | + move_exported_model_to_train, |
| 40 | +) |
| 41 | +from torchao.quantization.pt2e.quantize_pt2e import ( |
| 42 | + convert_pt2e, |
| 43 | + prepare_pt2e, |
| 44 | + prepare_qat_pt2e, |
| 45 | +) |
| 46 | + |
| 47 | +IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".bmp", ".webp"} |
| 48 | +# Imagenette folder names and their ImageNet-1k class indices. |
| 49 | +IMAGENETTE_TO_IMAGENET = { |
| 50 | + "n01440764": 0, |
| 51 | + "n02102040": 217, |
| 52 | + "n02979186": 482, |
| 53 | + "n03000684": 491, |
| 54 | + "n03028079": 497, |
| 55 | + "n03394916": 566, |
| 56 | + "n03417042": 569, |
| 57 | + "n03425413": 571, |
| 58 | + "n03445777": 574, |
| 59 | + "n03888257": 701, |
| 60 | +} |
| 61 | +MEAN = (0.485, 0.456, 0.406) |
| 62 | +STD = (0.229, 0.224, 0.225) |
| 63 | + |
| 64 | + |
| 65 | +def load_images(directory: Path, count: int, size: int, seed: int): |
| 66 | + from PIL import Image |
| 67 | + from torchvision import transforms |
| 68 | + |
| 69 | + transform = transforms.Compose( |
| 70 | + [ |
| 71 | + transforms.Resize(size * 256 // 224), |
| 72 | + transforms.CenterCrop(size), |
| 73 | + transforms.ToTensor(), |
| 74 | + transforms.Normalize(MEAN, STD), |
| 75 | + ] |
| 76 | + ) |
| 77 | + files = sorted( |
| 78 | + p for p in directory.rglob("*") if p.suffix.lower() in IMAGE_SUFFIXES |
| 79 | + ) |
| 80 | + if not files: |
| 81 | + raise SystemExit(f"no images found under {directory}") |
| 82 | + random.Random(seed).shuffle(files) |
| 83 | + images, labels = [], [] |
| 84 | + for path in files[:count]: |
| 85 | + images.append(transform(Image.open(path).convert("RGB"))) |
| 86 | + labels.append(IMAGENETTE_TO_IMAGENET.get(path.parent.name, -1)) |
| 87 | + return torch.stack(images), labels |
| 88 | + |
| 89 | + |
| 90 | +def qat_prepare(model, data, args): |
| 91 | + batch = min(args.qat_batch, len(data)) |
| 92 | + exported = torch.export.export( |
| 93 | + copy.deepcopy(model), |
| 94 | + (data[:2],), |
| 95 | + dynamic_shapes=({0: torch.export.Dim("batch", min=2, max=1024)},), |
| 96 | + strict=True, |
| 97 | + ).module() |
| 98 | + prepared = prepare_qat_pt2e(exported, EspNNQuantizer(is_qat=True)) |
| 99 | + parameters = [p for p in prepared.parameters() if p.is_floating_point()] |
| 100 | + for parameter in parameters: |
| 101 | + parameter.requires_grad_(True) |
| 102 | + steps = max(1, round(args.qat_epochs * max(1, len(data) // batch))) |
| 103 | + optimizer = torch.optim.SGD(parameters, lr=args.qat_lr, momentum=0.9) |
| 104 | + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, steps) |
| 105 | + generator = torch.Generator().manual_seed(args.seed) |
| 106 | + move_exported_model_to_train(prepared) |
| 107 | + with torch.no_grad(): |
| 108 | + for start in range(0, min(len(data), 16 * batch), batch): |
| 109 | + prepared(data[start : start + batch]) |
| 110 | + with torch.enable_grad(): |
| 111 | + for step in range(steps): |
| 112 | + if step == int(steps * 0.6): |
| 113 | + prepared.apply(disable_observer) |
| 114 | + inputs = data[torch.randint(0, len(data), (batch,), generator=generator)] |
| 115 | + if bool(torch.rand(1, generator=generator) < 0.5): |
| 116 | + inputs = inputs.flip(3) |
| 117 | + with torch.no_grad(): |
| 118 | + teacher = F.softmax(model(inputs), dim=1) |
| 119 | + loss = F.kl_div( |
| 120 | + F.log_softmax(prepared(inputs), dim=1), teacher, reduction="batchmean" |
| 121 | + ) |
| 122 | + optimizer.zero_grad() |
| 123 | + loss.backward() |
| 124 | + optimizer.step() |
| 125 | + scheduler.step() |
| 126 | + if step % max(1, steps // 10) == 0 or step + 1 == steps: |
| 127 | + print(f"QAT step {step + 1}/{steps} loss {loss.item():.4f}") |
| 128 | + move_exported_model_to_eval(prepared) |
| 129 | + for parameter in parameters: |
| 130 | + parameter.requires_grad_(False) |
| 131 | + return prepared |
| 132 | + |
| 133 | + |
| 134 | +def main() -> int: |
| 135 | + parser = argparse.ArgumentParser(description=__doc__) |
| 136 | + parser.add_argument("--model", default="mobilenet_v3_small") |
| 137 | + parser.add_argument("--size", type=int, default=224) |
| 138 | + parser.add_argument("--calib-dir", type=Path, required=True) |
| 139 | + parser.add_argument("--calib-samples", type=int, default=1024) |
| 140 | + parser.add_argument("--eval-dir", type=Path) |
| 141 | + parser.add_argument("--eval-samples", type=int, default=100) |
| 142 | + parser.add_argument("--qat-epochs", type=float, default=0.0) |
| 143 | + parser.add_argument("--qat-lr", type=float, default=1e-3) |
| 144 | + parser.add_argument("--qat-batch", type=int, default=16) |
| 145 | + parser.add_argument("--seed", type=int, default=0) |
| 146 | + parser.add_argument( |
| 147 | + "--output", type=Path, default=Path("models/mobilenet_v3_small_224.pte") |
| 148 | + ) |
| 149 | + args = parser.parse_args() |
| 150 | + |
| 151 | + from torchvision import models |
| 152 | + |
| 153 | + model = getattr(models, args.model)(weights="DEFAULT").eval() |
| 154 | + calibration, _ = load_images( |
| 155 | + args.calib_dir, args.calib_samples, args.size, args.seed |
| 156 | + ) |
| 157 | + example = (calibration[:1],) |
| 158 | + |
| 159 | + if args.qat_epochs > 0: |
| 160 | + prepared = qat_prepare(model, calibration, args) |
| 161 | + else: |
| 162 | + prepared = prepare_pt2e( |
| 163 | + torch.export.export(model, example, strict=True).module(), |
| 164 | + EspNNQuantizer(), |
| 165 | + ) |
| 166 | + with torch.no_grad(): |
| 167 | + for image in calibration: |
| 168 | + prepared(image.unsqueeze(0)) |
| 169 | + quantized = convert_pt2e(prepared) |
| 170 | + |
| 171 | + edge, report = to_espnn_edge(torch.export.export(quantized, example, strict=True)) |
| 172 | + print( |
| 173 | + f"{report['partitions']} ESP-NN partition(s), " |
| 174 | + f"{report['delegated_ops']} delegated operators, " |
| 175 | + f"{len(report['cpu_ops'])} on the CPU" |
| 176 | + ) |
| 177 | + |
| 178 | + if args.eval_dir is not None: |
| 179 | + images, labels = load_images( |
| 180 | + args.eval_dir, args.eval_samples, args.size, args.seed + 1 |
| 181 | + ) |
| 182 | + emulator = ProgramEmulator(edge.exported_program()) |
| 183 | + float_correct = device_correct = agree = 0 |
| 184 | + with torch.no_grad(): |
| 185 | + for image, label in zip(images, labels): |
| 186 | + image = image.unsqueeze(0) |
| 187 | + float_top1 = int(model(image).argmax()) |
| 188 | + device_top1 = int(emulator(image).to(torch.float32).argmax()) |
| 189 | + float_correct += int(float_top1 == label) |
| 190 | + device_correct += int(device_top1 == label) |
| 191 | + agree += int(float_top1 == device_top1) |
| 192 | + print( |
| 193 | + f"top-1 on {len(labels)} images: float {float_correct}, " |
| 194 | + f"int8 program {device_correct}, agreement {agree}" |
| 195 | + ) |
| 196 | + |
| 197 | + program = edge.to_executorch() |
| 198 | + plan = program.executorch_program.execution_plan[0] |
| 199 | + operators = sorted( |
| 200 | + f"{op.name}.{op.overload}" |
| 201 | + for op in plan.operators |
| 202 | + if not op.name.startswith("quantized_decomposed::") |
| 203 | + ) |
| 204 | + args.output.parent.mkdir(parents=True, exist_ok=True) |
| 205 | + args.output.write_bytes(program.buffer) |
| 206 | + ops_path = args.output.with_suffix(".ops.txt") |
| 207 | + ops_path.write_text(",".join(operators) + "\n") |
| 208 | + print(f"wrote {args.output} ({len(program.buffer)} bytes) and {ops_path}") |
| 209 | + return 0 |
| 210 | + |
| 211 | + |
| 212 | +if __name__ == "__main__": |
| 213 | + raise SystemExit(main()) |
0 commit comments