A Network on a Cortex-M

A neural network is a recipe that needs memory at every step. See how a chip with 320 KB of SRAM runs one: the arena, the planner and the kernels that squeeze 58 KB of tensors into 40.

Learn how TensorFlow Lite Micro and CMSIS-NN run an int8 network on a Cortex-M chip, and how to know before you flash whether the model fits.

Pick a strategy, then drag the image size. Watch which tensors stay alive and whether the run still fits in 320 KB of SRAM. Then we build, piece by piece, the arena, the planner, the kernels and the fused operators underneath.

You need what a convolution layer does (a small filter slid over an image) and a little C. We build the rest from zero.

Built from primary sources, listed in the Field Guide: the TensorFlow Lite Micro paper (David et al., MLSys 2021), the TFLM and CMSIS-NN source code and docs, and the CMSIS-NN paper (Lai, Suda and Chandra, 2018). Part of the series Firmware from Zero to Expertise. Starts from Where Memory Goes and NN Building Blocks.

Fit the network

32 px

The network is the CIFAR-10 CNN of the CMSIS-NN paper (three 5 by 5 convolutions, three poolings, one fully connected layer, int8). Its layer sizes at 32 px are the paper’s Table 1; other image sizes scale them by the same formulas, so those are our arithmetic, not measurements. The chip is the STM32F746ZG (320 KB SRAM). KB means 1,024 bytes, as in the paper. Stack and interpreter bookkeeping are not counted.

Chapter 0

Why a Network Needs a Memory Budget

See that a network that fits in flash can still fail in SRAM, and learn which numbers decide it

You trained a small image classifier on your laptop. It is accurate and it is tiny: 87 KB of weights. The target is a Nucleo board with an STM32F746ZG chip, which has 1,024 KB of flash and 320 KB of SRAM. The numbers look comfortable, so you convert the model, flash it, and run.

The board hangs. Or the first call to the library returns an error. Or it runs, but takes a full second and the answers look wrong. The weights fit in the chip. Something else did not.

That something else is the work of running the network. This lesson is about that work: what memory it needs, where the memory comes from, and how the libraries TensorFlow Lite Micro (TFLM, a small C++ interpreter that runs neural network models on microcontrollers) and CMSIS-NN (a set of fast integer kernels from Arm, a kernel being the tight loop that does one layer’s arithmetic) keep it small.

Two memories, two jobs

A microcontroller has two kinds of memory. Flash keeps its contents when the power is off. You write your program there, and it is large but slow to change. SRAM (static RAM) is the working memory. It is fast, it forgets everything at power off, and there is little of it. The chip above has about three times more flash than SRAM, and many chips have eight or sixteen times more.

A trained network is two things. The weights are the numbers learned in training. They never change after you flash them, so they can live in flash. The activations are the numbers that flow through the network while it works on one input: the image, then the output of layer one, then the output of layer two, and so on. They change on every run, so they must live in SRAM.

So the question is not “do the weights fit?” It is “do the activations fit, and do we waste any space?” Prerequisite lesson Where Memory Goes showed how the stack, the heap and static data share SRAM. The network’s activations are one more tenant, and a big one.

A real network, layer by layer

Let us look at a real case. In 2018 Arm engineers published CMSIS-NN, and they tested it on a small classifier for the CIFAR-10 dataset (32 by 32 colour images in ten classes). It has three convolution layers (a small filter slid over the image to find patterns), three pooling layers (each shrinks the image by keeping the strongest value in every small window) and one fully connected layer (every input number feeds every output number). They ran it on this very chip, the STM32F746ZG, with its Cortex-M7 core at 216 MHz.

Their Table 1 lists every layer. Use the buttons to see which layer is the biggest by each measure.

Which layer is the problem?

One bar per layer. Switch the measure and watch the longest bar jump to a different layer. Weights live in flash; activations live in SRAM.

Weights, output sizes and operation counts are the CMSIS-NN paper’s Table 1 (KB means 1,024 bytes; one operation is one multiply or one add, so a multiply-accumulate counts as two). Times are the paper’s measurements on a NUCLEO-F746ZG, Cortex-M7 at 216 MHz.

No single layer is the problem. The first convolution has the most output (32 KB), the third has the most weights (50 KB), and the second takes the most time (42.8 ms). Memory and time peak in different places. A memory plan has to look at the whole network, not one layer.

Add up the output column and you get 55 KB of activations in total. The weights are 87 KB. The paper reports that the whole run took 99.1 ms, which is 10.1 images per second, with 79.9% accuracy on the test set (the same network in floating point scored 80.3%).

The number that surprised the authors

The paper gives one more number. With its tuned kernels the maximum memory footprint was about 133 KB. Without one trick in the convolution kernel (Chapter 6 explains it), the footprint would be about 332 KB, and the paper says the network “would not fit on the board.” The board has 320 KB.

Read that again. The weights and activations did not change. A different way to compute the same layer moved the need from 332 KB to 133 KB. On a microcontroller, memory is a design choice at every level: the data, the order of the layers, the kernel inside each layer.

The hero at the top lets you play with the first two choices. The rest of this lesson builds the machinery underneath, so you can predict the numbers before you flash.

The road

  1. The parts: the model file, the op resolver, the interpreter, the arena and the kernels.
  2. The tensor arena: one array, two stacks, and the call that sizes it.
  3. From shapes to bytes: how one layer’s shape fixes its memory and its work.
  4. The memory planner: how tensors share space because they live at different times.
  5. Order decides the peak: how the sequence of layers changes the arena.
  6. Kernels that count in pairs: CMSIS-NN, the DSP instruction and the scratch buffer.
  7. Operator fusion: why ReLU should not be a separate step.
  8. When it does not fit: measuring, failing and what to change.
  9. Field guide: numbers, checklist, code and sources.
A model has 87 KB of weights and the chip has 320 KB of SRAM and 1,024 KB of flash. Which statement is the most accurate?

Chapter 1

The Parts of an On-Chip Inference

Follow one image from a file on your laptop to ten numbers on the chip, and name every piece it touches

Picture a vending machine that sorts coins. You drop a coin in, a few levers move, and a number comes out. Running a network on a chip works the same way. An image goes in, a fixed chain of steps runs, and ten scores come out. Five pieces make that happen, and each one lives in a different place.

Piece one: the model file

