[back]

The TPU from a program: software user manual

How to write Linux user programs for the unit of tpu_mcore on the Mercury+ KX2: the matrix array (MPU) and the vector station (VPU), through the AME instructions. Every operation has a C snippet; the complete programs are in sw/examples/.

State of this manual: 2026-11-25. The matrix instructions and the kernel support run on the board at 200 MHz (measured figures are marked "measured"). The VPU instruction xl8.vop passes in simulation and is in a bitstream being built; its figures are marked "simulation".

1. The system

the system as a program sees it

Two instruction sets

A program reaches the unit through two sets of instructions, both issued by the hart and executed by the unit:

set name what it is instructions
the matrix instructions AME, the RISC-V Attached Matrix Extension (the draft "Ztt", v0.6) a proposed standard: tiles, accumulators, the product; the subset this unit runs ame.acquire, ame.release, msettyp, mgettyp, mzero.acc, mls, mss, mmulacc, mmov.m.a
our own Xl8, l8's vendor extension what AME does not have: the VPU's vector operations on a tile xl8.vop (CUSTOM-1, funct7 0x58)

AME's encodings are the draft's and may change with it. Xl8 uses the opcodes RISC-V reserves for vendors. It is not the RISC-V vector extension (V): the hart is RV32IMA and has no vector registers; the VPU's "vectors" are the rows of a tile. (xl8.call, on the shape3 unit, is the other Xl8 instruction; this unit does not have it.)

Two ways into the unit from a program:

way what the program does when
AME instructions (this manual) issues the instructions itself, matrices in its own memory the standard way; no device, no driver call
/dev/tpu jobs (libtpu, section 9) describes a whole product as a job; the driver runs it on the tensor memory large products of any shape; needs the 1.5 GByte tensor memory

2. A first program

#include "l8ex.h"                     /* of sw/examples; it includes ame.h */

int main(void)
{
    uint8_t *h = ex_huge();           /* 4 MiB that is one page for the unit */
    int8_t  *a = (int8_t *)h;                         /* A: 128 rows of 256 int8 */
    int8_t  *b = a + 128 * 256;                       /* B: 256 rows of 64 int8  */
    int32_t *c = (int32_t *)(b + 256 * 64);           /* C: 128 rows of 64 int32 */

    /* ... fill a and b ... */

    ex_own();                         /* ame.acquire: the unit is this process's */
    msettyp(0, T8); msettyp(1, T8);   /* tiles 0 and 1 hold int8 */
    mzero_acc(0);                     /* accumulator 0 = 0 */
    mls_st(0, a, 256);                /* tile 0 = A, its rows 256 bytes apart */
    mls_st(1, b, 64);                 /* tile 1 = B, its rows 64 bytes apart */
    mmulacc(0, 0, 1);                 /* accumulator 0 += tile 0 x tile 1 */
    msettyp(0, T32); mmov_m_a(0, 0);  /* the sums into tile 0, as int32 */
    mss_st(0, c, 64 * 4);             /* tile 0 to C, its rows 256 bytes apart */
    ame_barrier();                    /* C is in memory now */
    ame_release();
    return 0;
}

Build and run:

make -C sw/examples                   # every example, static, with the image's compiler
make up                               # in cpu/riscv/tpu: the bitstream, Linux, ssh
make test                             # every example onto the board and run

To build one file by hand: riscv32-buildroot-linux-musl-gcc -O2 -static -I<path to ame.h> -o prog prog.c (the compiler is linux-p0/linux/build/output/host/bin/, ame.h is cpu/tensor/shape3/test/ame/ame.h).

No compiler generates these instructions. ame.h defines each one as a macro around the assembler's .insn directive, which emits the instruction word from its fields. mmulacc(0, 0, 1) is one 32-bit word in the program. Tile and accumulator numbers are fields of that word, so they must be compile-time constants (mls_st(t, ...) with a variable t does not compile: write the cases out, as mpu_gemm does).

3. The model

the unit behind the instructions

