File size: 5,427 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# 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)