# Streaming constants

Streaming copies a model's weights from slow memory into a small on-chip
**stream pool** just before the layer that reads them, following a
**transfer schedule** in the plan. One 16 KiB pool can serve a whole model,
because each part of the pool holds different weights at different times.

This page describes heliaAOT 1.5.0. Streaming is experimental: the settings it
uses (`memory.stream_pool`, `optimization.plan`, `module.transfer_provider`
and `residency: stream`) can change in any release.

## Do you need it?

Start from a conversion without streaming. Its results table, or
`<prefix>_residency.json`, gives the constant bytes in each memory, and the
report's `operators[].constants[].bytes` gives the bytes each layer reads.
The core's D-cache is 64 KB on Apollo510 and Apollo510B and 32 KB on
Apollo510L and Apollo330P, the datasheet values the helia-platforms catalog
records (`dcache_kb`).

| Where the weights are | Choose |
| --- | --- |
| On chip in DTCM or SRAM, beside the scratch arena | Direct, the default. Nothing to stream. |
| A few hot constants elsewhere, with free DTCM or SRAM to hold a copy | Pin: `constant_destination_memory`; see [Memory placement](https://ambiqai.github.io/helia-aot/guide/memory-placement/#cold-and-staged-constants). |
| MRAM (on chip on Apollo510, read in place through the D-cache) | Direct. MRAM offers only `cpu` copies, which never overlap compute, so streaming from MRAM pays only when a profile shows layers re-reading MRAM weights dominate and pinning them does not fit. |
| PSRAM, with more constant bytes than the D-cache the model can keep (the core's D-cache less what the application uses), and too many to pin | Stream. The largest layer's constants must fit the pool, and the pool must fit the free DTCM. |
| PSRAM, with fewer constant bytes than that | Direct is usually enough; measure. |
| Read by an Ethos-U command stream (an NPU model) | Never stream: `stageable: false`, reason `pinned` when stored in MRAM or PSRAM, `not a stream source` otherwise. |
| Read at init, a model output, or sharing storage with a tensor that cannot stream (a view, which an identity RESHAPE, SQUEEZE or EXPAND_DIMS of a constant leaves; an Ethos-U command stream; a model output or an init reader) | Cannot stream; the report's `constants[].reason` says which. A constant interned with its duplicates streams with them, and every reader reads the one copy from the pool. |

When two rows could apply, measure: profile the model with the weights in
place and with them pinned or streamed, and keep the faster run within your
memory budget; see [Measure a conversion](https://ambiqai.github.io/helia-aot/guide/measure/).

Measured on Apollo510 at 96 MHz, a 45 KB model with its weights in PSRAM at
12 MHz (RFC 0005):

| Where the weights are read from | Latency |
| --- | ---: |
| All on chip | 36.85 ms |
| PSRAM, D-cache off for the weights | 727.0 ms |
| PSRAM, a 16 KiB pool, a copy before each layer | 36.9 ms |
| PSRAM, a 16 KiB D-cache share (emulated) | 41.19 ms |
| PSRAM, a 16 KiB pool, a planned schedule | 37.26 ms |

## How it works

| Piece | What it is |
| --- | --- |
| `residency: stream` | A rule that permits a constant to stream. Its `memory` must be a stream source: MRAM or PSRAM. |
| `memory.stream_pool` | The pool, in DTCM, reserved in DTCM's budget before planning. The application binds it. Modules whose runs do not overlap can share one. |
| Transfer unit | One copy of one or more constants from one source memory into the pool, issued after an operator and finished before the first reader. |
| `cpu` unit | Copied by the module with `memcpy`. Works from MRAM and PSRAM. |
| `dma` unit | Copied by a [transfer provider](https://ambiqai.github.io/helia-aot/reference/transfer-provider/) while the CPU computes. PSRAM into DTCM on `apollo510_evb` and `apollo510b_evb`. |
| Schedule | The plan's `schedule` section: the list of units. heliaAOT never searches for one; it checks the one it is given. |

A permitted constant that no unit names stays direct. A conversion with a pool
and no schedule streams nothing, but the module still has a pool to bind.

A plan can size the pool itself: with `applies: ["schedule.pool"]` its
`schedule.pool` (`memory: dtcm` and `bytes`) replaces `memory.stream_pool`,
and `schedule.pool: null` with `schedule.no_pool: true` converts with no pool
at all. So a planner compares pool sizes, and no pool, from one configuration.
Every constant then needs a `memory` rule, as here; see
[Declared paths](https://ambiqai.github.io/helia-aot/guide/plans-and-reports/#declared-paths).

## Worked example

The [KWS example model](https://ambiqai.github.io/helia-aot/getting-started/convert/) on
`apollo510_evb`, as an `nsx` module. Its weights fit on chip, so it does not
need streaming; it is small enough to show every step. Run the commands from
the directory that holds `kws_ref.tflite`.

### 1. Configure the pool and the rules

```yaml title="stream.yaml"
model:
  path: kws_ref.tflite
module:
  path: ./out
  name: kws_stream
  type: nsx
platform:
  name: apollo510_evb
memory:
  stream_pool:
    bytes: 16384
  tensors:
    - type: constant
      attributes:
        memory: mram
        residency: stream
    - id: "16"
      attributes:
        memory: psram
        residency: stream
```

- The first rule stores every constant in MRAM and lets it stream.
- The second puts constant `16`, the FULLY_CONNECTED weights, in PSRAM. Ids
  are the plan's `tensors[].id`, from any earlier conversion of the model.
- `stream_pool.memory` defaults to `dtcm`, the only pool memory.

### 2. Convert once

```sh
helia-aot convert --path stream.yaml
```

```text
WARNING  memory.tensors permits residency stream for 37 constant(s) (17,
         conv_2d_0_weight_sum, conv_2d_0_multiplier, conv_2d_0_shift, 5,
         depthwise_conv_2d_1_weight_sum, depthwise_conv_2d_1_multiplier,
         depthwise_conv_2d_1_shift and 29 more), but no optimization.plan
         carries a transfer schedule, so they stay direct.
...
 Region   Kind                          Size    Capacity
 dtcm     scratch                    18.9 KB    496.0 KB
 mram     constant (cold) · 37       27.5 KB      3.9 MB
          tensors
 psram    constant (cold) · 1          928 B     64.0 MB
          tensors
 dtcm     stream pool (bound by      16.0 KB    496.0 KB
          the application) · 0
          units
```

The PSRAM arena is 928 bytes for 912 bytes of weights: a constant arena in
external memory is padded to the core's 32-byte D-cache line.

### 3. Find the ids a schedule names

A unit names constants by `tensors[].storage_id` when the entry has one, else
by `tensors[].id`, and names operators by `operators[].id`:

```python title="ids.py"
import json
plan = json.load(open("out/kws_stream/aot_plan.json"))
for op in plan["operators"]:
    print(op["index"], op["op_type"], op["id"])
for t in plan["tensors"]:
    print(t["id"], t["storage_id"], t["memory"], t["bytes"])
```

```text
2 CONV_2D 0:functional_1/activation_2/Relu;functional_1/batch_normalization_2/...
9 AVERAGE_POOL_2D 0:functional_1/average_pooling2d/AvgPool
10 RESHAPE 0:functional_1/flatten/Reshape
11 FULLY_CONNECTED 0:functional_1/dense/BiasAdd
...
18 None MRAM 4096
...
16 fully_connected_11_packed PSRAM 912
```

### 4. Write the schedule

Copy the plan, `cp out/kws_stream/aot_plan.json plan.json`, and in its
`schedule` section replace `"source": "none"` and `"units": []` with:

```json title="plan.json, schedule"
    "source": "plan",
    "units": [
      {
        "id": 0,
        "tensors": ["18"],
        "pool_offset": 0,
        "issue_after": null,
        "engine": "cpu"
      },
      {
        "id": 1,
        "tensors": ["fully_connected_11_packed"],
        "pool_offset": 0,
        "issue_after": "0:functional_1/average_pooling2d/AvgPool",
        "engine": "dma"
      }
    ]
```

- Unit 0 copies constant `18`, the weights of operator 2, from MRAM by CPU at
  the start of the run. It gains nothing here; it shows a `cpu` unit.
- Unit 1 copies the FULLY_CONNECTED weights from PSRAM by DMA after the
  average pool, so the copy overlaps the RESHAPE.
- Both use pool offset 0: unit 0's last reader runs before unit 1 is issued,
  so they are never live together.
- Leave out the derived fields (`bytes`, `wait_before`, `last_reader`,
  `source_memory`, `source_offset`); the conversion writes them back.

The rules a schedule must meet are in
[Plans and reports](https://ambiqai.github.io/helia-aot/guide/plans-and-reports/#the-transfer-schedule).
For a model with many layers, see
[A schedule for your own model](https://ambiqai.github.io/helia-aot/guide/streaming/#a-schedule-for-your-own-model).

### 5. Convert with the plan

```sh
helia-aot convert --path stream.yaml --optimization.plan plan.json --force
```

```text
WARNING  optimization.plan .../plan.json: schedule unit(s) 0 are issued at the
         start of every run (issue_after null), so their copy is exposed on
         every run; nothing is prefetched across runs.
WARNING  memory.tensors permits residency stream for 35 constant(s) (...) that
         the schedule of optimization.plan .../plan.json leaves out, so they
         stay direct.
...
 dtcm     stream pool (bound by      16.0 KB    496.0 KB
          the application) · 2
          units
```

The first warning is expected here: a `cpu` copy never overlaps compute.

### 6. Check the result

| Where | What it says here |
| --- | --- |
| `aot_report.json`, `stream_pool.pieces_in_flight` | `1`: the queue depth the provider needs |
| `aot_report.json`, `stream_pool.alignment` | `4096`: align the pool buffer to it |
| `aot_plan.json`, `tensors[]` | `18` and `16` now have `residency: stream`, a `unit` and a `pool_offset` |
| `aot_plan.json`, unit 1 | `wait_before` and `last_reader` are the FULLY_CONNECTED; `source_memory` is `PSRAM` |
| `aot_context.h` | `aot_num_transfer_units 2`, `aot_num_dma_units 1`, `aot_transfer_pieces_in_flight 1` |
| `README.md` | "Stream Pool", the target's "Transfer provider rules" and, for `nsx`, STEP 5 |
| `includes-api/aot_nsx_transfer.h` | The emitted provider, because the module has a `dma` unit |

## The C side

Every module type binds the pool before `aot_model_init`. `aot_model_init`
returns 10 while it is unbound.

```c
alignas(aot_arena_pool_dtcm_alignment) static int8_t AOT_PUT_IN_DTCM pool[aot_arena_pool_dtcm_size];
int32_t status = aot_bind_arena(aot_arena_pool_dtcm, pool, sizeof(pool));
```

### Put the PSRAM constants in PSRAM

The module declares the PSRAM constant arena, but nothing puts it in PSRAM
for you. PSRAM is volatile, so its bytes have to be written there after
`nsx_psram_init` on every boot. The array is declared with the placement hook
`AOT_PUT_IN_PSRAM_INIT`, which expands to nothing in every module type, so
without one of the two ways below it lands in ordinary RAM.

| Way | What you do |
| --- | --- |
| Caller-bound arenas | Convert with `memory.allocate_arenas: false`. The module then declares no buffers and writes each constant arena as a sidecar file. At boot, write `aot_arena_const_psram__blob.bin` into PSRAM and bind that address to `aot_arena_const_psram`. Bind every other region the same way: the scratch arena, the MRAM constant arena from its sidecar, and the pool. |
| Module-owned arenas | Define `AOT_PUT_IN_PSRAM_INIT` to a linker section in PSRAM's address range, and copy that section's initial bytes into PSRAM after `nsx_psram_init`. For `nsx`, define it in the header the CMake variable `KWS_STREAM_ATTRIBUTES_HEADER` names; for `cmake`, as a compile definition on the module's target, such as `target_compile_definitions(kws_stream PRIVATE "AOT_PUT_IN_PSRAM_INIT=__attribute__((section(\".psram_init\")))")`. The section and the copy are your linker script's and startup code's. |

With caller-bound arenas:

```sh
helia-aot convert --path stream.yaml --optimization.plan plan.json --no-memory.allocate-arenas --force
wc -c out/kws_stream/*.bin
```

```text
28168 out/kws_stream/aot_arena_const_mram__blob.bin
  928 out/kws_stream/aot_arena_const_psram__blob.bin
29096 total
```

```c
#include "aot_model.h"
#include "nsx_psram.h"

// The bytes of aot_arena_const_psram__blob.bin, linked into flash by the application.
extern const uint8_t psram_blob[aot_arena_const_psram_size];

// The PSRAM range the application reserves for the arena: no other buffer uses
// [PSRAM_CONST_OFFSET, PSRAM_CONST_OFFSET + aot_arena_const_psram_size).
#define PSRAM_CONST_OFFSET 0u

// After nsx_psram_init with XIP enabled; before aot_model_init. DTCM stays powered and deep sleep off throughout.
int32_t load_psram_constants(void) {
    nsx_psram_info_t info;
    if (nsx_psram_get_info(&info) != 0) {
        return -1;
    }
    const uint32_t offset = PSRAM_CONST_OFFSET;
    if (offset % aot_arena_const_psram_alignment != 0 || offset > info.size_bytes ||
        info.size_bytes - offset < aot_arena_const_psram_size) {
        return -1;  // misaligned, or past the end of the device
    }
    // If this range was ever written through the XIP window, or its history is unknown, clean and invalidate it
    // here, before the write; then leave it untouched through the window until the write returns.
    if (nsx_psram_write(offset, psram_blob, sizeof(psram_blob)) != 0) {
        return -1;  // If nsx-psram is now FAILED, keep DTCM powered and deep sleep off until reset.
    }
    void *arena = (void *)(uintptr_t)(info.base_address + offset);
    // Clean and invalidate the D-cache over [arena, arena + aot_arena_const_psram_size) here, before the first run.
    return aot_bind_arena(aot_arena_const_psram, arena, aot_arena_const_psram_size);
}
```

The arena needs a PSRAM range of its own. nsx-psram allocates nothing and
writes wherever the offset says, so reserve a range that no other PSRAM buffer
of the application uses (a heap, a frame buffer, another module's arena): at
a multiple of `aot_arena_const_psram_alignment` from the start of PSRAM, and
`aot_arena_const_psram_size` bytes long, the size padded to the D-cache line.
The example checks that the range fits the device before any cache
maintenance; `nsx_psram_write` would also refuse it with
`NSX_PSRAM_STATUS_OUT_OF_RANGE`, leaving the driver `READY`.

`nsx_psram_write` copies through a DTCM buffer by DMA, and the pinned
nsx-psram's `nsx_psram.h` states what the caller keeps in place around it.
The load runs before the transfer provider is bound, so the provider's sleep
rule does not cover it:

- Keep DTCM powered and stay out of deep sleep until the write returns.
- Before the write, clean and invalidate the D-cache over the range if it was
  ever written through the XIP window or its history is unknown; leave the
  range untouched through the window until the write returns.
- A write that fails in the platform transfer leaves nsx-psram `FAILED`
  (`nsx_psram_get_info`'s `state`) until reset, with its DMA storage still in
  use: keep DTCM powered and stay out of deep sleep until the reset. A
  refusal before the transfer, such as a misaligned offset, leaves it `READY`.

Skip this step with module-owned arenas and `aot_model_init` still
succeeds, but every run returns 301: the array sits in ordinary RAM, outside
the PSRAM window, so the emitted provider refuses each piece with 317
(`aot_nsx_transfer_last()`). With caller-bound arenas, an unbound region makes
`aot_model_init` return 10.

### Bind the provider

**`nsx` module.** Link `nsx::kws_stream_nsx_transfer` beside
`nsx::kws_stream`, then bind the emitted provider:

```c
#include "aot_nsx_transfer.h"

// After nsx_psram_init with XIP enabled and load_psram_constants():
status = aot_nsx_transfer_bind(&ctx, NULL);
if (status != 0) {
    return status;  // 310 to 314, or 323; ctx.transfer is unchanged
}
status = aot_model_init(&ctx);
```

STEP 5 of the module README has the full order, the cache rule and the
statuses. The provider needs nsx-psram's queue to hold
`aot_transfer_pieces_in_flight` pieces; its default, 8, does here.

**`cmake`, `cmsis_pack` or `zephyr` module.** Bind a provider of your own:

```c
int32_t my_dma_issue(void *self, uint32_t ticket, void *destination, const void *source, size_t bytes);
int32_t my_dma_wait(void *self, uint32_t ticket);
int32_t my_dma_abort(void *self);
extern struct my_dma my_dma;
static const aot_transfer_provider_t transfer = { my_dma_issue, my_dma_wait, my_dma_abort, &my_dma };

ctx.transfer = &transfer;
status = aot_model_init(&ctx);
```

What the three functions must do is on
[Transfer provider contract](https://ambiqai.github.io/helia-aot/reference/transfer-provider/). A
module with only `cpu` units needs no provider.

## A schedule for your own model

No released tool writes schedules yet. A planner that reads the report's
[stable fields](https://ambiqai.github.io/helia-aot/reference/compatibility/#stable-report-fields) can,
and so can a short script that follows these steps:

1. Convert once with the pool and the `stream` rules, and no plan.
2. Walk the report's `operators[]` in order. For each operator, take the
   `constants[]` that no earlier operator took, with `stageable: true` and
   `requested: stream` in the plan's `tensors[]` entry (`stageable` alone does
   not mean a rule permits streaming), named by `storage_id` when set, else
   `id`. The plan's `tensors[]` gives each one's `memory`, `bytes` and
   `alignment` (the report carries no memory).
3. Make one unit per operator and source memory, its tensors in the plan's
   `tensors[]` order. A constant that later operators read too (its id is in
   their `constants[]`, which names an interned duplicate by its stored copy)
   gets a unit of its own instead, held across all its readers: it stays live
   until its last reader has run. Its span: each tensor at the next multiple of its
   `alignment`. Its extent, the pool bytes it occupies: the span, rounded up to
   the source's `granule` for a `dma` unit. Leave out a group whose extent is
   larger than the pool; it stays direct.
4. Give each unit `issue_after` the operator before its reader (null for the
   first operator), `pool_offset: 0`, and `engine: cpu`, or `dma` where the
   report's `stream_pool.sources[]` offers it for that memory. When an
   operator has two units, start the second after the first's extent, at a
   multiple of its own alignment (and of the source's `granule` for `dma`).
   Every unit must end inside the pool, `pool_offset` plus its extent at most
   the pool's bytes; leave out one that does not, and it stays direct.
   Number the units from 0 in that order.
5. Convert with `optimization.plan`. A refusal names the unit and the fix:
   two units live together get disjoint offsets, a misaligned offset moves to
   the multiple the message names.

Every unit at offset 0, issued just before its reader, never overlaps
another unless a constant is read again later; a held unit's bytes stay its
own until its last reader, so give the units live meanwhile other offsets. To
overlap a `dma` copy with compute, issue it earlier and give units live
together disjoint offsets.
Applied to the KWS example with every constant permitted, these steps give 10
units, and 11 when one layer's constants are split between MRAM and PSRAM;
applied to IC ResNet-8 from PSRAM with a 16 KiB pool, 8 units, with two layers
too large for the pool left direct. All three convert.

## When it goes wrong

- A schedule is refused at conversion, naming the unit or tensor and the
  fix: see [Schedule refusals](https://ambiqai.github.io/helia-aot/guide/troubleshooting/#schedule-refusals).
- `aot_model_init` or `aot_model_run` returns 10, 14 or 300 to 329: see
  [Runtime statuses](https://ambiqai.github.io/helia-aot/reference/transfer-provider/#runtime-statuses).
  Every run returning 301 with provider code 317 means the PSRAM constants are
  not in PSRAM.
- Outputs differ from the unstreamed module: see
  [Runtime statuses](https://ambiqai.github.io/helia-aot/guide/troubleshooting/#runtime-statuses) for
  when that is expected, and otherwise check the cache rule in the module
  README's "Transfer provider rules".
- With module-owned arenas, the generated test case runs a module with `dma`
  units on its own synchronous provider, so it checks the schedule without
  your provider. With caller-bound arenas it loads no sidecar: it returns -1
  when a constant arena is read in place from a memory it cannot write, such
  as MRAM, and binds a zero-filled buffer for one in a writable memory, such
  as PSRAM. Check such a module with a harness of your own that loads and
  binds the sidecars, then calls `aot_model_init` and `aot_model_run`.

## Next

[Transfer provider contract](https://ambiqai.github.io/helia-aot/reference/transfer-provider/) for the
C interface, and [Plans and reports](https://ambiqai.github.io/helia-aot/guide/plans-and-reports/#the-transfer-schedule)
for every schedule field.