On your laptop you train in a framework such as Keras. You then convert the network to a .tflite file. This file is a FlatBuffer: a binary format that a program can read in place, without first parsing it into new objects. The file holds the graph (which layers, in what order, with which shapes) and all the weights, already quantized to int8.

The chip has no file system, so you turn the file into a C array with a tool such as xxd -i. The compiler then places the array in flash, as const data. The TFLM paper says it chose FlatBuffers because the format needs no unpacking: the library points straight at the bytes in flash. That is why the weights cost no SRAM.

Piece two: the op resolver

The graph says “convolution, then pooling”. Something must map each name to code. The op resolver is that table. You register only the operations your model uses, for example AddConv2D(), AddMaxPool2D() and AddFullyConnected(). The linker then leaves out every kernel you did not register. A model with three operation types carries three kernels, not a hundred.

Piece three: the interpreter

The interpreter is a small loop. It walks the list of operations in the order the file gives. For each one it finds the kernel, hands it the input and output tensors, and calls it. The paper measured this walking cost. On a Cortex-M4 it was under 0.1% of the cycles for the person-detection model, and 3.3% to 4.1% for the tiny Google Hotword model. The work is in the kernels, not in the loop.

Piece four: the kernels

A kernel is the C function that does one layer’s arithmetic. TFLM ships simple reference kernels that run on any chip. For a Cortex-M you can swap in the CMSIS-NN kernels with one build flag. Current TFLM builds do it with OPTIMIZED_KERNEL_DIR=cmsis_nn on the make command line, together with TARGET=cortex_m_generic and a core such as TARGET_ARCH=cortex-m7. Same model, same interpreter, different loops inside. On the person-detection model the paper saw more than a 4 times speedup on a Cortex-M4.

Piece five: the tensor arena

The last piece is memory for the activations. There is no malloc here. You give the interpreter one array, the tensor arena, and it carves everything it needs out of that array. The paper explains why: it assumes the system has no dynamic allocation, and it avoids allocating after start-up so a long-running device never suffers heap fragmentation. The next chapters are about this array.

Find the five pieces

Flash is on the left and SRAM on the right. Pick a piece to light up where it lives. Block heights are not to scale.

Illustrative layout for the CIFAR-10 network on an STM32F746ZG. The 87 KB of weights and the 40 KB of arena are computed in this lesson; the code sizes depend on your build, so those blocks carry no number. The interpreter figure is the TFLM paper’s.

What the file also carries

An int8 tensor is not only bytes. The model file attaches to each one a scale (how much real value one integer step stands for) and a zero point (the integer that stands for real zero). Without them the numbers are meaningless. The interpreter copies a small record for each tensor into the arena at start-up, which is part of why the arena has a persistent end. Chapter 2 shows that end, and the next lesson in this track, Quantization in Firmware, shows how the kernels use these two numbers.

The whole program

All five pieces meet in about twenty lines of C++. Read it once now. The comments say where each object lives.

c++// TensorFlow Lite Micro: set up once, then classify many images.
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "model_data.h"                 // const unsigned char g_model[] = {...};  in FLASH

constexpr int kArenaSize = 48 * 1024;
alignas(16) static uint8_t tensor_arena[kArenaSize];   // SRAM (.bss): all activations live here

static tflite::MicroInterpreter *interp;

bool nn_setup() {
  static tflite::MicroMutableOpResolver<3> resolver;      // only the 3 ops this model uses
  resolver.AddConv2D(); resolver.AddMaxPool2D(); resolver.AddFullyConnected();
  const tflite::Model *model = tflite::GetModel(g_model);   // points INTO flash, no copy
  static tflite::MicroInterpreter si(model, resolver, tensor_arena, kArenaSize);
  interp = &si;
  return interp->AllocateTensors() == kTfLiteOk;          // plan + carve the arena (Ch 2 to 5)
}

int nn_classify(const int8_t *img) {                       // img: 32 x 32 x 3 = 3,072 int8 values
  TfLiteTensor *in = interp->input(0);               // shape [1, 32, 32, 3], type int8
  memcpy(in->data.int8, img, 3072);
  if (interp->Invoke() != kTfLiteOk) return -1;       // run the 7 operations, in file order
  TfLiteTensor *out = interp->output(0);              // shape [1, 10], type int8
  int best = 0;
  for (int i = 1; i < 10; i++) if (out->data.int8[i] > out->data.int8[best]) best = i;
  return best;
}

Count what the data does. The input is 3,072 int8 values, one byte each. Invoke() runs seven operations. The output is ten int8 scores, and your code picks the largest. Nothing in this path allocates. Everything the operations need was reserved inside AllocateTensors(), which is where the next chapter goes.

In the program above, which object does tflite::GetModel(g_model) read, and where does that object live?

Chapter 2

The Tensor Arena: One Array, Two Stacks

Open the array TFLM carves everything from, and learn how to read its size off the chip instead of guessing

Imagine a single long bench in a workshop. Tools for the whole job go on the bench, and there is no other table. You place the tools you will keep all day at the right end. You place the tools for the current step at the left end, and you clear them when the step is over. As long as the two groups do not touch in the middle, the bench is big enough.

The tensor arena works exactly like this. It is the one array you hand to the interpreter, and TFLM keeps two stacks inside it (a stack is a region that grows in one direction as you add items). One stack starts at the left end and grows right. The other starts at the right end and grows left. The paper says that when the two stack pointers cross, there is a lack of capacity.

What goes on each end

The right end is the tail, and the source code calls its contents persistent. These live as long as the interpreter does. Examples are the descriptions of each tensor (their shape, type and quantization numbers), the bookkeeping for each operation, and any state a kernel keeps between calls. In the allocator source, persistent memory starts at the highest address and moves down.

The left end is the head, and its contents are non-persistent. These are the activations: the buffers that hold the image and every layer’s output while the network runs. They also include the scratch buffers some kernels ask for (Chapter 6). The head starts at the lowest address and moves up.

There is a third use. During start-up the library needs short-lived data, for example while it plans. It uses the free space between the two stacks, and gives it back when planning ends. The paper explains the reason: preparing the model needs data that inference no longer needs, so there is no need to keep it.

The start-up call, step by step

