File size: 3,807 Bytes
ce7fc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
# Copyright (c) 2026 Eoin Jordan
# SPDX-License-Identifier: Apache-2.0
"""Check that the firmware decodes as Python does.

Builds firmware/src/pose_decode.h into a small program with the host's g++
and feeds it network outputs in the three forms the firmware meets: float
with one plane per channel (the fp32 program), and float and int8 with the
channels together (the int8 program gives the last). What comes back must be
what decode() in train/pose_model.py gives.

    python firmware/tests/test_pose_decode.py            # random outputs
    python firmware/tests/test_pose_decode.py --pt train/out/pose_micro.pt   # the model's own, on noise
"""

import argparse
import pathlib
import struct
import subprocess
import sys
import tempfile

import numpy as np

HERE = pathlib.Path(__file__).resolve().parent
REPO = HERE.parents[1]
sys.path.insert(0, str(REPO / "train"))
from pose_model import GRID, KEYPOINTS, NUM_KEYPOINTS, OUTPUTS, THRESHOLD, decode  # noqa: E402


def run(binary: pathlib.Path, tmp: pathlib.Path, z: np.ndarray, int8: bool, nhwc: bool, scale: float, zero: int):
    data = z.transpose(1, 2, 0) if nhwc else z
    with open(tmp / "out.bin", "wb") as f:
        f.write(struct.pack("<iifi", int(int8), int(nhwc), scale, zero))
        f.write(np.ascontiguousarray(data, np.int8 if int8 else np.float32).tobytes())
    lines = subprocess.run([str(binary), str(tmp / "out.bin")], check=True, capture_output=True, text=True).stdout.split("\n")
    return int(lines[0]), np.array([[float(v) for v in line.split()] for line in lines[1:1 + NUM_KEYPOINTS]], np.float32)


def main() -> int:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--pt", type=pathlib.Path, help="take the outputs from this trained model")
    p.add_argument("--count", type=int, default=50)
    args = p.parse_args()

    rng = np.random.default_rng(0)
    if args.pt:
        import torch
        from pose_model import PoseMicro

        net = PoseMicro()
        net.load_state_dict(torch.load(args.pt, map_location="cpu"))
        with torch.no_grad():
            outputs = net.eval()(torch.rand(args.count, 3, 96, 96)).numpy()
    else:
        outputs = rng.normal(0.1, 0.3, (args.count, OUTPUTS, GRID, GRID)).astype(np.float32)

    with tempfile.TemporaryDirectory() as d:
        tmp = pathlib.Path(d)
        binary = tmp / "decode"
        subprocess.run(["g++", "-std=c++17", "-O1", "-Wall", "-Werror", "-I", str(REPO / "firmware" / "src"),
                        str(HERE / "test_pose_decode.cpp"), "-o", str(binary)], check=True)
        worst = 0.0
        for z in outputs:
            want = decode(z)
            scale = float(np.abs(z).max() / 127)
            q = np.clip(np.round(z / scale) - 3, -128, 127).astype(np.int8)   # zero point -3
            want_q = decode((q.astype(np.float32) + 3) * scale)
            for name, got, ref in (
                ("float NCHW", run(binary, tmp, z, False, False, 0.0, 0), want),
                ("float NHWC", run(binary, tmp, z, False, True, 0.0, 0), want),
                ("int8 NHWC", run(binary, tmp, q, True, True, scale, -3), want_q),
            ):
                found, k = got
                diff = float(np.abs(k - ref).max())
                worst = max(worst, diff)
                if diff > 1e-4 or found != int((ref[:, 2] >= THRESHOLD).sum()):
                    print(f"FAIL: {name}: the firmware decoder differs from Python by {diff:.2e}")
                    return 1
    print(f"firmware decoder matches Python on {len(outputs)} outputs in 3 forms "
          f"({NUM_KEYPOINTS} keypoints each, {KEYPOINTS[0]} to {KEYPOINTS[-1]}); largest difference {worst:.1e}")
    return 0


if __name__ == "__main__":
    sys.exit(main())