3.1 Tiles, accumulators, types

constant value elements
T8 0x40000008 int8
T16 0x40000010 int16
T32 0x40000020 int32
T64 0x40000040 int64 (the sums at x32)

3.2 The shapes on the KX2

The unit has a fixed shape; a tile is always the whole of it. The operands' type selects the width the array runs at.

width A and B elements A tile B tile C C element
x8 int8 128 rows of 256 elements (256 bytes a row) 256 rows of 64 columns (64 bytes a row) 128 x 64 int32
x16 int16 128 rows of 256 elements (512 bytes a row) 256 rows of 64 columns (128 bytes a row) 128 x 64 int32
x32 int32 128 rows of 64 elements (256 bytes a row) 64 rows of 64 columns (256 bytes a row) 128 x 64 int64

So one multiply is C(128 x 64) += A(128 x K) B(K x 64) with K = 256 (x8, x16) or 64 (x32). A longer K is done a tile of K at a time into the same accumulator (section 5.1). A smaller matrix is padded with zeros.

The sums are 48 bits wide inside (80 at x32) and saturate when they are narrowed to the tile's type.

3.3 Where a tile may lie in memory

A load or a store names the tile's first byte and the distance between its rows (the stride). The unit takes it directly when all of this holds:

  1. the first byte is on a 64-byte line (the address is a multiple of 64);
  2. the stride is a multiple of 64;
  3. the whole tile, from its first byte to its last row's end, lies inside one page of the program: a 4 KiB page or a 4 MiB huge page.

Nearly every tile is larger than 4 KiB, so in practice: put the matrices into a huge page (ex_huge(): mmap with MAP_HUGETLB; the kernel is booted with hugepages=4).

If a tile does not fit, nothing goes wrong: the hart traps, and the kernel emulates the instruction by copying the rows through a tile of its own. The result is the same, the time is not (measured, 16 pages of K at x8: 0.64 ms in a huge page, 107 ms from malloc).

3.4 Ownership

The unit belongs to one address space at a time.

3.5 What is queued, and the barrier

mls, mss, mmulacc, mmov.m.a, mzero.acc and xl8.vop are queued: the instruction returns as soon as the unit has taken the command, and the unit runs the queue in order, overlapping what can overlap (the next tile loads while this one multiplies).

So after mss_st the result is not yet in memory. ame_barrier() returns when the queue is empty. Always issue one before reading C, before freeing or unmapping a matrix the unit may still read, and before timing. ame_release and mgettyp are barriers too.

3.6 What the kernel does

4. The instructions

All are macros of ame.h. md, ms, acc, a, b are literal numbers; p is an address, s a stride in bytes, t a type value: these three are ordinary C expressions.

4.1 ame_acquire -- take the unit

unsigned long r = ame_acquire(1);     /* 1: granted;  2: busy, another address space has it;  8: bad descriptor */
if (r != 1) { /* try again later, or do the work on the hart */ }

The argument is the request descriptor: pass 1. Asking again while owning it answers 1 and restarts the unit's counters. ex_own() of l8ex.h is this with an error exit.

4.2 ame_release -- give it back

ame_release();                        /* waits for the queue, then the unit is free */

By a process that does not own the unit it changes nothing (and still waits for the queue).

4.3 msettyp -- a tile's element type

msettyp(0, T8);                       /* tile 0 holds int8: an A tile of 128 x 256 bytes */
msettyp(1, T8);                       /* tile 1 holds int8: a B tile of 256 x 64 bytes   */
msettyp(0, T32);                      /* ... later: tile 0 will receive int32 sums       */

Set the type before loading a tile and before moving sums into it. An unknown value sets amestatus.UN and changes nothing. The types of the tiles of a multiply decide the width: both operands int8 is x8, int16 is x16, int32 is x32. Changing the width waits for the queue (a barrier inside the unit).

4.4 mgettyp -- read a tile's type (and wait)

unsigned long t = mgettyp(0);         /* the value msettyp wrote; returns when the queue is empty */