All of this happens inside AllocateTensors(). In order:

  1. Read the graph. The interpreter reads the list of tensors and operations from the FlatBuffer in flash.
  2. Allocate the persistent data. It builds a record for every tensor and operation at the tail. These are small.
  3. Prepare each operation. Each kernel looks at its tensor shapes and may request a scratch buffer, or store some precomputed numbers at the tail.
  4. Plan the activations. The memory planner (Chapter 4) decides where every activation and scratch buffer sits, and returns one number: the size of the head.
  5. Commit. The head is set to that size. If the head and the tail still do not cross, the call returns kTfLiteOk.

From then on nothing allocates. Invoke() only reads and writes the planned places. That is why a device can run for a year without heap trouble.

Run AllocateTensors

Pick a model, set the arena size, then press Run. The blue head grows from the left and the pink tail from the right. Shrink the arena until they collide.

12 KB

Persistent (tail) and non-persistent (head) sizes for the first three models are Table 3 of the TFLM paper, measured on a Sparkfun Edge (Ambiq Apollo3, Cortex-M4): 1.29 and 7.75, 12.12 and 0.68, 26.50 and 55.30 kilobytes. For our CIFAR net the head is the planner result from Chapter 4 and the 3 KB tail is a made-up round number.

How big should the arena be?

Nobody can add this up by hand. The TFLM get-started page says the size depends on the model and may need to be found by experimentation. There is a better method, because the interpreter can tell you. Its header has a method arena_used_bytes(), available after AllocateTensors(). The comment on it says it “gives the optimal arena size”.

The recipe has four steps. First, give the arena a size that is clearly too big. Second, call AllocateTensors(). Third, print arena_used_bytes(). Fourth, set the arena to that number plus a small margin, and flash again. The same header adds a detail: the array should be 16-byte aligned. If it is not, the best size is arena_used_bytes() + 16. That is why the example code in Chapter 1 wrote alignas(16).

// bring-up: one line tells you the real size printf("arena used: %u of %u bytes\n", (unsigned) interp->arena_used_bytes(), (unsigned) kArenaSize); arena used: 9262 of 49152 bytes // example output: now set kArenaSize to about 9.5 KB

When the arena is too small

The symptom is that AllocateTensors() returns an error and the log prints a line that begins Failed to resize buffer. Requested: ..., available ..., missing: .... That text is in the allocator source. The three numbers are in bytes. “Missing” is exactly how much bigger the arena must be. The measurement is one line, and the fix is to raise kArenaSize by at least that amount.

The opposite error costs you silently. An arena that is 20 KB too large still runs, but those 20 KB of SRAM are gone for your stack, your buffers and your radio. This is why you size from arena_used_bytes() and not from habit.

On real hardware. Board: STM32 Nucleo-F746ZG (or any Cortex-M with 256 KB or more of SRAM). Build the example from Chapter 1 with a 128 KB arena. Print arena_used_bytes() over the serial port. Shrink the array to that size plus 16 and confirm the model still runs. Then shrink it by 1 KB more and read the missing number in the error line.
Your code calls AllocateTensors() and it fails with “missing: 3,200”. What is the most direct fix?

Chapter 3

From Shapes to Bytes

Read the memory and the work of any layer straight off its shape, before you write a line of firmware

A shipping clerk can tell you the size of a parcel without opening it: length times width times height. A network layer is the same. You can know how many bytes its output takes, and how many multiplications it needs, from its shape alone. This is the skill that lets you budget memory on paper.

A tensor is a block of numbers

A tensor is a block of numbers with a shape. An image is a tensor with three dimensions: height, width and channels (three for red, green and blue). TFLite stores image tensors as [N, H, W, C]. N is the batch size, always 1 on a chip. The CMSIS-NN header documents the same order for the input of its convolution: [N, H, W, C_IN]. This order is called NHWC, and the channel value changes fastest in memory.

With int8 data each number is one byte. So a tensor’s size in bytes is just the product of its dimensions. A 32 by 32 image with 3 channels is 32 × 32 × 3 = 3,072 bytes. The same image in float32 would be 12,288 bytes, four times more. That fourfold saving is the first reason to quantize.

The output shape of a convolution

A convolution slides a small window (the kernel, here 5 by 5) over the input. At each position it multiplies the window by a set of weights and adds the results into one number. With same padding (zeros added around the border) and stride 1 (the window moves one pixel at a time), the output has the same height and width as the input. With stride 2 the height and width are halved, rounded up.

The depth of the output is set by the number of filters. Each filter has its own weights and produces one output channel. So a layer that maps 32 channels to 64 channels has 64 filters, and each filter sees all 32 input channels.

Three formulas

Take a convolution with kernel K by K, Cin input channels, Cout output channels, and an output of Ho by Wo. The three numbers we need follow directly.

Bout
Bytes of the output tensor in int8. This is SRAM, and it decides the arena.
Bw
Bytes of the weights in int8. This is flash. (Each output channel also has one 32-bit bias, which is small.)
MACs
Multiply-accumulates: one multiply plus one add. Every output number takes K²Cin of them. This decides the time.

Notice what depends on what. The output bytes depend on the picture size and the filter count. The weight bytes do not depend on the picture size at all. The work depends on everything. A bigger picture raises SRAM and time but leaves flash alone. That is exactly what you saw in the hero when you dragged the image size.

A worked example

Take the third layer of the CIFAR network from Chapter 0: Conv 2 in our naming, with a 16 by 16 input of 32 channels, a 5 by 5 kernel and 32 filters.

  1. Output shape. Same padding and stride 1 keep 16 by 16. There are 32 filters, so the output is 16 × 16 × 32.
  2. Output bytes. 16 × 16 × 32 = 8,192 bytes, which is 8 KB. This matches the paper’s table.
  3. Weight bytes. 5 × 5 × 32 × 32 = 25,600 bytes, which is 25 KB. This matches the table.
  4. MACs. Each of the 8,192 outputs needs 5 × 5 × 32 = 800 MACs, so 8,192 × 800 = 6,553,600 MACs.
  5. Operations. The paper counts a multiply and an add as two operations, so 13.1 million. This matches the table.

The paper’s pooling rows also check out. Pool 1 is listed with 73.7 K operations and 8,192 outputs. That is 9 per output, which means a 3 by 3 window. We never needed to be told: the shapes gave it away.

Size a layer

Set the input and the filters. The bars show the input, the output, the weights and the convolution scratch buffer. Switch to float32 and every bar grows four times.

16 px
32
32
5 by 5
1

Formulas as in this chapter, same padding. Scratch is the CMSIS-NN arm_convolve_s8 buffer for cores without Helium (two columns of int16, row length rounded up to a multiple of 4); the depthwise kernel is not modelled, so it shows no scratch. Biases are not counted.

