pose-micro / train /pose_model.py
eoinedge's picture
PoseMicro from GitHub run 3
ce7fc72 verified
Raw History Blame Contribute Delete
5.43 kB
# Copyright (c) 2026 Eoin Jordan
# SPDX-License-Identifier: Apache-2.0
"""PoseMicro: single-person keypoints for microcontrollers.
A 96 x 96 RGB picture of one person goes in and the 17 COCO keypoints come
out. The network is a stack of plain and depthwise convolutions, the same
operators as BrickNet, so it runs on the same kernels: fp32 on ExecuTorch's
portable ones and int8 on CMSIS-NN.
It reduces the picture by a factor of eight and answers on the 12 x 12 grid,
with 51 numbers a cell:
[0:17] heat about 1 in the cell that holds the keypoint, 0 elsewhere
[17:34] dx where in that cell, as (x - cell centre) / 2 cell widths
[34:51] dy the same down the picture
Decoding is one argmax per keypoint and two additions, with no exponential,
so it costs nothing on the device. The firmware does the same decoding in
firmware/src/pose_decode.h; keep the two in step, together with the
constants below.
The layer widths come from what the board can do: BrickNet's 1.3 million
multiply-adds take 60 ms in int8 on the XIAO ESP32S3, and this network has
7.0 million.
"""
import numpy as np
import torch
import torch.nn as nn
SIDE = 96
GRID = 12
STRIDE = SIDE // GRID
INPUT_SHAPE = (1, 3, SIDE, SIDE)
NUM_KEYPOINTS = 17
OUTPUTS = 3 * NUM_KEYPOINTS
OFFSET_SPAN = 2.0 # an offset output of 1.0 is this many cell widths
KEYPOINTS = (
"nose", "left_eye", "right_eye", "left_ear", "right_ear",
"left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
"left_wrist", "right_wrist", "left_hip", "right_hip",
"left_knee", "right_knee", "left_ankle", "right_ankle",
)
# What a mirrored picture turns each keypoint into.
MIRROR = (0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15)
SKELETON = (
(5, 7), (7, 9), (6, 8), (8, 10), (5, 6), (5, 11), (6, 12), (11, 12),
(11, 13), (13, 15), (12, 14), (14, 16), (0, 1), (0, 2), (1, 3), (2, 4),
)
# Decoding. A keypoint counts as found when its heat reaches this.
THRESHOLD = 0.3
def conv_bn(cin: int, cout: int, kernel: int, stride: int, groups: int = 1) -> nn.Sequential:
return nn.Sequential(
nn.Conv2d(cin, cout, kernel, stride, kernel // 2, groups=groups, bias=False),
nn.BatchNorm2d(cout),
nn.ReLU(),
)
class PoseMicro(nn.Module):
"""Pixels scaled to 0..1 in, (N, 51, 12, 12) out."""
def __init__(self, width: int = 32, rounds: int = 6) -> None:
super().__init__()
w = width
layers = [
conv_bn(3, w // 2, 3, 2), # 96 -> 48
conv_bn(w // 2, w // 2, 3, 2, w // 2), # 48 -> 24, depthwise
conv_bn(w // 2, w, 1, 1),
conv_bn(w, w, 3, 1, w), # depthwise, once more at 24 x 24
conv_bn(w, w, 1, 1),
conv_bn(w, w, 3, 2, w), # 24 -> 12, depthwise
conv_bn(w, 2 * w, 1, 1),
]
# Rounds at 12 x 12: cheap there, and each widens what a cell sees by
# two cells. A wrist is placed by the elbow and shoulder it hangs from,
# so a cell has to see most of the person.
for _ in range(rounds):
layers += [conv_bn(2 * w, 2 * w, 3, 1, 2 * w), conv_bn(2 * w, 2 * w, 1, 1)]
self.features = nn.Sequential(*layers)
self.head = nn.Conv2d(2 * w, OUTPUTS, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.head(self.features(x))
def fused(self) -> "PoseMicro":
"""A copy for export with every batch norm folded into its convolution."""
import copy
from torch.nn.utils.fusion import fuse_conv_bn_eval
net = copy.deepcopy(self).eval()
for i, block in enumerate(net.features):
net.features[i] = nn.Sequential(fuse_conv_bn_eval(block[0], block[1]), nn.ReLU())
return net
def multiply_adds(model: nn.Module) -> int:
"""Multiply-adds of one forward pass."""
total = 0
side = SIDE
for m in model.modules():
if isinstance(m, nn.Conv2d):
side = side // m.stride[0]
total += side * side * m.out_channels * (m.in_channels // m.groups) * m.kernel_size[0] * m.kernel_size[1]
return total
def decode(out: np.ndarray) -> np.ndarray:
"""(51, 12, 12) network output to [17][3]: x and y as fractions of the picture
(0..1 from the left and from the top) and the heat of the cell they came from."""
k = NUM_KEYPOINTS
heat = out[:k].reshape(k, -1)
cell = heat.argmax(axis=1)
gy, gx = np.divmod(cell, GRID)
idx = np.arange(k)
dx = out[k:2 * k].reshape(k, -1)[idx, cell] * OFFSET_SPAN
dy = out[2 * k:].reshape(k, -1)[idx, cell] * OFFSET_SPAN
x = (gx + 0.5 + dx) / GRID
y = (gy + 0.5 + dy) / GRID
return np.stack([x, y, heat[idx, cell]], axis=1).astype(np.float32)
def pose_line(kpts: np.ndarray, ms: int | None = None, threshold: float = THRESHOLD) -> str:
"""The line the firmware prints for a frame: POSE n=<found> then x y heat for all 17,
as hundredths of the picture (and of the heat), in the order of KEYPOINTS."""
found = int((kpts[:, 2] >= threshold).sum())
parts = [f"POSE n={found}"]
for x, y, s in kpts:
parts.append(f"{int(round(100 * float(np.clip(x, 0, 1))))},{int(round(100 * float(np.clip(y, 0, 1))))},"
f"{int(round(100 * float(np.clip(s, 0, 1))))}")
if ms is not None:
parts.append(f"ms={ms}")
return " ".join(parts)