4.5 mzero_acc -- an accumulator to zero

mzero_acc(0);                         /* the next mmulacc on accumulator 0 starts from zero */

4.6 mls_st -- load a tile from memory

/* an A tile (tile 0 or 2): 128 rows, each `256 * element bytes` long, `stride` bytes apart */
mls_st(0, a, 256);                    /* x8: rows of 256 bytes, contiguous                        */
mls_st(0, a + p * 256, k);            /* x8: columns p*256 .. of a 128 x k matrix (rows k apart)  */
mls_st(0, a16, 512);                  /* x16: rows of 256 int16                                   */

/* a B tile (tile 1 or 3): K rows, each one column-row of the weights */
mls_st(1, b, 64);                     /* x8: 256 rows of 64 bytes, contiguous: one long burst     */
mls_st(1, b16, 128);                  /* x16: 256 rows of 64 int16                                */

The rows of an A tile may lie anywhere a stride apart, which is how a wide matrix is cut into tiles of K without copying. B's rows are best contiguous (stride = the row's bytes): the DMA then reads them as one burst.

A load into a tile whose page is still multiplying waits in the queue; the program does not.

4.7 mmulacc -- multiply and accumulate

mmulacc(0, 0, 1);                     /* accumulator 0 += tile 0 x tile 1   (page 0) */
mmulacc(0, 2, 3);                     /* accumulator 0 += tile 2 x tile 3   (page 1) */
mmulacc(1, 0, 1);                     /* into accumulator 1 instead                  */

The operands must be one page's pair: (0, 1) or (2, 3), A copy first. Both must have been loaded since the grant. Anything else sets amestatus.UN and does nothing.

4.8 mmov_m_a -- the sums into a tile

msettyp(0, T32);                      /* the width to narrow to */
mmov_m_a(0, 0);                       /* tile 0 = accumulator 0, each sum saturated to int32 */

The destination is an A copy (tile 0 or 2). The accumulator keeps its value: more products can be added and moved out again. With T8 or T16 the sums saturate to 8 or 16 bits directly (no scaling: for scaling use xl8.vop).

After the move the tile holds C in C's layout: 128 rows of 64 elements, a row 64 * element bytes long.

4.9 mss_st -- store a tile to memory

mss_st(0, c, 64 * 4);                 /* x8 / x16: 128 rows of 64 int32, rows 256 bytes apart */
mss_st(0, c64, 64 * 8);               /* x32: 128 rows of 64 int64                            */
ame_barrier();                        /* now it is there                                      */

Stores what the tile's type says: after mmov_m_a, C. Rows stride bytes apart; contiguous rows are one burst. A tile that was not loaded or moved into since the grant: amestatus.UN, nothing stored.

4.10 ame_barrier -- wait for the unit

ame_barrier();                        /* returns when every queued command is done */

4.11 amestatus -- did the unit refuse something?

amestatus_clear();
/* ... instructions ... */
ame_barrier();
if (amestatus() & 1) { /* an instruction was unsupported or had nothing to work on (UN) */ }

UN is sticky until cleared. It is how a program finds out that the bitstream has no xl8.vop (section 4.12), or that it read a tile it never loaded. It is not a trap: the program goes on.

4.12 xl8_vop (Xl8) -- the VPU on a tile (simulation; in the next bitstream)

The Xl8 instruction. The tile is an A copy (0 or 2); the second argument is a descriptor made by a macro.

/* QLD: the channels' parameters into the VPU's table.
 * The parameters: 16 bytes a channel -- int32 bias, M, Mp, Mn -- contiguous from the tile's first byte.
 * They are loaded as an ordinary int8 A tile (128 rows of 256 bytes: reserve 32 KiB, the rest unused). */
msettyp(2, T8);
mls_st(2, par, 256);
xl8_vop(2, XL8_VOP_QLD(64));            /* 64 channels */