You double the image side from 32 to 64 pixels in a network of 3 by 3 convolutions. What happens to the weight bytes of each convolution and to its output bytes?

Chapter 4

The Memory Planner

Let tensors that live at different times share the same bytes, and watch 58 KB of tensors shrink to 40 KB

A hotel does not build one room for every guest who will ever visit. Guests arrive and leave. Room 12 hosts one guest on Monday and another on Wednesday. The hotel only needs enough rooms for the busiest night.

Activation tensors are the guests. In Chapter 3 we saw that the network makes seven outputs plus the input, and that their sizes add up to 58 KB. But the first convolution’s output is only needed until the pooling layer has read it. After that its 32 KB are dead. If the next tensors take over those bytes, the arena can be much smaller than the sum.

Lifetime: the only thing the planner needs

The lifetime of a buffer is the span from the first operation that uses it to the last operation that uses it. Number the operations 1, 2, 3 and so on. In a straight chain, the output of operation k is written by k and read by k + 1, so it lives from step k to k + 1. The input is alive at steps 0 and 1. Two buffers may share bytes only if their lifetimes do not overlap.

Now draw it. Put time (the operation number) on the horizontal axis and the address in the arena on the vertical axis. Every buffer becomes a rectangle: as wide as its lifetime, as tall as its size. A valid plan is a way to place the rectangles so that none overlap. The arena size is how tall the pile gets. The paper shows this same picture in its Figure 4, and calls the task a kind of bin packing.

The greedy algorithm

Finding the perfect packing is hard. The TFLM source says the problem is NP-complete, which means no known method is fast for every input. So TFLM uses a simple rule of thumb, the GreedyMemoryPlanner. The header of greedy_memory_planner.h describes it in steps:

  1. Sort the buffers by size, largest first.
  2. Place the largest at offset zero.
  3. For each next buffer, look only at the placed buffers that are alive at the same time as it, in address order.
  4. Take the first gap between them that is big enough. If there is none, put the buffer after the last one.
  5. When all are placed, the peak (the highest end address) is the arena size for the head.

Placing big buffers first leaves small holes for small buffers. The planner also rounds every size up to a multiple of 16 bytes, which is why the 10-byte final output takes 16.

Worked example: our network

Here is what the algorithm did for the CIFAR network at 32 pixels. We ran the same steps in the page. The sizes are from Chapter 3.

  1. Conv 1 out, 32,768 B, alive in steps 1 to 2. It is the largest, so it goes at offset 0.
  2. Pool 1 out, 8,192 B, steps 2 to 3. It overlaps Conv 1 out at step 2, so it cannot touch offset 0. It goes at 32,768.
  3. Conv 2 out, 8,192 B, steps 3 to 4. Conv 1 out died at step 2, so offset 0 is free. It goes back to 0.
  4. Input, 3,072 B, steps 0 to 1. It overlaps Conv 1 out, so it goes after it, at 32,768, where Pool 1 out will arrive later.
  5. The small tensors fill the holes that remain. The conv scratch buffers (304 B, 3,200 B and 3,200 B, each alive for one step) slot in as well.

The highest end address is 40,960 bytes: 40 KB. The naive sum was 58 KB, plus 6.5 KB if you also give each scratch buffer its own space. The planner saved 18 KB without the scratch and 25 KB with it.

There is a floor under this number. At step 2, Conv 1 out (32 KB) and Pool 1 out (8 KB) are both alive, and 32 + 8 = 40 KB. No plan can do better than the busiest step. Here the greedy plan reaches that floor exactly. In general it does not always reach it, which is why the source calls the result “decent” and not best.

Pack the arena

Each rectangle is a buffer: wide as its lifetime, tall as its size. Compare the naive layout with the TFLM greedy plan, then raise the image side and watch which step sets the peak.

32 px

The greedy planner is a line-by-line port of greedy_memory_planner.cc from tflite-micro (sizes rounded up to 16 bytes). The network is the CIFAR-10 CNN; other image sides scale its sizes by the formulas of Chapter 3.

Try 64 pixels. The naive total is 232 KB and the plan is 160 KB. At 96 pixels the plan is 360 KB, and no placement trick can bring it under 320 KB. Only a smaller tensor can.

Failure mode: the peak is too tall

The symptom is the error from Chapter 2: the arena will not fit. The measurement is the step where the live buffers add up to the most. In our network that is the first pooling. The fix is not a bigger plan. It is a smaller peak: a smaller input, fewer filters in the first layer, or a first layer with stride 2. All three shrink the biggest tensor. Chapter 8 returns to this.

TFLM also supports an offline plan. A host tool can compute a better layout and store the offsets in the model’s FlatBuffer metadata. The runtime then skips planning. This helps when a smarter packer finds a smaller arena than the greedy rule does. The interface is visible in the source as the extra offline_offset argument of AddBuffer.

Two activation buffers of 8 KB each have lifetimes of steps 2 to 3 and steps 5 to 6. How much arena do they need together?

Chapter 5

Order Decides the Peak

Change only the sequence of two branches and watch the arena grow by 16 KB, with no change to any weight

You are packing for a trip with two bags to fill. You already hold a coat. If you pack the small bag first, you carry the coat while you handle the big pile of clothes. If you pack the big bag first, you carry the coat only through the small job. The coat is the same and the bags are the same. Only the order differs, and with it how much you juggle at once.

Networks with branches have this property. Our CIFAR network is a straight chain, so there is only one order. But many real models, such as those with skip connections, or those that read two sensors in two branches, have a choice. The result of one branch must wait, in memory, while the other branch runs.

Who decides the order?

The interpreter does not choose. It loops over the operators in the order they appear in the model file, one by one. In micro_interpreter.cc that is a plain for loop over the list. The converter wrote that list when you made the .tflite file. So the order is baked in before the chip ever sees the model.

The memory planner then works on whatever order it is given. The same graph in two valid orders gives two different sets of lifetimes, and so two different arenas.

A small example with two branches

Imagine a device with two sensors. Branch A reads an 8 KB input, makes a 40 KB tensor, then reduces it to 4 KB. Branch B reads a 4 KB input, makes a 24 KB tensor, then expands it to 30 KB. A final step joins the two results into a 16 KB tensor. All numbers are int8 bytes, and all sizes are made up for this example.

