#!/usr/bin/env python3 # Copyright (c) 2026 Eoin Jordan # SPDX-License-Identifier: Apache-2.0 """Put the measured numbers and a sheet of sample predictions into README.md. Reads train/out/pose_micro_scores.json (train/export_pose.py) and rewrites the part of README.md between the two "numbers" markers, so the model card always says what the published weights actually score. Also draws assets/samples.jpg: the fp32 model's answers on validation crops whose pictures may be redistributed, taken in a fixed shuffled order and not picked by how well they came out, with their sources in assets/CREDITS.md. python train/export_pose.py && python tools/make_card.py """ import argparse import json import pathlib import random import sys import numpy as np import torch from PIL import Image REPO = pathlib.Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO / "train")) from export_pose import OPEN_LICENSES, SCORES, test_picture # noqa: E402 from pose_model import PoseMicro, decode # noqa: E402 from pose_predict import draw # noqa: E402 from train_pose import DATA, STATE, load # noqa: E402 START, END = "", "" def row(name: str, s: dict) -> str: return (f"| {name} | {100 * s['pck_0.1']:.1f}% | {100 * s['pck_0.2']:.1f}% | {s['oks']:.3f} | " f"{100 * s['oks_0.5']:.1f}% | {s['mean_error_px']:.1f} px |") def numbers(s: dict) -> str: m, t, p, q = s["model"], s["training"], s["programs"], s.get("int8_program") ops = lambda names: ", ".join(n.split(".")[-2] for n in names) # noqa: E731 lines = [ START, f"**{m['parameters']:,} parameters, {m['multiply_adds'] / 1e6:.2f} million multiply-adds a picture.**", "", "| | fp32 | int8 |", "|---|---|---|", "| Program | `firmware/model/pose_micro.pte` | `firmware/model/pose_micro_cmsis_nn.pte` |", "| Kernels | ExecuTorch portable | CMSIS-NN, plain C path |", f"| Flash | {p['fp32']['bytes']:,} bytes | {p['int8']['bytes']:,} bytes |", f"| Working memory the runtime plans | {p['fp32']['planned_bytes']:,} bytes | {p['int8']['planned_bytes']:,} bytes |", f"| Operators | {ops(p['fp32']['operators'])} | {ops(p['int8']['operators'])} |", "| Picture goes in as | float, 0 to 1, one plane a channel | int8, pixel minus 128, channels together |", "", f"Scored on {s['validation_crops']:,} single-person crops of COCO val2017:", "", "| | PCK@0.1 | PCK@0.2 | OKS | Crops with OKS of 0.5 or more | Mean error, of 96 px |", "|---|---|---|---|---|---|", row("Average pose, whatever the picture", s["average_pose"]), row("PoseMicro fp32", s["fp32"]), row("PoseMicro int8", q["scores"] if q else s["int8"]), "", ] if q: a = q["against_pytorch"] lines += ["The int8 row is the int8 program itself, run on a PC on the kernels the firmware builds: ExecuTorch's " "Cortex-M operators on CMSIS-NN in plain C (`firmware/tests/host_int8`). Its output values are " f"{a['mean_steps']:.1f} steps of the int8 scale from the quantised model in PyTorch on average and " f"{a['largest_steps']} at most; the integer kernels round differently and the layers add up. " f"In PyTorch the quantised model scores PCK@0.1 of {100 * s['int8']['pck_0.1']:.1f}% and OKS of " f"{s['int8']['oks']:.3f}.", ""] else: lines += ["The int8 row is the quantised model in PyTorch. The int8 program itself was not run for this table " "(`firmware/tests/host_int8/build.sh` makes that possible).", ""] by = s["fp32"].get("pck_0.2_by_keypoint") if by: parts = {"head": ("nose", "left_eye", "right_eye", "left_ear", "right_ear")} parts.update({p + "s": (f"left_{p}", f"right_{p}") for p in ("shoulder", "elbow", "wrist", "hip", "knee", "ankle")}) lines += ["PCK@0.2 of the fp32 model by part of the body: " + ", ".join(f"{name} {100 * sum(by[k] for k in ks) / len(ks):.0f}%" for name, ks in parts.items()) + ".", ""] if t.get("minutes"): lines.append(f"These weights were trained for {t['minutes']:.0f} minutes on {t['threads']} CPU threads: " f"{t['epochs']:.1f} passes over {t['training_crops']:,} crops.") lines.append(END) return "\n".join(lines) def samples(state: pathlib.Path, data: pathlib.Path, out: pathlib.Path, count: int = 8) -> None: net = PoseMicro() net.load_state_dict(torch.load(state, map_location="cpu")) model = net.fused() val_x, val_k, meta = load("val", 0, data) order = [i for i, m in enumerate(meta) if m.get("license") in OPEN_LICENSES and (val_k[i, :, 2] > 0).sum() >= 12] random.Random(0).shuffle(order) order = order[:count] side = 192 sheet = Image.new("RGB", (side * (count // 2), side * 2)) credits = ["# Sample pictures", "", "The crops in `samples.jpg`, left to right and top to bottom, are from COCO val2017:", ""] for n, i in enumerate(order): picture = test_picture(np.asarray(val_x[i])) x = torch.from_numpy(picture.copy()).permute(2, 0, 1)[None].float() / 255.0 with torch.no_grad(): k = decode(model(x)[0].numpy()) sheet.paste(draw(Image.fromarray(picture), k, side), ((n % (count // 2)) * side, (n // (count // 2)) * side)) credits.append(f"{n + 1}. `{meta[i]['file']}`, {OPEN_LICENSES[meta[i]['license']]}, {meta[i].get('flickr_url') or 'cocodataset.org'}") out.parent.mkdir(parents=True, exist_ok=True) sheet.save(out, quality=90) (out.parent / "CREDITS.md").write_text("\n".join(credits) + "\n") print(f"wrote {out} and {out.parent / 'CREDITS.md'}") def main() -> None: p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--scores", type=pathlib.Path, default=SCORES) p.add_argument("--state-dict", type=pathlib.Path, default=STATE) p.add_argument("--data", type=pathlib.Path, default=DATA) p.add_argument("--readme", type=pathlib.Path, default=REPO / "README.md") p.add_argument("--samples", type=pathlib.Path, default=REPO / "assets" / "samples.jpg") args = p.parse_args() text = args.readme.read_text() if START not in text or END not in text: sys.exit(f"{args.readme} has no {START} ... {END} part") block = numbers(json.loads(args.scores.read_text())) args.readme.write_text(text[: text.index(START)] + block + text[text.index(END) + len(END):]) print(f"updated the numbers in {args.readme}") samples(args.state_dict, args.data, args.samples) if __name__ == "__main__": main()