#!/usr/bin/env python3 # Copyright (c) 2026 Eoin Jordan # SPDX-License-Identifier: Apache-2.0 """Export PoseMicro for the firmware: fp32, int8 and the self-test picture. Reads train/out/pose_micro.pt (train/train_pose.py) and writes: firmware/model/pose_micro.pte fp32, portable kernels firmware/model/pose_micro_cmsis_nn.pte int8, cortex_m operators on CMSIS-NN, plain C path firmware/src/pose_test_input.h one validation crop, what both programs should answer for it and the int8 input and output scales train/out/pose_micro_scores.json both models scored on the val crops The int8 program takes the picture as int8 and answers in int8: the quantize operator at its input and the dequantize operator at its output are removed. The firmware hands over camera bytes, so the input is 27,648 bytes and not a 110 KB float picture, and the decoder turns back into floats only the 51 numbers it reads. What is left in the program is two operators. Both models are scored on the val2017 crops, so the cost of quantising shows next to the fp32 numbers, and both next to the score of answering the average pose whatever the picture, which is the number to beat. The fp32 program is run on this PC with ExecuTorch's Python runtime and must agree with PyTorch. The int8 program needs the Cortex-M kernels, which that runtime does not have: firmware/tests/host_int8/build.sh builds them and CMSIS-NN for the PC, and when its library is there the int8 program itself is run on every validation crop, scored, and its answer for the test picture is what the firmware's self-test expects. The integer kernels round differently from the quantised model in PyTorch and the layers add up, so the two agree on the pose and not on every output value; without the library the firmware's int8 self-test falls back on PyTorch's values and a loose limit. python train/train_pose.py python train/export_pose.py """ import argparse import json import pathlib import sys import numpy as np import torch sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from pose_model import (GRID, INPUT_SHAPE, KEYPOINTS, NUM_KEYPOINTS, OFFSET_SPAN, OUTPUTS, SIDE, THRESHOLD, # noqa: E402 PoseMicro, decode, multiply_adds, pose_line) from train_pose import CROP, DATA, LOG, MARGIN, OKS_SIGMAS, OUT, STATE, load, predict, report, score, views # noqa: E402 REPO = pathlib.Path(__file__).resolve().parents[1] NHWC = torch.channels_last SCORES = OUT / "pose_micro_scores.json" KERNELS = REPO / "firmware" / "tests" / "host_int8" / "build" / "libpose_cortex_m_host.so" # COCO licences that allow the test crop to be redistributed inside the firmware and this repository. # COCO licence ids of pictures that may be passed on with credit and no further condition. Share-alike # pictures (id 5) are left out, so nothing in this repository asks for a licence other than its own. OPEN_LICENSES = {4: "CC BY 2.0", 7: "no known copyright restrictions", 8: "US Government work"} def program_ops(program) -> list[str]: return sorted({str(n.target) for n in program.exported_program().graph.nodes if n.op == "call_function" and hasattr(n.target, "_schema")}) def planned_bytes(program) -> int: """Memory the runtime plans for the tensors of the program: its working RAM.""" return int(sum(program.executorch_program.execution_plan[0].non_const_buffer_sizes)) def write_pte(program, out: pathlib.Path) -> dict: ops = program_ops(program) print("operators in program:") for op in ops: print(f" {op}") out.parent.mkdir(parents=True, exist_ok=True) out.write_bytes(program.buffer) print(f"wrote {out} ({out.stat().st_size} bytes, {planned_bytes(program)} bytes of planned memory)") return {"bytes": out.stat().st_size, "planned_bytes": planned_bytes(program), "operators": ops} def export_fp32(model, out: pathlib.Path) -> dict: from executorch.exir import EdgeCompileConfig, to_edge_transform_and_lower with torch.no_grad(): exported = torch.export.export(model, (torch.zeros(*INPUT_SHAPE),)) program = to_edge_transform_and_lower( exported, compile_config=EdgeCompileConfig(_check_ir_validity=False) ).to_executorch() return write_pte(program, out) def quantise(model, calibration_u8: np.ndarray): """PT2E quantisation with the Cortex-M quantizer. Returns the converted module.""" from executorch.backends.cortex_m.quantizer.quantizer import CortexMQuantizer from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e example = (torch.zeros(*INPUT_SHAPE).to(memory_format=NHWC),) blank = np.zeros((1, NUM_KEYPOINTS, 3), np.float32) with torch.no_grad(): exported = torch.export.export(model, example, strict=False) try: captured = exported.module(check_guards=False) except TypeError: captured = exported.module() prepared = prepare_pt2e(captured, CortexMQuantizer()) for i in range(0, len(calibration_u8), 50): x, _ = views(calibration_u8[i:i + 50], np.repeat(blank, len(calibration_u8[i:i + 50]), 0), False) prepared(x.to(memory_format=NHWC)) return convert_pt2e(prepared) def qparams(converted, which: str): """(scale, zero point) of the first quantize or the last dequantize node.""" found = None for node in converted.graph.nodes: if node.op != "call_function": continue name = str(node.target) if which == "input" and "quantize_per_tensor" in name and "dequantize" not in name: return float(node.args[1]), int(node.args[2]) if which == "output" and "dequantize_per_tensor" in name: found = (float(node.args[1]), int(node.args[2])) if found is None: raise RuntimeError(f"the quantised graph has no {which} quantisation node") return found def export_int8(converted, out: pathlib.Path) -> dict: from executorch.backends.cortex_m.edge_compile_config import cortex_m_edge_compile_config from executorch.backends.cortex_m.passes.cortex_m_pass_manager import CortexMPassManager from executorch.backends.cortex_m.target_config import CortexM, CortexMTargetConfig from executorch.exir import to_edge from executorch.exir.passes.quantize_io_pass import QuantizeInputs, QuantizeOutputs # A Cortex-M0+ has neither DSP nor Helium: the plain C kernels of # CMSIS-NN, the ones that also compile for Xtensa. target = CortexMTargetConfig(cpu=CortexM.M0PLUS) example = (torch.zeros(*INPUT_SHAPE).to(memory_format=NHWC),) with torch.no_grad(): exported = torch.export.export(converted, example, strict=False) edge = to_edge(exported, compile_config=cortex_m_edge_compile_config()) edge = edge.transform([QuantizeInputs(edge, [0]), QuantizeOutputs(edge, [0])]) edge._edge_programs["forward"] = CortexMPassManager( edge.exported_program(), target_config=target ).transform() program = edge.to_executorch() print(f"CMSIS-NN code path: {target.backend.name}") return write_pte(program, out) def average_pose_score(kpts: np.ndarray, meta: list) -> dict: """The score of answering the average pose of the crops whatever the picture.""" labelled = kpts[:, :, 2] > 0 mean = np.array([kpts[labelled[:, j], j, :2].mean(0) for j in range(NUM_KEYPOINTS)]) * (SIDE / CROP) truth = kpts[:, :, :2] * (SIDE / CROP) d = np.linalg.norm(mean[None] - truth, axis=2) box = SIDE / MARGIN scale = np.array([m["scale"] for m in meta], np.float32) area = np.array([m["area"] for m in meta], np.float32) e = (d * (CROP / SIDE) / scale[:, None]) ** 2 / (2 * area[:, None] * (2 * OKS_SIGMAS[None]) ** 2) oks = (np.exp(-e) * labelled).sum(1) / labelled.sum(1).clip(min=1) return {"crops": int(len(kpts)), "pck_0.2": float((d <= 0.2 * box)[labelled].mean()), "pck_0.1": float((d <= 0.1 * box)[labelled].mean()), "oks": float(oks.mean()), "oks_0.5": float((oks >= 0.5).mean()), "mean_error_px": float(d[labelled].mean())} def pick_test(kpts, meta, out_fp32, out_int8) -> int: """A validation crop to bake into the firmware: freely licensed, a whole person, both models place its keypoints well, and no keypoint's heat is close to the threshold, so a last-digit difference on the board cannot change how many are found.""" best, best_error = None, 1e9 for i, m in enumerate(meta): if m.get("license") not in OPEN_LICENSES: continue labelled = kpts[i, :, 2] > 0 if labelled.sum() < 15: continue truth = kpts[i, :, :2] * (SIDE / CROP) errors = [] for o in (out_fp32[i], out_int8[i]): k = decode(o) if (k[:, 2] >= THRESHOLD).sum() < 15 or np.abs(k[:, 2] - THRESHOLD).min() < 0.03: errors = None break errors.append(np.linalg.norm(k[:, :2] * SIDE - truth, axis=1)[labelled].mean()) if errors and max(errors) < best_error: best, best_error = i, max(errors) if best is None: print("warning: no freely licensed validation crop has 15 keypoints found by both models;" " the self-test uses the freely licensed crop with the most labelled keypoints") open_ones = [i for i, m in enumerate(meta) if m.get("license") in OPEN_LICENSES] best = max(open_ones, key=lambda i: (kpts[i, :, 2] > 0).sum()) return best def c_array(values, per_line: int, fmt) -> list[str]: return [" " + ", ".join(fmt(v) for v in values[i:i + per_line]) + "," for i in range(0, len(values), per_line)] def at_keypoints(z: np.ndarray): """(cell of each keypoint's highest heat, [17][3] heat and the two offset outputs there).""" k = NUM_KEYPOINTS flat = z.reshape(OUTPUTS, GRID * GRID) cells = flat[:k].argmax(axis=1) idx = np.arange(k) return cells, np.stack([flat[idx, cells], flat[k + idx, cells], flat[2 * k + idx, cells]], axis=1) def write_header(picture_u8, crop_meta, z_fp32, z_int8, in_q, out_q, out: pathlib.Path, from_program: bool) -> None: """picture_u8 is [96][96][3]; z_* are the two models' outputs for it, [51][12][12]. z_int8 is what the int8 program itself answered on this PC when from_program is set, and otherwise the quantised model in PyTorch, which the integer kernels come near but do not match. """ k_fp32, k_int8 = decode(z_fp32), decode(z_int8) cells, values = at_keypoints(z_fp32) cells_q, values_q = at_keypoints(z_int8) lines = [ "/* Generated by train/export_pose.py. Do not edit.", " * One validation crop and the keypoints the two programs should give for it.", f" * COCO val2017 {crop_meta['file']}, annotation {crop_meta['annotation']},", f" * {crop_meta.get('flickr_url') or 'cocodataset.org'}", f" * licence: {OPEN_LICENSES.get(crop_meta.get('license'), 'see cocodataset.org')}", f" * fp32: {pose_line(k_fp32)}", f" * int8: {pose_line(k_int8)}", " */", "#pragma once", "", "#include ", "", f"#define POSE_TEST_FOUND {int((k_fp32[:, 2] >= THRESHOLD).sum())}", f"#define POSE_TEST_FOUND_Q {int((k_int8[:, 2] >= THRESHOLD).sum())}", "", "/* 1: the int8 values below are the int8 program's own answer, from a run on", " * a PC on the kernels the firmware builds (firmware/tests/host_int8).", " * 0: they are the quantised model in PyTorch, which the integer kernels", " * come near but do not match, so the self-test is loose. */", f"#define POSE_TEST_Q_FROM_PROGRAM {int(from_program)}", "/* Output steps the int8 self-test allows. */", f"#define POSE_TEST_Q_STEPS {1 if from_program else 24}", "", "/* The int8 program takes round(pixel / 255 / scale) + zero_point. */", f"#define POSE_Q_INPUT_SCALE {in_q[0]:.9e}f", f"#define POSE_Q_INPUT_ZERO_POINT {in_q[1]}", "/* The int8 program answers round(value / scale) + zero_point. */", f"#define POSE_Q_OUTPUT_SCALE {out_q[0]:.9e}f", f"#define POSE_Q_OUTPUT_ZERO_POINT {out_q[1]}", "", "/* RGB, row by row, three bytes a pixel: [96][96][3]. */", "static const uint8_t kPoseTestImage[96 * 96 * 3] = {", *c_array(picture_u8.flatten().tolist(), 24, str), "};", "", "/* fp32 model: the cell (row * 12 + column) where each keypoint's heat is", " * highest, then the heat and the two offset outputs in that cell. */", "static const uint8_t kPoseTestCell[17] = {", *c_array(cells.tolist(), 17, str), "};", "static const float kPoseTestValues[17 * 3] = {", *c_array(values.flatten().tolist(), 3, lambda v: f"{v:.5f}f"), "};", "", ("/* The int8 program run on a PC, same layout. */" if from_program else "/* Quantised model computed in PyTorch, same layout. */"), "static const uint8_t kPoseTestCellQ[17] = {", *c_array(cells_q.tolist(), 17, str), "};", "static const float kPoseTestValuesQ[17 * 3] = {", *c_array(values_q.flatten().tolist(), 3, lambda v: f"{v:.5f}f"), "};", "", ] out.write_text("\n".join(lines), newline="\n") print(f"wrote {out}") print(f" fp32: {pose_line(k_fp32)}") print(f" int8: {pose_line(k_int8)}") def test_picture(crop_u8: np.ndarray) -> np.ndarray: """The 96 x 96 picture the firmware is given for a stored crop, as bytes.""" x, _ = views(crop_u8[None], np.zeros((1, NUM_KEYPOINTS, 3), np.float32), False) return (x[0].permute(1, 2, 0) * 255).round().clamp(0, 255).to(torch.uint8).numpy() def check_on_host(pte: pathlib.Path, picture_u8: np.ndarray, expected: np.ndarray) -> float: """Run the fp32 program with the ExecuTorch Python runtime on the test picture.""" from executorch.runtime import Runtime x = (torch.from_numpy(picture_u8.copy()).permute(2, 0, 1)[None].float() / 255.0).contiguous() method = Runtime.get().load_program(pte).load_method("forward") got = method.execute([x])[0][0].numpy() diff = float(np.abs(got - expected).max()) print(f"{pte.name} on the host runtime: max |pte - pytorch| = {diff:.2e}") assert diff < 1e-3, "pte output drifted from PyTorch" return diff def int8_program(pte: pathlib.Path, kernels: pathlib.Path): """The int8 program, loaded on this PC with the kernels firmware/tests/host_int8/build.sh builds.""" import ctypes from executorch.runtime import Runtime runtime = Runtime.get() # loads the runtime library the kernels register with ctypes.CDLL(str(kernels), mode=ctypes.RTLD_GLOBAL) return runtime.load_program(pte).load_method("forward") def run_int8_program(method, x_int8: torch.Tensor) -> np.ndarray: """int8 output [n][51][12][12] of the program for int8 pictures [n][3][96][96].""" out = [method.execute([one[None].contiguous(memory_format=NHWC)])[0][0].numpy().copy() for one in x_int8] return np.stack(out) def predict_int8_program(method, crops_u8: np.ndarray, in_q) -> np.ndarray: """What the program answers for crops framed as in scoring, still in int8.""" out = [] blank = np.zeros((1, NUM_KEYPOINTS, 3), np.float32) for i in range(0, len(crops_u8), 256): x, _ = views(crops_u8[i:i + 256], np.repeat(blank, len(crops_u8[i:i + 256]), 0), False) q = torch.clamp(torch.round(x / in_q[0]) + in_q[1], -128, 127).to(torch.int8) out.append(run_int8_program(method, q)) return np.concatenate(out) def to_int8(z: np.ndarray, q) -> np.ndarray: return np.clip(np.round(z / q[0]) + q[1], -128, 127).astype(np.int32) def main() -> None: p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--state-dict", type=pathlib.Path, default=STATE) p.add_argument("--pte", type=pathlib.Path, default=REPO / "firmware" / "model" / "pose_micro.pte") p.add_argument("--pte-int8", type=pathlib.Path, default=REPO / "firmware" / "model" / "pose_micro_cmsis_nn.pte") p.add_argument("--header", type=pathlib.Path, default=REPO / "firmware" / "src" / "pose_test_input.h") p.add_argument("--scores", type=pathlib.Path, default=SCORES) p.add_argument("--data", type=pathlib.Path, default=DATA) p.add_argument("--val", type=int, default=0, help="validation crops to score (default: all)") p.add_argument("--calibration", type=int, default=500, help="training crops used to set the int8 ranges") p.add_argument("--int8-kernels", type=pathlib.Path, default=KERNELS, help="library from firmware/tests/host_int8/build.sh; with it the int8 program itself is run") p.add_argument("--width", type=int, default=32) p.add_argument("--rounds", type=int, default=6) args = p.parse_args() if not args.state_dict.exists(): sys.exit(f"{args.state_dict} not found: run train/train_pose.py first") net = PoseMicro(args.width, args.rounds) net.load_state_dict(torch.load(args.state_dict, map_location="cpu")) model = net.fused() val_x, val_k, val_meta = load("val", args.val, args.data) train_x, _, _ = load("train", args.calibration, args.data) print("\n== average pose, whatever the picture ==") baseline = average_pose_score(val_k, val_meta) print(report(baseline)) out_fp32 = predict(model, val_x, nhwc=False) s_fp32 = score(out_fp32, val_k, val_meta) print("\n== fp32 ==") print(report(s_fp32)) f_fp32 = export_fp32(model, args.pte) print("\n== int8 ==") converted = quantise(model.to(memory_format=NHWC), np.asarray(train_x[: args.calibration])) out_int8 = predict(converted, val_x, nhwc=True) s_int8 = score(out_int8, val_k, val_meta) print(report(s_int8)) f_int8 = export_int8(converted, args.pte_int8) i = pick_test(val_k, val_meta, out_fp32, out_int8) picture = test_picture(np.asarray(val_x[i])) # The header and the host check use the picture as bytes, exactly as the firmware has it. x = torch.from_numpy(picture.copy()).permute(2, 0, 1)[None].float() / 255.0 with torch.no_grad(): z_fp32 = model.to(memory_format=torch.contiguous_format)(x)[0].numpy() z_int8 = converted(x.to(memory_format=NHWC))[0].numpy() in_q, out_q = qparams(converted, "input"), qparams(converted, "output") program, z_test = None, z_int8 if args.int8_kernels.exists(): print("\n== int8, the program itself on CMSIS-NN built for this PC ==") method = int8_program(args.pte_int8, args.int8_kernels) q_program = predict_int8_program(method, val_x, in_q) s_program = score((q_program.astype(np.float32) - out_q[1]) * out_q[0], val_k, val_meta) print(report(s_program)) steps = np.abs(q_program.astype(np.int32) - to_int8(out_int8, out_q)) print(f"against the quantised model in PyTorch: {100 * (steps == 0).mean():.1f}% of output values identical, " f"{steps.mean():.2f} steps apart on average, {steps.max()} at most") if s_program["pck_0.1"] < s_int8["pck_0.1"] - 0.02: sys.exit("the int8 program scores well under the quantised model in PyTorch: something is wrong with it") # The test picture goes in as the firmware gives it: bytes through a 256-entry table. table = np.clip(np.round(np.arange(256) / 255.0 / in_q[0]) + in_q[1], -128, 127).astype(np.int8) q_test = run_int8_program(method, torch.from_numpy(table[picture]).permute(2, 0, 1)[None])[0] z_test = (q_test.astype(np.float32) - out_q[1]) * out_q[0] program = { "scores": s_program, "kernels": "ExecuTorch cortex_m operators on CMSIS-NN in plain C, built for the PC", "against_pytorch": {"largest_steps": int(steps.max()), "mean_steps": float(steps.mean()), "share_identical": float((steps == 0).mean())}, } else: print(f"\nint8 program not run here: no {args.int8_kernels} (sh firmware/tests/host_int8/build.sh builds it)") write_header(picture, val_meta[i], z_fp32, z_test, in_q, out_q, args.header, program is not None) for name, z in (("fp32", z_fp32), ("int8", z_test)): margin = float(np.abs(decode(z)[:, 2] - THRESHOLD).min()) print(f" {name}: the heat nearest the threshold of {THRESHOLD} is {margin:.3f} from it") if margin < 0.005: print(" warning: that is close; the number of keypoints found in the self-test may differ on a board") diff = check_on_host(args.pte, picture, z_fp32) log_file = args.state_dict.with_name(LOG.name) log = json.loads(log_file.read_text()) if log_file.exists() else {} args.scores.parent.mkdir(parents=True, exist_ok=True) args.scores.write_text(json.dumps({ "model": {"width": args.width, "rounds": args.rounds, "parameters": sum(q.numel() for q in net.parameters()), "multiply_adds": multiply_adds(net)}, "training": {k: log.get(k) for k in ("training_crops", "epochs", "minutes", "threads", "batch", "lr")}, "validation_crops": len(val_x), "average_pose": baseline, "fp32": s_fp32, "int8": s_int8, "int8_program": program, "programs": {"fp32": f_fp32, "int8": f_int8}, "int8_input": {"scale": in_q[0], "zero_point": in_q[1]}, "int8_output": {"scale": out_q[0], "zero_point": out_q[1]}, "host_check_max_abs_diff": diff, "test_picture": {k: val_meta[i].get(k) for k in ("file", "annotation", "flickr_url", "license")}, }, indent=1)) print(f"wrote {args.scores}") if __name__ == "__main__": main()