Both inputs are in memory from the start, because the application fills them before Invoke(). We now compute the live memory at each step for the two orders.

Order 1: branch A first.

  1. Step 1, A makes its 40 KB tensor. Live: input A 8 + A’s tensor 40 + input B 4 = 52 KB.
  2. Step 2, A reduces to 4 KB. Live: 40 + 4 + input B 4 = 48 KB.
  3. Step 3, B makes its 24 KB tensor. Live: A’s 4 KB result + input B 4 + 24 = 32 KB.
  4. Step 4, B expands to 30 KB. Live: 4 + 24 + 30 = 58 KB.
  5. Step 5, join. Live: 4 + 30 + 16 = 50 KB.

The most memory ever live at once is 58 KB. The greedy planner of Chapter 4 packs it into 62 KB: 4 KB above that floor, because its early placements leave a gap that a later buffer cannot use. This is the price of a quick rule.

Order 2: branch B first. Now B’s 30 KB result sits in memory while A runs. At step 3, A makes its 40 KB tensor, and the live set is B’s 30 + input A 8 + 40 = 78 KB. The floor is 78 KB, and the planner reaches it: 78 KB.

The rule falls out of the arithmetic. Whatever a branch leaves behind stays alive while the other branch runs. So run first the branch whose leftover is small, and run last the branch whose leftover is large. Here A leaves 4 KB and B leaves 30 KB. The best order is A, then B: 62 KB against 78 KB, a saving of 16 KB.

Reorder the branches

Pick which branch runs first. Then drag the size of branch B’s result and find where the best order flips.

30 KB

Illustrative sizes, not a real model: input A 8 KB, A tensor 40 KB, A result 4 KB, input B 4 KB, B tensor 24 KB, join 16 KB. Placement is the TFLM greedy planner of Chapter 4.

Drag B’s result down to 4 KB. The two orders become nearly equal. Drag it to 60 KB and order 2 gets very bad. The order matters most when one branch leaves a lot behind and the other has a tall peak of its own.

Skip connections: the same effect, built in

A skip connection (also called a residual connection) adds a block’s input to its output. The input must therefore stay alive for the whole block. In a block that widens the data in the middle, the widest tensor and the stored input are live together. That sum is often the peak of the whole network. If you want to cut the arena, look at the skip first.

Researchers go further than reordering. The MCUNet line of work, taught in MCUNet and TinyEngine, designs the network so its peak activation fits and rewrites kernels to work in place. This lesson stays with the plain TFLM planner, which is what you will meet first.

Failure mode

The symptom: a model that looks small is stuck above your SRAM limit. The measurement: read the planner’s busiest step, as the device above does, and check which tensors are alive then. The fix: reorder the branches in the model code, convert again, and print arena_used_bytes() to confirm. If the converter keeps your order you win the difference. If it picks its own order, compare the two numbers and keep the smaller.

On real hardware. Board: STM32 Nucleo-F746ZG. Build a Keras model with two branches that join. Convert it twice, with the branches defined in swapped order. Print arena_used_bytes() for both and compare with this page’s prediction. If the two numbers are equal, the converter chose the order, and you have learned that too.
Branch X leaves a 2 KB result and has a tall 50 KB peak. Branch Y leaves a 40 KB result and has a 20 KB peak. Which order gives the smaller arena?

Chapter 6

Kernels That Count in Pairs

See how CMSIS-NN does two multiplications per instruction, why it needs a scratch buffer, and what that buys in milliseconds

Two clerks count ballots. The first lifts one ballot at a time. The second lifts two at once, one in each hand. The second clerk finishes in half the time, but needs a little table space to lay the ballots out. A fast kernel is the second clerk. The table space is the scratch buffer.

What a kernel computes

Every output number of an int8 convolution is a dot product. Take the 75 input values under one 5 by 5 window of a 3-channel image, and the 75 weights of one filter. Multiply them in pairs and add up the products in a 32-bit accumulator (a register wide enough that the sum cannot overflow). Add the bias. Then requantize: scale the 32-bit sum back down to an int8 number. The int8 values carry a zero point (the int8 value that stands for real zero), so the kernel adds an offset to each input first. The CMSIS-NN header documents that field as “the negative of the zero value for the input tensor”.

For our first layer that is 75 multiply-accumulates per output number, and 1,024 × 32 output numbers. Chapter 3 gave the total: 2.46 million MACs for this layer alone.

The Cortex-M trick: SMLAD

The Cortex-M4 and M7 have a DSP extension: extra instructions for signal-processing arithmetic. One of them is SMLAD, a dual 16-bit multiply with accumulate. It treats each 32-bit register as two 16-bit halves. It multiplies the low halves, multiplies the high halves, and adds both products to the accumulator. That is two MACs in one instruction. The CMSIS-NN paper builds its kernels around it. The README names the targets: a Cortex-M4, or an M33 with the optional DSP extension. Cores without it (the README gives M0 and M3 as examples) always have a pure C version of each operator.

The M55 and M85 add MVE, also called Helium, a vector extension. The buffer-size code in the source shows its width: 16 int8 elements per vector register.

There is a catch. SMLAD works on 16-bit pairs, but the data is 8-bit. The kernel must first expand int8 values to int16, two at a time. The paper does this expansion once per piece of data and reuses it across many output channels, so the cost is spread thin.

Two MACs in one instruction

Press New numbers. The first column multiplies one pair per instruction. The second packs two int8 values into each int16 pair and uses two SMLAD instructions.

Idealised: it counts multiply-accumulate instructions only. Real kernels also spend instructions on loads, on the int8 to int16 expansion and on loop control, which is why the measured speedups below are 2.6 to 5.4 times and not an exact 2 times per instruction.

The convolution as a matrix product

A convolution is awkward for SIMD, because the windows overlap. The standard fix is im2col (image to column). Copy each window into one column of a big table, so that all the windows sit side by side. The convolution then becomes a plain matrix multiply, which maps well onto SMLAD.

The price is memory, because overlapping windows repeat pixels. The paper says it plainly: im2col increases the footprint because pixels in the input are repeated in the output matrix. So CMSIS-NN uses a partial im2col. It expands only a few columns at a time (the paper says e.g. 2), enough to get the full speed of the matrix kernel with little extra memory.