/* REQ8: every int32 of the tile to its int8, in place.  Element i uses channel i modulo 64:
 *   t = x + bias          y = sat16(round(t * M >> SQ))          o = sat8(round(y * (y > 0 ? Mp : Mn) >> SH)) */
xl8_vop(0, XL8_VOP_REQ8(12, 14, 64));   /* SQ = 12, SH = 14, 64 channels */

/* the tile is now PACKED: 128 rows of 64 int8, contiguous */
mss_st(0, out, 64);
ame_barrier();

the VPU

4.13 Not on this unit

These AME instructions decode but the unit answers amestatus.UN: mmov_a_m (a tile into an accumulator), mzero_m, mmulaccneg, the transposed products, a multiply of tiles that are not a page's pair, and every other word of the AME opcode. The VPU's other operations (GELU, softmax, layernorm) exist in the unit but have no instruction form yet.

5. Recipes

5.1 K longer than a tile

void gemm(const int8_t *a, const int8_t *b, int32_t *c, int pages)     /* A 128 x (256*pages), B (256*pages) x 64 */
{
    int k = 256 * pages;
    mzero_acc(0);
    for (int p = 0; p < pages; p++) {
        if (p & 1) { mls_st(2, a + p * 256, k); mls_st(3, b + p * 256 * 64, 64); mmulacc(0, 2, 3); }
        else       { mls_st(0, a + p * 256, k); mls_st(1, b + p * 256 * 64, 64); mmulacc(0, 0, 1); }
    }
    if ((pages - 1) & 1) { msettyp(2, T32); mmov_m_a(2, 0); mss_st(2, c, 256); }
    else                 { msettyp(0, T32); mmov_m_a(0, 0); mss_st(0, c, 256); }
    ame_barrier();
}

The two tile pairs take turns: while page 0 multiplies, the DMA loads page 1. The sums are moved into the page that multiplied last. Complete: examples/mpu_gemm.

5.2 More than 128 rows or 64 columns

Run the product once per block of 128 rows of A (the same B tiles again) and once per block of 64 columns of B. Each block is an independent accumulator's worth; use accumulator 0 for one and 1 for the next if you want two results to stand at the same time.

5.3 A convolution

A convolution is a product of the neighbourhoods with the weights. The hart builds A: one row per output position holding its kh * kw * channels input bytes (padded to K); B is the weights as K x 64; C is the 128 positions times 64 output channels.

for (int pos = 0; pos < 128; pos++)                     /* im2col: the hart's part */
    for (int tap = 0; tap < 9; tap++)
        memcpy(a + pos * 256 + tap * CI, neighbour(in, pos, tap), CI);
mls_st(0, a, 256); mls_st(1, weights, 64); mmulacc(0, 0, 1);

Complete, with zero padding and the check against the convolution written out: examples/mpu_conv3x3.

5.4 A filter bank, a correlation

Any "sum over k of x[k] h[k]" for many x and many h at once is a product: 128 signal windows against 64 filters of 256 taps is one mmulacc. examples/mpu_firbank finds a template planted in a noisy signal.

5.5 A dense layer with its activation

mls_st(0, x, 256); mls_st(1, w, 64); mmulacc(0, 0, 1);           /* W x                */
msettyp(0, T32); mmov_m_a(0, 0);
mls_st(2, par, 256); xl8_vop(2, XL8_VOP_QLD(64));                  /* bias, scale, ReLU  */
xl8_vop(0, XL8_VOP_REQ8(12, 14, 64));
mss_st(0, y, 64);                                                /* int8 out           */

examples/mlp_layer runs two such layers and falls back to the hart's ex_req8() on a unit without xl8.vop.

5.6 16-bit data

Type the operands T16; A's rows are then 512 bytes, B's 128. examples/mpu_gemm16.

5.7 Sharing the unit

while (ame_acquire(1) != 1) usleep(1000);       /* wait for the other process */
/* ... */
ame_release();                                  /* release between pieces of work, so others get a turn */

6. The MPU in detail

the MPU

7. Performance notes

