/* Copyright (c) 2026 Eoin Jordan * SPDX-License-Identifier: Apache-2.0 * * One person's pose from a 96 x 96 picture, on a microcontroller. * * PoseMicro (train/pose_model.py) turns a 96 x 96 colour picture of one * person into the 17 COCO keypoints. They go out on the console, one line a * frame: * * POSE n=15 52,18,93 55,16,90 49,16,91 ... ms= * * n keypoints found (heat at or over the threshold: 0.30 unless you change * it), then x,y,heat of all 17 in COCO * order (nose, eyes, ears, shoulders, elbows, wrists, hips, knees, ankles; * left before right), then the time of the inference. x runs from 0 at the * left to 100 at the right of the picture, y from 0 at the top to 100 at * the bottom, and heat from 0 to 100. * * 1. Load the programs embedded in flash: fp32 on the portable kernels and, * unless built with -DAPP_CMSIS_NN=OFF, int8 on the CMSIS-NN kernels. * 2. Run each on a picture baked into pose_test_input.h and compare what it * answers at the keypoints with what the export expects. * 3. With CONFIG_APP_CAMERA, find the pose in every camera frame, and with * CONFIG_APP_SCREEN show the frame with the skeleton on it. * * A host can ask for things by sending one character on the console: * c the next frame as the model gets it, before its POSE line * s the next screen as it is drawn * i the start-up report again: sizes, self-tests and timings * t one frame from the embedded picture, not the camera * + raise the heat a keypoint needs on camera frames by 0.05 * - lower it by 0.05 (CONFIG_APP_POSE_THRESHOLD_PERCENT is where it starts) * * The runner is the one of the brick detector in * executorch-zephyr-xiao-esp32s3 (firmware/src/lego.cpp); what differs is * that the int8 program also answers in int8, so nothing is turned back into * floats but the 51 numbers the decoder reads. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef CONFIG_ESP_SPIRAM #include #endif #include #include #include #include #include #include "model_pte.h" /* generated: model_pte[], model_pte_len */ #include "pose_decode.h" #include "pose_test_input.h" /* generated by train/export_pose.py */ #ifdef APP_CMSIS_NN #include "model_q_pte.h" /* generated: model_q_pte[], model_q_pte_len */ #endif #ifdef CONFIG_APP_CAMERA #include "camera.h" #endif #ifdef CONFIG_APP_SCREEN #include "screen.h" #endif using executorch::aten::ScalarType; using executorch::aten::Tensor; using executorch::aten::TensorImpl; using executorch::extension::BufferDataLoader; using executorch::runtime::Error; using executorch::runtime::EValue; using executorch::runtime::HierarchicalAllocator; using executorch::runtime::MemoryAllocator; using executorch::runtime::MemoryManager; using executorch::runtime::Method; using executorch::runtime::MethodMeta; using executorch::runtime::Program; using executorch::runtime::Result; using executorch::runtime::Span; using executorch::runtime::TensorInfo; using pose::kCells; using pose::kKeypoints; using pose::kSide; #ifdef APP_CMSIS_NN /* The int8 program works in internal RAM. */ alignas(16) static uint8_t q_method_pool[CONFIG_APP_POSE_METHOD_POOL_SIZE]; alignas(16) static uint8_t q_temp_pool[CONFIG_APP_POSE_TEMP_POOL_SIZE]; #endif alignas(16) static uint8_t temp_pool[CONFIG_APP_POSE_TEMP_POOL_SIZE]; namespace { struct Found { pose::Keypoint k[kKeypoints]; int n; /* keypoints with heat at or over the threshold */ float threshold; /* the threshold n was counted with */ uint32_t us; }; /* Memory for things too large for the internal RAM: the PSRAM of the * module when it is enabled, the heap otherwise. The fp32 program needs * about 300 KB for a 96 x 96 x 3 float picture and its first feature map. */ uint8_t *big_alloc(size_t size) { #ifdef CONFIG_ESP_SPIRAM return static_cast(shared_multi_heap_aligned_alloc(SMH_REG_ATTR_EXTERNAL, 16, size)); #else return static_cast(k_aligned_alloc(16, size)); #endif } /* One loaded program with its memory, ready to run. */ class Runner { public: Runner(const char *name, const uint8_t *pte, size_t pte_len, uint8_t *method_mem, size_t method_size, uint8_t *temp_mem, size_t temp_size) : name(name), pte_len(pte_len), loader_(pte, pte_len), method_allocator_(method_size, method_mem), temp_allocator_(temp_size, temp_mem) { } Error init(); void info() const; /* A 96 x 96 picture in, as RGB bytes or, when rgb888 is null, as RGB565 * in host order. The program's answer, still in its own memory and good * until the next run, and the time of execute() out. */ Error run(const uint8_t *rgb888, const uint16_t *rgb565, pose::Output *out, uint32_t *us); const char *const name; const size_t pte_len; private: BufferDataLoader loader_; MemoryAllocator method_allocator_; MemoryAllocator temp_allocator_; std::vector> planned_spans_; Program *program_ = nullptr; Method *method_ = nullptr; Tensor *input_tensor_ = nullptr; void *input_ = nullptr; size_t planned_ = 0; bool input_int8_ = false; bool input_nhwc_ = false; int8_t lut_[256]; }; /* True when a four-dimensional tensor keeps its data as rows of pixels with * the channels together (NHWC) and not as one plane per channel (NCHW). */ template bool channels_last(const T &dim_order) { return dim_order.size() == 4 && dim_order[1] == 2 && dim_order[2] == 3 && dim_order[3] == 1; } Error Runner::init() { Result program_res = Program::load(&loader_); if (!program_res.ok()) { ET_LOG(Error, "%s: Program::load failed: 0x%x", name, (unsigned)program_res.error()); return program_res.error(); } program_ = new Program(std::move(program_res.get())); const char *method_name = program_->get_method_name(0).get(); Result meta = program_->method_meta(method_name); if (!meta.ok()) { return meta.error(); } size_t planned = 0; for (size_t id = 0; id < meta->num_memory_planned_buffers(); ++id) { size_t size = static_cast(meta->memory_planned_buffer_size(id).get()); uint8_t *buf = static_cast(method_allocator_.allocate(size, 16)); if (buf == nullptr) { ET_LOG(Error, "%s: planned buffer %zu (%zu B) does not fit the method pool", name, id, size); return Error::MemoryAllocationFailed; } planned += size; planned_spans_.push_back({buf, size}); } auto *planned_memory = new HierarchicalAllocator({planned_spans_.data(), planned_spans_.size()}); auto *memory_manager = new MemoryManager(&method_allocator_, planned_memory, &temp_allocator_); Result method_res = program_->load_method(method_name, memory_manager); if (!method_res.ok()) { ET_LOG(Error, "%s: load_method(%s) failed: 0x%x", name, method_name, (unsigned)method_res.error()); return method_res.error(); } method_ = new Method(std::move(method_res.get())); /* The fp32 program takes floats, one plane per channel. The int8 one * takes the picture as int8 with the channels together: its quantize * operator was removed at export, so the bytes go in through a table. */ Result in_meta = meta->input_tensor_meta(0); if (!in_meta.ok()) { return in_meta.error(); } input_int8_ = in_meta->scalar_type() == ScalarType::Char; input_nhwc_ = channels_last(in_meta->dim_order()); const size_t want = kSide * kSide * 3 * (input_int8_ ? 1 : sizeof(float)); if (in_meta->nbytes() != want || (!input_int8_ && in_meta->scalar_type() != ScalarType::Float)) { ET_LOG(Error, "%s: the input is not a 96 x 96 x 3 picture", name); return Error::InvalidProgram; } /* The picture is written here and copied into the program by * set_input(), so this buffer need not be in fast memory. */ input_ = big_alloc(in_meta->nbytes()); if (input_ == nullptr) { return Error::MemoryAllocationFailed; } for (int v = 0; v < 256; ++v) { float q = roundf(static_cast(v) / 255.f / POSE_Q_INPUT_SCALE) + POSE_Q_INPUT_ZERO_POINT; lut_[v] = static_cast(fminf(fmaxf(q, -128.f), 127.f)); } auto *impl = new TensorImpl( in_meta->scalar_type(), in_meta->sizes().size(), const_cast(in_meta->sizes().data()), input_, const_cast(in_meta->dim_order().data())); input_tensor_ = new Tensor(impl); planned_ = planned; return Error::Ok; } void Runner::info() const { printk("%-9s %6u bytes in flash, %6u planned, pool %6u of %6u bytes used, %s %s input\n", name, (unsigned)pte_len, (unsigned)planned_, (unsigned)method_allocator_.used_size(), (unsigned)method_allocator_.size(), input_int8_ ? "int8" : "float", input_nhwc_ ? "NHWC" : "NCHW"); } Error Runner::run(const uint8_t *rgb888, const uint16_t *rgb565, pose::Output *result, uint32_t *us) { const int plane = kSide * kSide; int8_t *in_q = static_cast(input_); float *in_f = static_cast(input_); for (int i = 0; i < plane; ++i) { uint8_t px[3]; if (rgb888 != nullptr) { px[0] = rgb888[3 * i]; px[1] = rgb888[3 * i + 1]; px[2] = rgb888[3 * i + 2]; } else { /* Fill the low bits, so white is 255 and not 248. */ const uint16_t v = rgb565[i]; const uint8_t r = (v >> 11) & 0x1f, g = (v >> 5) & 0x3f, b = v & 0x1f; px[0] = static_cast((r << 3) | (r >> 2)); px[1] = static_cast((g << 2) | (g >> 4)); px[2] = static_cast((b << 3) | (b >> 2)); } for (int c = 0; c < 3; ++c) { const int at = input_nhwc_ ? i * 3 + c : c * plane + i; if (input_int8_) { in_q[at] = lut_[px[c]]; } else { in_f[at] = static_cast(px[c]) * (1.f / 255.f); } } } Error err = method_->set_input(EValue(*input_tensor_), 0); if (err != Error::Ok) { ET_LOG(Error, "%s: set_input failed: 0x%x", name, (unsigned)err); return err; } uint32_t t0 = k_cycle_get_32(); err = method_->execute(); uint32_t t1 = k_cycle_get_32(); if (err != Error::Ok) { ET_LOG(Error, "%s: execute failed: 0x%x", name, (unsigned)err); return err; } *us = k_cyc_to_us_floor32(t1 - t0); const EValue &out = method_->get_output(0); if (!out.isTensor()) { return Error::InvalidState; } const Tensor &t = out.toTensor(); const bool is_int8 = t.scalar_type() == ScalarType::Char; if (t.numel() != pose::kOutputs || (!is_int8 && t.scalar_type() != ScalarType::Float)) { ET_LOG(Error, "%s: the output is not 51 x 12 x 12 int8 or float", name); return Error::InvalidState; } /* Left where it is: the decoder reads 17 x 144 numbers to find the * keypoints and 34 more to place them, whatever the layout and type. */ result->data = t.const_data_ptr(); result->is_int8 = is_int8; result->channels_last = channels_last(t.dim_order()); result->scale = POSE_Q_OUTPUT_SCALE; result->zero_point = POSE_Q_OUTPUT_ZERO_POINT; return Error::Ok; } /* Hundredths without the float formatter, held to 0..100. */ int hundredths(float v) { int h = static_cast(v * 100.f + 0.5f); return h < 0 ? 0 : (h > 100 ? 100 : h); } void print_pose(const Found &res) { printk("POSE n=%d", res.n); for (int i = 0; i < kKeypoints; ++i) { printk(" %d,%d,%d", hundredths(res.k[i].x), hundredths(res.k[i].y), hundredths(res.k[i].heat)); } printk(" ms=%u\n", (res.us + 500) / 1000); } void decode(const pose::Output &out, uint32_t us, float threshold, Found *res) { pose::decode(out, res->k); res->n = pose::found(res->k, threshold); res->threshold = threshold; res->us = us; } /* Run the embedded picture, compare with the reference and time it. * `cells` says where PyTorch found each keypoint and `expected` what it * answered there: heat, offset across, offset down. Returns the average time * of an inference in microseconds, 0 on failure. */ /* expected_found below 0: the number of keypoints found is not part of the test. */ uint32_t self_test(Runner &runner, const uint8_t *cells, const float *expected, int expected_found, float tolerance, const char *reference, Found *res) { pose::Output out = {}; uint32_t us = 0; if (runner.run(kPoseTestImage, nullptr, &out, &us) != Error::Ok) { printk("%s: FAIL: inference\n", runner.name); return 0; } float max_diff = 0.f; for (int k = 0; k < kKeypoints; ++k) { for (int part = 0; part < 3; ++part) { const float got = pose::value(out, part * kKeypoints + k, cells[k]); max_diff = fmaxf(max_diff, fabsf(got - expected[3 * k + part])); } } /* Always the threshold the export counted with, whatever the camera's is. */ decode(out, us, pose::kThreshold, res); printk("\n%s self-test: embedded picture, against %s\n", runner.name, reference); printk(" "); print_pose(*res); if (expected_found >= 0) { printk(" found %d keypoints, expected %d\n", res->n, expected_found); } printk(" max |device - expected| = %.2e (limit %.2e)\n", static_cast(max_diff), static_cast(tolerance)); const bool pass = (expected_found < 0 || res->n == expected_found) && max_diff <= tolerance; printk("%s SELF-TEST %s\n", runner.name, pass ? "PASS" : "FAIL"); /* The fp32 program takes seconds a run; three are enough to time it. */ const int reps = us > 1000000 ? 3 : 10; uint32_t total = 0; for (int i = 0; i < reps; ++i) { runner.run(kPoseTestImage, nullptr, &out, &us); total += us; } printk("%s inference: %u us average over %d runs\n", runner.name, total / reps, reps); res->us = total / reps; return pass ? total / reps : 0; } #if defined(CONFIG_APP_CAMERA) || defined(CONFIG_APP_SCREEN) void rgb888_to_rgb565(const uint8_t *in, uint16_t *out, int count) { for (int i = 0; i < count; ++i) { out[i] = static_cast(((in[3 * i] & 0xF8) << 8) | ((in[3 * i + 1] & 0xFC) << 3) | (in[3 * i + 2] >> 3)); } } #endif #ifdef CONFIG_APP_CAMERA /* The picture as text: one line a row, four hex digits a pixel. */ void dump_image(const uint16_t *img) { static const char hex[] = "0123456789abcdef"; static char line[kSide * 4 + 1]; printk("IMG %d %d rgb565\n", kSide, kSide); for (int y = 0; y < kSide; ++y) { for (int x = 0; x < kSide; ++x) { const uint16_t c = img[y * kSide + x]; line[4 * x] = hex[c >> 12]; line[4 * x + 1] = hex[(c >> 8) & 0xf]; line[4 * x + 2] = hex[(c >> 4) & 0xf]; line[4 * x + 3] = hex[c & 0xf]; } line[kSide * 4] = '\0'; printk("%s\n", line); } printk("END IMG\n"); } #endif #ifdef CONFIG_APP_SCREEN /* What the screen shows. The picture fills the panel; the round edge cuts * its corners. */ struct View { const uint16_t *image; /* 96 x 96 RGB565 */ const Found *res; const char *caption; }; constexpr int kImgX = 24; constexpr int kImgY = 6; constexpr int kImgScale = 2; /* The person's left in blue and right in red, as in the pictures of the * model card; the nose in white. */ uint16_t keypoint_color(int k) { return k == 0 ? COLOR_WHITE : ((k & 1) ? RGB565(70, 150, 255) : RGB565(255, 50, 40)); } int screen_x(float x) { return kImgX + static_cast(x * kSide * kImgScale); } int screen_y(float y) { return kImgY + static_cast(y * kSide * kImgScale); } /* A limb as a row of dots: the screen has no line, and dots clip for free. */ void draw_limb(const pose::Keypoint &a, const pose::Keypoint &b) { const int x0 = screen_x(a.x), y0 = screen_y(a.y); const int dx = screen_x(b.x) - x0, dy = screen_y(b.y) - y0; const int longest = abs(dx) > abs(dy) ? abs(dx) : abs(dy); const int steps = longest / 3 > 0 ? longest / 3 : 1; for (int i = 0; i <= steps; ++i) { screen_fill(x0 + dx * i / steps - 1, y0 + dy * i / steps - 1, 2, 2, COLOR_AMBER); } } void draw_view(void *ctx) { const View *v = static_cast(ctx); const Found &res = *v->res; char text[24]; screen_rgb565(kImgX, kImgY, v->image, kSide, kSide, kImgScale); for (int i = 0; i < pose::kLimbs; ++i) { const pose::Keypoint &a = res.k[pose::kSkeleton[i][0]]; const pose::Keypoint &b = res.k[pose::kSkeleton[i][1]]; if (a.heat >= res.threshold && b.heat >= res.threshold) { draw_limb(a, b); } } for (int k = 0; k < kKeypoints; ++k) { if (res.k[k].heat < res.threshold) { continue; } const int cx = screen_x(res.k[k].x), cy = screen_y(res.k[k].y); /* A black edge, so the dot shows on any shirt and any wall. */ screen_fill(cx - 3, cy - 3, 7, 7, COLOR_BLACK); screen_fill(cx - 2, cy - 2, 5, 5, keypoint_color(k)); } snprintk(text, sizeof(text), "n=%d %ums", res.n, (res.us + 500) / 1000); screen_text(120 - SCREEN_FONT_W * static_cast(strlen(text)), 202, text, 2, COLOR_WHITE); screen_text(120 - SCREEN_FONT_W / 2 * static_cast(strlen(v->caption)), 222, v->caption, 1, COLOR_GREY); } #endif /* CONFIG_APP_SCREEN */ /* The start-up report: sizes, the self-test of each program and its time. * Returns the program for the camera loop. A host that opened the port too * late to see it can ask for it again with 'i'. */ Runner *report(Runner &fp32, Runner *int8, Found *res) { Runner *live = &fp32; printk("\nExecuTorch PoseMicro on %s (Zephyr %s)\n", CONFIG_BOARD_TARGET, KERNEL_VERSION_STRING); fp32.info(); if (int8 != nullptr) { int8->info(); } const uint32_t us = self_test(fp32, kPoseTestCell, kPoseTestValues, POSE_TEST_FOUND, 1e-3f, "PyTorch", res); if (int8 != nullptr) { /* The integer kernels round differently from the quantised * model in PyTorch and the layers add up, so the export runs * this program on a PC, on the same kernels, and stores what * it answered: the board should match that to the step. When * the export could not, the values are PyTorch's, the limit * is loose and the number of keypoints found is not tested. */ const int steps = CONFIG_APP_POSE_INT8_STEPS > 0 ? CONFIG_APP_POSE_INT8_STEPS : POSE_TEST_Q_STEPS; const uint32_t us_q = self_test(*int8, kPoseTestCellQ, kPoseTestValuesQ, POSE_TEST_Q_FROM_PROGRAM ? POSE_TEST_FOUND_Q : -1, (steps + 0.5f) * POSE_Q_OUTPUT_SCALE, POSE_TEST_Q_FROM_PROGRAM ? "this program run on a PC" : "the quantised model in PyTorch", res); if (us != 0 && us_q != 0) { printk("\nint8 on CMSIS-NN is %u.%02ux the speed of fp32 on the portable " "kernels\n", us / us_q, (us % us_q) * 100 / us_q); } if (!IS_ENABLED(CONFIG_APP_POSE_LIVE_FP32)) { live = int8; } } printk("live program: %s\n", live->name); return live; } } // namespace int main(void) { executorch::runtime::runtime_init(); static Found res; Runner *int8_or_null = nullptr; uint8_t *pool = big_alloc(CONFIG_APP_POSE_FP32_POOL_SIZE); if (pool == nullptr) { printk("FAIL: no %d bytes for the fp32 program (is the PSRAM enabled?)\n", CONFIG_APP_POSE_FP32_POOL_SIZE); return 1; } static Runner fp32("portable", model_pte, model_pte_len, pool, CONFIG_APP_POSE_FP32_POOL_SIZE, temp_pool, sizeof(temp_pool)); if (fp32.init() != Error::Ok) { printk("FAIL: runtime init (portable)\n"); return 1; } #ifdef APP_CMSIS_NN static Runner int8("cmsis-nn", model_q_pte, model_q_pte_len, q_method_pool, sizeof(q_method_pool), q_temp_pool, sizeof(q_temp_pool)); if (int8.init() != Error::Ok) { printk("FAIL: runtime init (cmsis-nn)\n"); return 1; } int8_or_null = &int8; #endif /* --- 1. Self-test on the embedded picture ----------------------------- */ Runner *const live = report(fp32, int8_or_null, &res); #if defined(CONFIG_APP_CAMERA) || defined(CONFIG_APP_SCREEN) static uint16_t frame[kSide * kSide]; #endif #ifdef CONFIG_APP_SCREEN static View view; rgb888_to_rgb565(kPoseTestImage, frame, kSide * kSide); view.image = frame; view.res = &res; view.caption = "self-test"; const bool have_screen = screen_init() == 0; if (have_screen) { screen_render(draw_view, &view); } #endif /* --- 2. Live camera loop --------------------------------------------- */ #ifdef CONFIG_APP_CAMERA const struct device *const console = DEVICE_DT_GET(DT_CHOSEN(zephyr_console)); if (app_camera_init() != 0) { printk("camera init failed; stopping after self-test\n"); return 0; } #ifdef CONFIG_APP_SCREEN k_msleep(1500); /* leave the self-test picture up for a moment */ view.caption = live->name; #endif /* The heat a keypoint needs on camera frames, in percent. A camera's * pictures are not COCO's: '+' and '-' on the console move it while * you watch, and CONFIG_APP_POSE_THRESHOLD_PERCENT keeps what works. */ int threshold_percent = CONFIG_APP_POSE_THRESHOLD_PERCENT; printk("keypoint threshold on camera frames: %d%% ('+' and '-' change it)\n", threshold_percent); for (;;) { bool want_image = false; bool want_test = false; unsigned char ch; while (device_is_ready(console) && uart_poll_in(console, &ch) == 0) { if (ch == 'c') { want_image = true; } if (ch == '+' || ch == '-') { threshold_percent += ch == '+' ? 5 : -5; threshold_percent = threshold_percent < 5 ? 5 : threshold_percent > 95 ? 95 : threshold_percent; printk("keypoint threshold on camera frames: %d%%\n", threshold_percent); } if (ch == 'i') { report(fp32, int8_or_null, &res); } if (ch == 't') { want_test = true; } #ifdef CONFIG_APP_SCREEN if (ch == 's') { screen_dump_next(); } #endif } pose::Output out = {}; uint32_t us = 0; Error err; if (want_test) { /* One frame from the embedded picture instead of the camera. */ rgb888_to_rgb565(kPoseTestImage, frame, kSide * kSide); err = live->run(kPoseTestImage, nullptr, &out, &us); } else { if (app_camera_capture_rgb565(frame) != 0) { k_msleep(CONFIG_APP_CAMERA_INTERVAL_MS); continue; } err = live->run(nullptr, frame, &out, &us); } if (err != Error::Ok) { k_msleep(CONFIG_APP_CAMERA_INTERVAL_MS); continue; } decode(out, us, static_cast(threshold_percent) / 100.f, &res); #ifdef CONFIG_APP_SCREEN view.caption = want_test ? "self-test" : live->name; #endif if (want_image) { dump_image(frame); } print_pose(res); #ifdef CONFIG_APP_SCREEN if (have_screen) { screen_render(draw_view, &view); } #endif k_msleep(CONFIG_APP_CAMERA_INTERVAL_MS); } #else ARG_UNUSED(live); #endif return 0; }