Now the numbers. Full im2col for Conv 2 would need one column per output position, 16 × 16 = 256 of them, each with 5 × 5 × 32 = 800 values. At one byte each that is 204,800 bytes, about 200 KB. The paper reports 133 KB with partial im2col and 332 KB without. The gap, 199 KB, matches that 200 KB within a kilobyte. This is our own arithmetic, not a statement in the paper, but it explains why the network “would not fit on the board”.

The partial buffer is small. The source of arm_convolve_s8_get_buffer_size (the version for cores without Helium) is two columns of int16, with the column length rounded up to a multiple of 4. For Conv 2: 2 × 800 × 2 bytes = 3,200 bytes. For Conv 1: the column is 75, rounded up to 76, so 2 × 76 × 2 = 304 bytes. These are the scratch buffers you saw in the planner picture in Chapter 4.

Where the scratch comes from

You do not call the CMSIS-NN size function yourself. The TFLM kernel in kernels/cmsis_nn/conv.cc does. During the prepare step it asks CMSIS-NN how much scratch the layer needs, and requests that many bytes from the arena with RequestScratchBufferInArena. The planner then treats it as one more buffer that lives for one step. At run time the kernel passes the buffer to arm_convolve_wrapper_s8 and the library does the rest.

What it buys

The paper compared CMSIS-NN against a baseline built from the older CMSIS-DSP convolution, plus plain pooling and ReLU. On the STM32F746 at 216 MHz, the convolutions went from 443.4 ms to 96.4 ms, a 4.6 times speedup, and the whole network from 456.4 ms to 99.1 ms. Energy improved 4.9 times. The TFLM paper saw the same effect on the person-detection model: CMSIS-NN kernels gave more than a 4 times speedup on a Cortex-M4 (18,990.8 K to 4,857.7 K cycles). For the small Google Hotword model the gain was only about 25%, because the kernel loops are a smaller share of its run time.

Kernel cycle table

Switch kernels and slide the clock. The faint bar behind each layer is the other kernel.

216 MHz

CMSIS-NN per-layer times are the paper’s Table 1 (Cortex-M7, 216 MHz). Baseline times are the CMSIS-NN time of each layer multiplied by the paper’s per-type ratio (convolution 4.6, pooling 5.4); they add up to 457 ms against the paper’s 456.4 ms. Other clocks assume time scales as 1 over the clock, which real chips break with flash wait states and caches. Illustrative.

At 216 MHz the fast network spends about 21.4 million cycles on 12.3 million MACs. That is 1.7 cycles per MAC. The baseline spends 8.

The call underneath

c// What TFLM's cmsis_nn/conv.cc ends up calling for each int8 convolution (simplified).
cmsis_nn_context ctx = { scratch_ptr, scratch_bytes };       // the buffer the planner placed (Ch 4)
cmsis_nn_conv_params cp = {
  .input_offset  = -input_zero_point,                        // added to every int8 input first
  .output_offset = output_zero_point,
  .stride = {1, 1}, .padding = {2, 2}, .dilation = {1, 1},
  .activation = { act_min, act_max }                         // clamp: this is where ReLU lives (Ch 7)
};
cmsis_nn_dims in  = {1, 16, 16, 32}, flt = {32, 5, 5, 32}, bias = {1, 1, 1, 32}, out = {1, 16, 16, 32};
// dims are NHWC for data, [C_OUT, HK, WK, C_IN] for the filter
arm_cmsis_nn_status s = arm_convolve_wrapper_s8(&ctx, &cp, &per_channel_quant,
                         &in, in_data, &flt, filter_data, &bias, bias_data, &out, out_data);
On real hardware. Board: STM32 Nucleo-F746ZG (Cortex-M7, 216 MHz). Enable the cycle counter: set bit 24 (TRCENA) of DEMCR at 0xE000EDFC, zero DWT_CYCCNT at 0xE0001004, then set bit 0 (CYCCNTENA) of DWT_CTRL at 0xE0001000. Read the counter before and after Invoke(). Build once with reference kernels and once with OPTIMIZED_KERNEL_DIR=cmsis_nn, and compare the ratio with this page.
Why does CMSIS-NN use a partial im2col instead of expanding the whole input at once?

Chapter 7

Operator Fusion: Do Two Steps in One Pass

Move ReLU inside the convolution and remove a whole 32 KB tensor from the arena

On a sandwich line, one worker spreads the butter and passes the bread to a second worker, who adds the cheese. Between them sits a tray. If one worker does both jobs, the tray disappears. The sandwich is the same. There is less to carry and less table to keep clear.

Operator fusion is this idea for networks. Two neighbouring operations become one. The first operation’s result never goes to a tensor in the arena. It goes straight into the second operation’s arithmetic, while the number is still in a register.

The end of a convolution

Recall Chapter 6. For each output number, the kernel ends with four small steps. It has the 32-bit accumulator, then it adds the bias, then it scales the sum down to int8 (requantization), and then it stores the byte. That last store has a hidden fifth part: a clamp, which cuts the value to a chosen range [min, max] before it is stored. Every int8 store needs one anyway, because the range of int8 is only −128 to 127.

Now think about ReLU, the common activation: it keeps positive numbers and turns negative ones to zero. In int8 the number that means real zero is the zero point, call it z. So ReLU is exactly a clamp whose minimum is z. It is a clamp with a different lower limit.

That is the whole trick. If the convolution already clamps, then ReLU costs nothing extra: set the minimum to z and keep the maximum at 127. The data format records this. In the TFLite schema, the convolution options carry a field named fused_activation_function. In TFLM’s conv_common.cc the kernel turns that field into output_activation_min and output_activation_max. CMSIS-NN receives them in its parameter struct as cmsis_nn_activation, whose fields are min and max, described in the header as “used to clamp the result”.

Worked example: one output number

Use made-up but typical values. The scale from accumulator to output is M = 0.01 (illustrative). The output zero point is z = −100. The accumulator holds −600.

  1. Scale. −600 × 0.01 = −6.
  2. Add the zero point. −6 + (−100) = −106.
  3. Clamp without ReLU. The range is [−128, 127]. The byte stored is −106. It stands for a real value below zero.
  4. Clamp with ReLU fused. The range is [−100, 127]. −106 is below the minimum, so the byte stored is −100. That stands for real zero.

Now compare with an unfused graph. The convolution stores −106 into a 32 KB tensor. A separate ReLU operator then reads that whole tensor and writes another 32 KB tensor holding −100. The values end up the same. But there was an extra pass over 32 KB, and an extra 32 KB tensor in the arena.