what figure source
array, while a product runs 99.4 % of the clocks busy (x8, x32), 99.1 % (x16) measured
128 x 4096 x 64 int8, huge page 0.64 ms measured
the same from malloc (kernel emulation) 107 ms measured
VPU, REQ8 while it runs 91 % of four elements a clock simulation
the hart 50 MHz; about 4 microseconds for one element of a requantisation measured (the network's run)
JPEG decode on the hart 27 ms for a 38 x 32 window, 3.5 s for 1280 x 720 measured
TCP through Linux 0.11 MByte/s out, 0.46 in (the hart is the limit) measured
the debug link into the DDR3 9.2 MByte/s out, 7.1 in measured

What follows for a program:

  1. Keep matrices in a huge page. One tile outside it costs more than the whole product.
  2. Let the unit work while the hart prepares the next operand: instructions return at once, so build the next A between mmulacc and the barrier.
  3. The hart is the slow part. Copies (im2col), checks and any per-element arithmetic on the hart decide the time of a network, not the products. Move per-element work into xl8.vop.
  4. Bulk data to and from a host goes over the debug link, not through the board's TCP.

8. When something goes wrong

what you see why what to do
Illegal instruction at an AME instruction the unit is not this process's (no ame_acquire, or it answered BUSY) acquire first; check its result
Segmentation fault at mls_st / mss_st the tile reaches unmapped memory the tile's full size: rows x stride, not the matrix's
the result is all zero or stale read before the barrier ame_barrier() before reading C
amestatus() & 1 an unsupported instruction, a tile not loaded since the grant, a wrong tile pair section 4; clear it and check after each step to find which
a product is hundreds of times slower a tile is not in one page or not on 64-byte lines: emulated huge page, 64-byte alignment of base and stride
no huge page none reserved boot with hugepages=4 (the image does)
wrong sums at the edges the tile is always full size: the unused rows and columns were not zero zero the padding of A and B

The unit's own counters (rows multiplied, the span) are reset by ame_acquire and can be read over the debug link (sw/ame_bare.py prints them).

9. The other way: jobs through /dev/tpu

libtpu (in examples/superresolution) describes a product of any shape as one job; the driver checks it and the unit's job path runs it on the tensor memory (1.5 GByte at 0xA000_0000, mapped into the program).

#include "libtpu.h"

tpu_t t;  tpu_mat a, b, c;  tpu_stats st;
if (tpu_open(&t)) return 1;                              /* /dev/tpu, the tensor memory mapped        */
tpu_mat_alloc(&t, &a, 128, 4096, 1);                     /* rows, columns, bytes an element; zeroed   */
tpu_mat_alloc_tight(&t, &b, 4096, 64, 1, 1);             /* a matrix that is never an A               */
tpu_mat_alloc_tight(&t, &c, 128, 64, 4, 0);
*(int8_t *)tpu_at(&a, 3, 17) = 5;                        /* an element's address                      */
tpu_gemm(&t, &a, &b, &c, &st);                           /* C = A B, saturating to C's element        */
printf("%llu clocks, the array %.1f %% of the span\n", (unsigned long long)st.clocks, 100.0 * st.rows / st.span);
tpu_close(&t);

tpu_gemm_win takes A as windows on memory that is not copied (a convolution's input map). examples/superresolution runs the 34-layer super-resolution network this way, each layer against its reference.

10. The examples

folder shows section
mpu_gemm the product, K over several tiles; huge page against malloc 5.1, 3.3
mpu_gemm16 int16 operands 5.6
mpu_firbank a bank of FIR / matched filters as one product 5.4
mpu_conv3x3 a convolution layer by im2col 5.3
vpu_requant xl8.vop: QLD and REQ8 against the hart's formula and time 4.12
mlp_layer two dense layers with ReLU, the requantisation in the VPU or on the hart 5.5
superresolution the demo's network through /dev/tpu 9

Each prints <name> ok; make test in cpu/riscv/tpu uploads and runs them all.

[back]