Uh oh!
There was an error while loading. Please reload this page.
Cortex-M backend: Add AoT scratch-buffer planning. - #19636
Conversation
Add scratch tensors to the operator signatures, which are then assigned exir.memory.alloc. These allocs are automatically memory planned by ExecuTorch. Introduce `required_cmsis_buffer_size`which computes the buffer size from node properties + the Cortex-M configuration. The function uses functions registered by target in backends/cortex_m/passes/scratch_buffer_sizes.py This is used to set the size of the allocs in ConvertToCortexMPass Finally, modify the kernels to use the new scratch tensor instead of allocating temporary memory. Add a new macro CORTEX_M_ENABLE_ASSERT to do a safety check that the aot computed buffer size is equal to the buffer size computed at runtime. Use this when testing. Signed-off-by: Erik Lundell <erik.lundell@arm.com> Change-Id: Ia7ec8eda87833888a0639b480e531fd17818298a
Follow the plan from previous buffer planning work. Signed-off-by: Erik Lundell <erik.lundell@arm.com> Change-Id: I4bf3ca1cc421421b61903cba24856d0fd635d64a
We can now reduce the memory size to 0 when building the cortex_m test runner. Signed-off-by: Erik Lundell <erik.lundell@arm.com> Change-Id: Ieb1292c2db4651cd1f0756aa9d43ecedd5e262e5
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/19636
Note: Links to docs will display an error until the docs builds have been completed. ❌ 2 New Failures, 3 Unrelated FailuresAs of commit 7ad198a with merge base b73df0b ( NEW FAILURES - The following jobs have failed:
BROKEN TRUNK - The following jobs failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
Erik-Lundell
commented
May 18, 2026
This is a polished version of #16580 |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
| ) | ||
| with node.graph.inserting_before(node): | ||
| scratch = node.graph.call_function( |
There was a problem hiding this comment.
exir.passes.make_alloc_node is the canonical helper for emitting memory.alloc nodes. It's used by to_out_variant and to_scratch_op_pass use internally, and it sets meta["val"] and meta["tensor_meta"] on the alloc. The memory planner keys off meta["val"] / meta["tensor_meta"] to build the TensorSpec that drives lifetime analysis and arena placement.
There was a problem hiding this comment.
Thanks, I'll use that
| ) | ||
| return exir_ops.edge.cortex_m.quantized_conv2d.default, new_args | ||
| def _set_scratch_buffer_size(self, node: torch.fx.Node) -> None: |
There was a problem hiding this comment.
IIUC, the current flow creates each scratch alloc with a placeholder shape, wires it into the cortex_m op's args, and then walks back through node.args[-(i+1)] in _set_scratch_buffer_size to mutate the alloc's shape once the size is known. This works, but the two-phase flow has a few drawbacks:
- The alloc -> size pairing is positional and implicit, split across two files. Adding a non-scratch trailing arg to any op signature silently mis-pairs.
- The UNINITIALIZED_ALLOC_ARGS sentinel + later mutation requires a reader to follow two hops to understand the alloc's actual size.
- _set_scratch_buffer_size exists only to undo the placeholder.
All the values required_cmsis_nn_buffer_sizes needs are already available locally in get*_replacement. If the size functions took inputs directly (e.g. an explicit ConvBufferSizeInputs dataclass), you could compute sizes before constructing the cortex_m op and emit allocs at their final size on one pass.
There was a problem hiding this comment.
I see your point, but I would like to keep the current design with the following arguments:
- node already perfectly captures the context needed to compute scratch buffer sizes. Introducing a new dataclass interface creates more boilerplate code with the risk of mismatching args.
- Importantly, node.meta["val"].shape is needed for conv, which requires either executing the node the calculate it (as is done now), or some duplication of logic to compute the shape from its args.
- cortex_m node creation is only done in one place in the pass (L513) , and the initialization happens directly after, so the logic is not too far separated.
- There is a check that the trailing args are allocs, so there is no silent mis-pairing. If alloc sizes were given in the wrong order, the runtime check would catch it.
I have pushed a commit to try to clarify the pattern though.
| return [ | ||
| int( | ||
| cmsis_nn.convolve_wrapper_buffer_size( |
Mainly clarify the uninitialized/intialize alloc pattern. Signed-off-by: Erik Lundell <erik.lundell@arm.com> Change-Id: I062a5048094129be6ed8e9f7eafc096f34132b2f
Signed-off-by: Erik Lundell <erik.lundell@arm.com> Change-Id: I8da2906a5f4cc69d15d033d8e5d1113d8b4afc4e
Uh oh!
There was an error while loading. Please reload this page.
Change-Id: Id4bd854d81b42769115f4fd9f58c24b19742696b
A failed check doesn't crash, it just passes an error to the caller. This matches the name RUNTIME_CHECK better than ASSERT. Signed-off-by: Erik Lundell <erik.lundell@arm.com> Change-Id: I4a077c62a4dcf02040f0ea29d1794168da66b411
Uh oh!
There was an error while loading. Please reload this page.
The library is generated from this repository, so an ExecuTorch change can break it without touching examples/arduino at all. Nothing checked that. The job builds the library, verifies the shipped models against it, compiles every example for arduino:zephyr:unoq, and runs arduino-lint in Library Manager submission mode. It runs on changes under examples/arduino, backends/cortex_m, kernels/portable, runtime, and schema, which is the set that can break any of the four. verify_models.py is the part worth having. A .pte records how many values each operator call puts on the stack, and the generated kernel wrappers reject anything else; the two only agree when the model and the library came from the same commit. Cortex-M schemas change - scratch was added to the conv operators in pytorch#19636 and pytorch#19825 - and a mismatch is invisible until far too late, because the program loads, every operator resolves, and then execute returns InvalidProgram naming nothing useful. Tracking that down by hand took the better part of a day. The check compares the two directly in about a second, needs no board, and reports: FAIL KeywordSpotting cortex_m::quantized_avg_pool2d.out: model supplies 10, library expects 11 Compiling is deliberately not the whole job. Every failure worth finding in this library compiled cleanly first, so the model check runs before the sketches and arduino-lint guards the thing users actually install. Authored with Claude Code (Opus 5).
The library is generated from this repository, so an ExecuTorch change can break it without touching examples/arduino at all. Nothing checked that. The job builds the library, verifies the shipped models against it, compiles every example for arduino:zephyr:unoq, and runs arduino-lint in Library Manager submission mode. It runs on changes under examples/arduino, backends/cortex_m, kernels/portable, runtime, and schema, which is the set that can break any of the four. verify_models.py is the part worth having. A .pte records how many values each operator call puts on the stack, and the generated kernel wrappers reject anything else; the two only agree when the model and the library came from the same commit. Cortex-M schemas change - scratch was added to the conv operators in pytorch#19636 and pytorch#19825 - and a mismatch is invisible until far too late, because the program loads, every operator resolves, and then execute returns InvalidProgram naming nothing useful. Tracking that down by hand took the better part of a day. The check compares the two directly in about a second, needs no board, and reports: FAIL KeywordSpotting cortex_m::quantized_avg_pool2d.out: model supplies 10, library expects 11 Compiling is deliberately not the whole job. Every failure worth finding in this library compiled cleanly first, so the model check runs before the sketches and arduino-lint guards the thing users actually install. Authored with Claude Code (Opus 5).
The library is generated from this repository, so an ExecuTorch change can break it without touching examples/arduino at all. Nothing checked that. The job builds the library, verifies the shipped models against it, compiles every example for arduino:zephyr:unoq, and runs arduino-lint in Library Manager submission mode. It runs on changes under examples/arduino, backends/cortex_m, kernels/portable, runtime, and schema, which is the set that can break any of the four. verify_models.py is the part worth having. A .pte records how many values each operator call puts on the stack, and the generated kernel wrappers reject anything else; the two only agree when the model and the library came from the same commit. Cortex-M schemas change - scratch was added to the conv operators in pytorch#19636 and pytorch#19825 - and a mismatch is invisible until far too late, because the program loads, every operator resolves, and then execute returns InvalidProgram naming nothing useful. Tracking that down by hand took the better part of a day. The check compares the two directly in about a second, needs no board, and reports: FAIL KeywordSpotting cortex_m::quantized_avg_pool2d.out: model supplies 10, library expects 11 Compiling is deliberately not the whole job. Every failure worth finding in this library compiled cleanly first, so the model check runs before the sketches and arduino-lint guards the thing users actually install. Authored with Claude Code (Opus 5).
…els (#21546) ## Summary The Arduino library this directory generates could not compile, and had it compiled it could not have run a model. Kernels never reached the operator registry — ExecuTorch registers them through codegen and the build script never ran it, so every `Method::load` would have failed with `OperatorMissing`. CMSIS-NN was never vendored, so the Cortex-M ops shipped without the library they call. `schema/*.cpp` was never copied, the `*_aten.cpp` exclusion also deleted the portable-mode `tensor_parser_exec_aten.cpp`, and `__errno` was missing because the Zephyr core mixes picolibc with newlib's `libm_nano`. Both `minimal.cpp` and `zephyr.cpp` were vendored, so which `et_pal_*` backend you got depended on link order, and every `ET_LOG` was discarded either way. One backend now ships and its logs route to a hook the examples implement against `Serial`. The examples ship their models — previously none did, so every sketch `#error`ed when opened from the IDE menu. The README pointed at the Ethos-U `pte_to_header.py`, whose `network_model_sec` section no Arduino core defines, so following the docs produced a model that fails `Program::load`. Static link mode is mandatory and undocumented; the Dynamic default yields a silently dead board. Renamed to `ExecuTorch` because `arduino-lint` rejects "Arduino" in an Arduino library's name. Registering every portable kernel costs 1.58 MB against 786 KB of flash, so the op set is a curated default overridable via `ROOT_OPS`/`ALL_OPS`. Models and libraries must come from the same ExecuTorch commit — Cortex-M schemas change (`scratch` in #19636, #19825), and a mismatch loads fine, resolves every operator, then fails at `Method::execute`. The library now records and pins that commit. CI to enforce it follows separately. ## Test plan `arduino:zephyr:unoq`, board core 0.55.2, `link_mode=static`, flashed on hardware: ``` HelloExecuTorch Model loaded OK!, 1 method 60% flash, 20% RAM AddModel [1,2,3] + 1 = [2.00, 3.00, 4.00] 64% flash, 26% RAM KeywordSpotting 10/10 keywords correct 70% flash, 53% RAM ``` All ten MFCC inputs in one sketch, exercising the CMSIS-NN conv / depthwise / avgpool / linear kernels: ``` yes 8.95 no 4.78 up 4.63 down 9.72 left 7.87 right 7.41 on 12.03 off 8.02 stop 8.64 go 9.57 ``` `arduino-lint --library-manager submit`: no errors, no warnings, under both `specification` and `strict`. Clean regeneration is byte-identical across all 626 generated files. Only the Uno Q was tested; the other three boards remain marked Planned. Authored with Claude Code (Opus 5).
The library is generated from this repository, so an ExecuTorch change can break it without touching examples/arduino at all. Nothing checked that. The job builds the library, verifies the shipped models against it, compiles every example for arduino:zephyr:unoq, and runs arduino-lint in Library Manager submission mode. It runs on changes under examples/arduino, backends/cortex_m, kernels/portable, runtime, and schema, which is the set that can break any of the four. verify_models.py is the part worth having. A .pte records how many values each operator call puts on the stack, and the generated kernel wrappers reject anything else; the two only agree when the model and the library came from the same commit. Cortex-M schemas change - scratch was added to the conv operators in #19636 and #19825 - and a mismatch is invisible until far too late, because the program loads, every operator resolves, and then execute returns InvalidProgram naming nothing useful. Tracking that down by hand took the better part of a day. The check compares the two directly in about a second, needs no board, and reports: FAIL KeywordSpotting cortex_m::quantized_avg_pool2d.out: model supplies 10, library expects 11 Compiling is deliberately not the whole job. Every failure worth finding in this library compiled cleanly first, so the model check runs before the sketches and arduino-lint guards the thing users actually install.
This is done for conv, depthwise conv, transpose conv, and bmm.
Add scratch tensors to the operator signatures, which are then
assigned exir.memory.alloc. These allocs are automatically memory
planned by ExecuTorch.
Introduce
required_cmsis_buffer_sizewhich computes the buffersize from node properties + the Cortex-M configuration.
The function uses functions registered by target in
backends/cortex_m/passes/scratch_buffer_sizes.py
This is used to set the size of the allocs in ConvertToCortexMPass
Finally, modify the kernels to use the new scratch tensor instead
of allocating temporary memory. Add a new macro CORTEX_M_ENABLE_RUNTIME_CHECKS
to do a safety check that the aot computed buffer size is equal to the
buffer size computed at runtime. Use this when testing.
cc @psiddh@AdrianLundell@digantdesai@rascani@freddan80@per@zingo@oscarandersson8218@mansnils@Sebastian-Larsson@robell