Fuse the ReLU

Top: one output number goes through scale, zero point and clamp. Drag the accumulator below zero and toggle the fusion. Bottom: the arena peak of the whole network with and without a separate ReLU operator.

-600
32 px

The scale M = 0.01 and zero point −100 are made up for the example. The arena bars use the CIFAR-10 network of this lesson and the greedy planner of Chapter 4, with the separate ReLU written as one more operator after each convolution.

At 32 pixels the unfused graph needs a 64 KB arena and the fused graph needs 40 KB. The peak moves from the pooling step to the ReLU step, where the whole convolution output and the whole ReLU output are alive together. At 96 pixels the gap grows to 216 KB.

Other fusions you already have

Bias. The bias add is part of the convolution kernel, as you saw in the call in Chapter 6. Requantization. The int32 accumulator never becomes a tensor. It lives in a register and is scaled before it is stored. Batch normalization. The converter folds it into the convolution before you ever see the model. A batch-norm layer computes y = γ(x − μ)/σ + β, and because the convolution is linear, you can multiply the weights by γ/σ and adjust the bias once, offline. The lesson NN Building Blocks derives this folding. After it, the layer is gone from the file.

The paper hints at the time side too. In its Table 2, a separate ReLU cost 1.06 ms with the baseline code and 0.4 ms with CMSIS-NN. That is small next to 99.1 ms. The memory is the bigger prize, because an extra tensor can decide whether the model fits at all.

Failure mode: a fusion that did not happen

The symptom is an arena larger than your own arithmetic predicts. The measurement: list the operators in the model (any FlatBuffer viewer will do) and look for a standalone ReLU or add after a convolution. The fix is to write the model so the converter can fuse. A fusion is blocked when something else needs the value before the activation, for example a skip connection that reads the convolution output. Then both the pre-activation and the post-activation tensor must exist.

In an int8 network, what does a fused ReLU change inside the convolution kernel?

Chapter 8

When It Does Not Fit: Measure, Then Shrink the Peak

Turn a vague “it crashes” into one of three numbers, and pick the cheapest lever that moves it

A doctor does not treat “I feel bad”. She asks where it hurts and takes a temperature. An on-chip network that misbehaves needs the same questions. There are three budgets, and each has its own gauge. Once you read the gauge, the fix is usually clear.

Three budgets, three gauges

The prerequisite lesson Where Memory Goes covers the stack side: how deep the interpreter’s own call chain goes, and how to find the high-water mark. The arena does not protect you from a stack overflow. They share the same SRAM.

Symptom, measurement, fix

SymptomMeasurementFix
Linker stops: “region RAM overflowed by N bytes”N, the exact overshoot; the arena is the biggest array in bssShrink the arena to arena_used_bytes(), or lower the peak (below)
Start-up error: “Failed to resize buffer ... missing: N”N bytes missing; the planner peak in Chapter 4Raise the arena by N if SRAM allows; otherwise lower the peak
It runs, but takes far longer than expectedCycles per MAC from the DWT counter; the CMSIS-NN build gave about 1.7Check that the build used OPTIMIZED_KERNEL_DIR=cmsis_nn and the right TARGET_ARCH
Hard fault (the chip stops on an illegal memory access) in the first Invoke()Fault address and stack high-water markAlign the arena to 16 bytes; give the task a larger stack
Runs, but the answers differ from the laptopCompare int8 outputs for one fixed input, layer by layerA quantization problem, not a memory one: see the next lesson in this track

The levers that lower the peak

Because the arena is set by the busiest step, the cheapest fix is the one that shrinks the biggest tensor at that step. Here is the order to try them, from least to most work.

  1. Quantize to int8. Float32 uses four bytes per value. This is a fourfold cut in the arena and in the weights.
  2. Fuse activations (Chapter 7). This removes whole tensors.
  3. Reorder branches (Chapter 5). This is free if your model has branches.
  4. Use a stride-2 first layer. The first layer sees the largest image. With stride 2 it makes an output one quarter the size. This costs some accuracy, so measure it.
  5. Reduce the input size. The arena grows with the square of the image side. Going from 96 to 64 pixels cuts the planned arena in this lesson from 360 KB to 160 KB.
  6. Use fewer filters in the first layers. They set the biggest activations.
  7. Change the method. Process the image in patches, as MCUNet does (see MCUNet and TinyEngine). This trades extra compute for a lower peak.

Will it fit?

Pick a chip and a model setup. The two bars show the weights against flash and the arena against SRAM. Try to rescue a failing setup with the levers below.

80 px

The model is the CIFAR-10 CNN of this lesson scaled to the chosen side. Flash shows weights only (the interpreter and kernels add more, so it is a lower bound). SRAM shows the arena only (stack and other globals add more). The stride-2 option halves the size the network sees after the first layer and is shown as an input of 3 values per pixel at the full side. Float32 is four times the bytes. The RP2040 runs code from external flash, whose size is a board choice, so it is shown against 2 MB as an illustration. Chip memory sizes are from the vendors’ product specifications.

Start at 80 pixels on the first chip. It fits. Switch to the nRF52840 and the arena is just under its limit. Now turn off int8 and watch every chip fail. Then rescue the setup using only the other two controls.

On real hardware. Board: nRF52840 DK (256 KB RAM) or the Nucleo-F746ZG. Before you flash, read arm-none-eabi-size and compare its bss with your arena. After you flash, print arena_used_bytes() and the DWT cycle count. Write all three budgets on one line in your notes. When something fails later, you can tell which one moved.
The linker reports “region RAM overflowed by 24,000 bytes” right after you enlarged the model. The arena is a 150 KB array. What is the best first step?

Chapter 9

Field Guide: Numbers, Checklist and Sources

Keep the numbers, the steps and the code of this lesson on one page, and find where to go next

The lesson in one paragraph

A network on a Cortex-M is a FlatBuffer model in flash, an op resolver that links only the kernels you use, an interpreter that walks the operators in file order, and one tensor arena in SRAM. The arena has a persistent tail and a planned head. The greedy planner gives every activation an address by its lifetime, so the head is as tall as the busiest step, not the sum of all tensors. CMSIS-NN kernels run int8 layers with SMLAD pairs and a small im2col scratch buffer. Fusion moves ReLU and bias into the convolution and removes whole tensors. You read arena_used_bytes() for SRAM, the linker for flash, and the DWT counter for time.

The numbers that matter

WhatNumberSource and why it matters
CIFAR-10 CNN, int887 KB weights, 55 KB activations, 24.7 M operationsCMSIS-NN paper, Table 1. Weights and activations peak in different layers
Run time on STM32F746, 216 MHz99.1 ms per image (10.1 images per second)CMSIS-NN paper. A real measurement for the same chip as this lesson
Accuracy, float vs int880.3% vs 79.9%CMSIS-NN paper. Quantizing cost 0.4 points here
Footprint, partial vs full im2colabout 133 KB vs about 332 KBCMSIS-NN paper. The full version would not fit in 320 KB
CMSIS-NN against baseline loops456.4 ms to 99.1 ms; 4.6 times faster, 4.9 times less energyCMSIS-NN paper, Table 2
Person detection on Cortex-M4 (96 MHz)18,990.8 K to 4,857.7 K cycles, more than 4 timesTFLM paper, Table 2a. Kernels matter more than the interpreter
Interpreter overhead on Cortex-M4under 0.1% to 4.1% of cyclesTFLM paper, Table 2a. The loop is cheap
Arena memory, three models9.04, 12.80 and 81.79 KB (persistent plus non-persistent)TFLM paper, Table 3. Either half can dominate
Arena alignment16 bytesmicro_interpreter.h: otherwise add 16 to arena_used_bytes()
Our network, 32 px: naive vs planned58 KB vs 40 KB (greedy, with 6.5 KB of scratch hidden inside)This lesson’s arithmetic with the TFLM greedy rule
Conv scratch (5 by 5 by 32, no Helium)2 × 800 × 2 = 3,200 bytesarm_convolve_s8_get_buffer_size
Fused ReLU, 32 pxarena 40 KB instead of 64 KBThis lesson’s arithmetic. A separate operator adds a whole tensor
Chip memoriesSTM32F746ZG 1,024 KB flash and 320 KB SRAM; nRF52840 1 MB and 256 KB; RP2040 264 KB SRAMVendor product pages and datasheets

The terms

TermPlain meaning
Tensor arenaOne array in SRAM that holds every activation, scratch buffer and record
Head and tailThe non-persistent (planned) end and the persistent end of the arena
LifetimeFirst to last operation that touches a buffer
Greedy plannerPlace the biggest buffers first, each in the first gap among buffers alive at the same time
KernelThe C loop that does one operation’s arithmetic
SMLADOne instruction that multiplies two pairs of 16-bit values and adds both products
im2colCopying overlapping windows into columns so a convolution becomes a matrix product
FusionDoing two operators in one pass with no tensor between them

The checklist

  1. Count first. Write the shape, the output bytes, the weights and the MACs for each layer (Chapter 3).
  2. Find the busiest step. Add the live buffers at each step and note the biggest sum (Chapters 4 and 5).
  3. Quantize and fuse. int8 everywhere, with activations fused into the convolutions (Chapter 7).
  4. Build with the right kernels. OPTIMIZED_KERNEL_DIR=cmsis_nn and the correct TARGET_ARCH (Chapter 6).
  5. Start with a big arena. Read arena_used_bytes(), then trim to that plus a margin (Chapter 2).
  6. Align the array. alignas(16).
  7. Read the three gauges. arm-none-eabi-size, the arena, the DWT cycle count (Chapter 8).
  8. Keep a record. Write the three numbers in your notes after each model change.

The core as code

This is the planner rule in plain C, so you can hold it in your head. It follows the steps in greedy_memory_planner.h. It is a teaching version, not a copy of the library code.

ctypedef struct { int size, first, last, off; } buf_t;      // bytes, first and last step alive, chosen offset

static int overlaps(const buf_t *a, const buf_t *b) {      // alive at the same time?
  return !(a->first > b->last || b->first > a->last);
}

int plan(buf_t *b, int n) {                           // b[] already sorted: largest size first
  int peak = 0;
  b[0].off = 0; peak = b[0].size;                   // the largest goes at offset 0
  for (int i = 1; i < n; i++) {
    int cand = 0;                                   // candidate offset
    for (;;) {                                      // walk placed buffers in address order
      int next = -1, best = 1 << 30;
      for (int j = 0; j < i; j++)                    // the next overlapping buffer above cand
        if (overlaps(&b[i], &b[j]) && b[j].off + b[j].size > cand && b[j].off < best)
          { best = b[j].off; next = j; }
      if (next < 0 || b[next].off - cand >= b[i].size) break;   // room before it? take the gap
      cand = b[next].off + b[next].size;                  // else move past it
    }
    b[i].off = cand;
    if (cand + b[i].size > peak) peak = cand + b[i].size;
  }
  return peak;                                          // the size of the head (round up to 16)
}

Where this sits in the field

TFLM is one way to run a network on a chip. Other tools generate C code for each model instead of interpreting it, trading flexibility for lower overhead (the TFLM paper names several, among them TinyEngine, TVM and STM32Cube.AI). Chips with Helium, small NPUs and DSPs change which operators run where, and that is the next lesson in this track. The memory ideas stay the same: lifetimes, a peak, and a plan.

Keep going

Sources

Everything above comes from these primary sources, opened for this lesson.

What we did not open: the Arm Architecture Reference Manual itself. The DWT and DEMCR register addresses in Chapter 6 were cross-checked on several secondary pages, so confirm them in the ARMv7-M manual or your chip’s reference manual before you rely on them. The STM32F746ZG memory sizes came from ST’s product page and the Zephyr board page, not from the datasheet PDF. Chapter 1 and 2 byte counts for the CIFAR network are this lesson’s own arithmetic, labelled where they appear. The in-page devices are models: they do not run a Cortex-M.

The takeaway. A network on a microcontroller is a memory plan first and a computation second. Count the bytes of each layer, find the busiest step, let tensors share space by lifetime, and use kernels and fusion that give memory back. Then measure the three gauges on the real board.
A planned arena is 160 KB on a chip with 128 KB of SRAM. Which change is most likely to make it fit with the least work?

Now press Present or Teach and explain, from memory, why 58 KB of tensors need only 40 KB of arena. Draw the rectangles. Then go back to the bar at the top, choose Planned plus flash, drag the image side to 96 pixels, and say which step you would shrink first.

A Network on a Cortex-M
TFLM paper · CMSIS-NN paper · CMSIS-NN · TFLM source · Back to Gleams