[back]

Hot Chips in my pocket
Tensors. Today: TPU behind RISC-V:
Zooming into a pixel with the TPUle1

It runs on a Mercury+ KX2 at 200 MHz.

Not Google's design, but its idea, built from scratch: a weight-stationary multiply-accumulate array, a TPU in the small, written in l8 and exported as plain Verilog. A RISC-V hart (RV32IMA with caches, an MMU, CLINT, PLIC and a 16550 UART) only feeds it: it issues AME matrix instructions, and the unit behind them does the work.

what is inside: the hart in its quarter clock, the crossings, the unit, one memory port

What is inside

The unit behind the instructions

the unit: the front, the engine's queue, the two pages with their tiles, the MPU, the accumulators, the VPU, the DMA

An AME instruction does not run in the hart. The front checks that the unit is the program's and that the tile lies in one page of its memory, and turns the instruction into a command for the engine's queue. The hart goes on at once; a barrier instruction waits until the queue is empty. The engine runs the commands in order and lets them overlap where they can: the next tile loads while this one multiplies.

The MPU

the MPU: 16 columns of 32 chained DSPs in four groups, A streaming, B standing, the shapes

The array is a grid of multiply-accumulate cells: on the KX2 16 columns of 32 DSP48s. Inside a column the cells are chained, each handing its running sum to the next over the DSP's own cascade wires, so a column is one long sum of products.

How full it runs was measured on the KX2 from 2 to 128 tiles of K: the array takes a row in 99.4 % of the clocks between a product's first and last row (99.1 % at int16). What is missing is a fixed gap of 23 clocks at each change of tile (39 at int16), whatever the product's length: the DDR3 keeps up with the array.

The VPU

the VPU: the table, a lane's thirteen clocks, the tile before and after, a layer's instructions

A network's layer ends by turning its int32 sums back into int8: add the channel's bias, scale, apply the activation, saturate. On a 50 MHz hart that takes about 4 microseconds an element and is most of a network's time. The VPU does it in the unit, on the rows of a page's A copy.

In the simulation the VPU is 91 % full while it runs (a region of 768 elements takes 210 clocks: 192 for the elements, 18 to start and drain). In a stream of load, REQ8 and store it is busy about half the time and waits for the DMA the rest.

The demo: zooming onto a car

A car on a highway interchange, about 20 pixels long in a drone's recording, followed through six seconds and enlarged four times by a network that runs on the unit. From the left: the scene with the tracked window, the view as recorded, the view enlarged by bicubic interpolation, by the network (realesr-general-x4v3 with 8-bit weights and activations: 34 convolutions of 3 x 3 with 64 channels, 1470 million multiply-adds a window), and by a second, fifteen times larger network for comparison. The enlarged views are held on the car's front by the host.

What is shown is simulated: the pictures are computed on the host by the integer model of the unit, the bytes the board has to return. What has been checked so far:

Not yet: the run on the board. The bitstream with xl8.vop has not met 200 MHz yet on this small part (the kept build, below, is the one before it), and the live page is being built: the viewer picks a car in the overview, the host follows it and sends each window through memory by the debug link, the board returns the enlarged window, and the page shows it at the rate actually reached.

Bicubic interpolation, the compact network, the large one (RRDBNet); each frame shown four times. The compact network is the demo's: on this clip its picture is the clearer one, at a fifteenth of the work. More on what is shown: the simulated demo's page.

The system

the KX2 as it runs: the host, the board's Linux, the hart's AME port, the unit, the DDR3

The system is the Mercury+ KX2 (an XC7K160T with 2 GByte of DDR3) on its PE1 base board, and a host PC.

make prog, make linux and make test in cpu/riscv/tpu program the board, boot it and run the examples on it.

The same core on the Arty

the Arty as it was run: host PC, the JTAG cable, the FPGA

On the Arty everything goes over the one USB cable, JTAG being the only link the board has here. l8net.jtag_proxy holds the cable and carries l8's debug-link datagrams. ame_bare.py --jtag uses them on two buses:

The hart runs the program, which drives the array through AME instructions. The host then reads C back and compares it with numpy. Inside the FPGA the core shares the DDR3 with the debugger through a merge in front of the MIG.

Numbers

Arty A7-100T Mercury+ KX2 (xc7k160t)
array 8 columns x 16 rows, 128 DSPs 16 columns x 32 rows, 512 DSPs
unit clock 81.25 MHz (the MIG's) 200 MHz
peak, int8 / int16 10.4 G multiply-adds a second 102.4 G multiply-adds a second
routed timing, l8 build met, +0.120 ns of slack met, +0.003 ns of slack
routed timing, around the exported Verilog met, +0.448 ns of slack NOT met, -0.221 ns
on the board C equal to numpy at int8, int16 and int32 over 16 pages; the array busy 99.8 %, 99.7 %, 99.8 % of the run C equal to numpy at int8, int16 and int32 over 16 pages; the array busy 99.4 %, 99.1 %, 99.4 % of the run. Under Linux, AME from a user program: 128 x 4096 x 64 at int8 in 0.64 ms

What the KX2 build takes of the device unit by unit, how full the array's DSPs run and what the board's DDR3 allows: the KX2 build, further down this page (as a page of its own).

The board run on the Arty was made on 2026-11-20 over the JTAG cable, the only link that board has here, with the column as it stood before the restructure below.

How 200 MHz was reached

The KX2 first missed 200 MHz by a third of a nanosecond, and the reason was in the multiply array. A column's running sum has to pass from one DSP to the next. The DSPs have a dedicated wire for exactly that (PCOUT to PCIN), but Vivado, left to infer it from the plain description, never used it: every row's sum went over general routing into the next DSP's C input, and in the full design four rows of every column fell out of the DSPs into 48-bit carry chains, 5.2 ns each.

Synthesizing one column on its own showed that whether the cascade is inferred depends on details the design cannot state: an 8-row chain cascaded, then stopped cascading once the weight passed through two registers with enables. So the column is now four segments, each holding every register of its rows, and on a 7-series part the compiler writes a segment as eight DSP48E1 cells linked PCOUT to PCIN. In simulation and in the exported Verilog the segment stays its plain l8 description. The cells were checked against that description in xsim on random inputs. Afterwards the KX2's worst path was in the DMA, no longer in the array.

The exported Verilog

tpu_mcore.v is one module, tpu_mcore #(JP, CB, R, MW, VL, HF), with no vendor cells: Vivado, Yosys and an ASIC flow can all take it. The generics are a short list on purpose: the module holds the shapes it was built and checked at (the Arty's and the KX2's), each as its own generate branch, and a check in the module refuses any other binding. The l8 design was not bent to make the export more general; a new shape is one more entry in the export's list. tpu_mcore_arty.v and tpu_mcore_kx2.v are one instance each.

The column's segment can be swapped: its module stands inside an ifndef, and the KX2 build compiles the DSP48E1 cascade in its place. The exported core runs the hart's AME program under Verilator with C equal to the integer product at all three widths, in the same number of clocks as the l8 design.

The generics

tpu_mcore #(JP, CB, R, MW, VL, HF): the shape's numbers a board chooses. They are a short list on purpose. The module holds the two shapes below, each built and checked, and refuses any other binding when it elaborates; the rest of the design's numbers are fixed in the export at the values both shapes share.

generic meaning Arty KX2
JP the array's columns 8 16
CB log2 of JP 3 4
R a row in bytes: the array is R DSPs high, and a stream row of A is R bytes 16 32
MW the memory line in bits (the port's data width); a whole number of rows, MW / 8R >= 1 128 512
VL the VPU's lanes, 32 bits each (a divisor of R / 4) 4 4
HF the hart's clock in MHz, as declared to the tools (the hart runs at clk / 4) 21 51

Fixed in the export:

generic meaning value
DB the pages' depth, log2 of their rows 12 (4096 rows)
AB the accumulators' words, log2 9 (512)
MA an AME tile's rows 128
GA, GB a tile's column groups at int8 and int32, at int16 4, 2
KA, KC a tile's K at int8 and int16, at int32 256, 64

A new shape is one more entry in the export's list (tpu_mcore_v.l8), built and checked like these two.

The mcore API: using the core in your own design

tpu_mcore speaks the mcore interface, the bigger sibling of the small cores' ucore interface: one memory port, a run line, a device window, a console and a few debug lines, and nothing else about the system. The board around it serves the memory (on the Arty and the KX2: the DDR3 controller), drives run after loading a program, and may talk to the hart's devices through the window. tpu_mcore.json in the download lists the same in machine-readable form.

The port groups of tpu_mcore

The port groups

group ports meaning
clock clk, rst (synchronous, active high) the unit's clock: the array, the pages, the DMA, the engine, the VPU and the memory port. The hart runs at clk / 4, made inside by a registered divider: constrain */slowr_reg/Q as a generated clock, asynchronous to clk. Every crossing between the two clocks is inside the module.
M, memory m_rd_req_*, m_rd_rsp_*, m_wr_req_*, m_wr_rsp_*, m_w_* AXI4's five channels (AR, R, AW, B, W) with up to four transactions outstanding each way. The unit's DMA (rows of A and B in, C out) and the hart's caches (line refills, word writes) are merged inside onto this one port. Addresses are physical: the hart's MMU has translated them, and the unit checks AME's against its window.
run run the hart leaves reset when run is 1; load the memory first. The hart starts at 0x8000_0000.
R, device window cmd1_* in, rsp1_* out the hart's devices for an outside master, as l8's debug-link datagrams on two byte streams with valid, ready and last
console urxd in, utxd out the 16550's serial line, 8N1, 512 clk cycles a bit
debug halted, wpc[31:0], irqu the hart has stopped; the pc of the last retired instruction; the unit's job is done (it also goes to the PLIC inside)

The memory handshake

  1. A beat moves on the rising clk edge where valid && ready on its channel; the sender holds the beat until then.
  2. A request (at the physical address, n the beats, opt the access's options) carries a tag; up to four are in flight each way, told apart by their tags.
  3. A read's n beats come back on rd_rsp with its tag, last on the n-th.
  4. A write's n data beats follow on w in the order the write requests were taken, last on the n-th; each write is answered once on wr_rsp with its tag.
  5. A line is MW bits: 128 on the Arty, 512 on the KX2. m_w_data_strb has one bit a byte.

What the hart sees

address what
0x0200_0000 CLINT (timer, software interrupts)
0x0C00_0000 PLIC
0x1000_0000 16550 UART
0x1003_0000 the unit's job registers
0x8000_0000 .. the memory port

The first four are also what the device window reaches from outside.

Programming it

The software user manual is the last part of this page (as a page of its own): how to write Linux user programs for the unit -- the model (tiles, accumulators, pages, ownership), every instruction with a C snippet, recipes (products, convolutions, filter banks, dense layers), the MPU and the VPU in detail, and the examples of sw/examples.

The hart drives the array with AME instructions, a RISC-V matrix extension (draft v0.6; opcode CUSTOM-1). No compiler knows them yet, so sw/ame.h in the download wraps each one as an .insn intrinsic. A program runs bare metal in M mode on physical addresses: there is no driver in between, and the unit sees the same memory as the hart.

The model

The shapes

A tile of A is 128 rows of K elements, a tile of B K rows of N columns, and the accumulator holds C = 128 x N. N is four times the columns: 32 on the Arty, 64 on the KX2.

operands K a tile C's elements
int8 256 int32
int16 256 int32
int32 64 int64

A longer K is a loop over tiles into the same accumulator: each mmulacc adds one tile's worth.

In memory

sw/ame_bare.py in the repository writes exactly this layout and checks C against numpy.

An example: the program that ran on the board

#include <stdint.h>
#include "ame.h"

#define PAR 0x8F000000u   /* the host writes the arguments here; DONE goes to 1 at the end */
asm(".section .text.init\n.globl _start\n_start:\n  la sp, _stack_top\n  call main\n1: j 1b\n");

struct par { uint32_t mode, sw, pages, ata, sta, ppa, atb, stb, ppb, atc, stc, done, ta, tb; };

void main(void)
{
    volatile struct par *p = (void *)PAR;
    uint32_t t = 0x40000008 + ((1u << p->mode) - 1) * 8, tc = 0x40000008 + ((1u << p->sw) - 1) * 8, pg, n = p->pages;

    ame_acquire(1);
    msettyp(0, t); msettyp(1, t); msettyp(2, t); msettyp(3, t);
    mzero_acc(0);
    for (pg = 0; pg < n; pg++) {            /* one K tile a page; the two pairs take turns */
        uint32_t a = p->ata + pg * p->ppa, b = p->atb + pg * p->ppb;

        if (pg & 1) { mls_st(2, a, p->sta); mls_st(3, b, p->stb); mmulacc(0, 2, 3); }
        else        { mls_st(0, a, p->sta); mls_st(1, b, p->stb); mmulacc(0, 0, 1); }
    }
    if ((n - 1) & 1) { msettyp(2, tc); mmov_m_a(2, 0); mss_st(2, p->atc, p->stc); }
    else             { msettyp(0, tc); mmov_m_a(0, 0); mss_st(0, p->atc, p->stc); }
    ame_release();
    p->done = 1;
}

Build it with any RV32 GCC (sw/Makefile): -march=rv32ima_zicsr -mabi=ilp32 -ffreestanding -nostdlib -nostartfiles -T link.ld, then objcopy -O binary. The linker script places it at 0x8000_0000, where the hart starts.

Running it on the Arty

From cpu/riscv/tpu/board/arty in the repository: make prog loads the bitstream, make link starts the JTAG proxy (leave it running), and make ame MODE=0 (1, 2 for int16, int32) runs ame_bare.py --jtag. That script holds the hart, writes the program and A and B into the DDR3, writes the arguments at 0x8F00_0000 and sets run. It then waits for DONE, reads C back and compares it with numpy, and reads the unit's counters through the device window.

Download the archive. It holds:

folder what
(top) the exported core: tpu_mcore.v, the two shape files, the KX2's DSP segment, tpu_mcore.json (the interface descriptor)
system the exported core in a system, in Verilog: the KX2 board design around tpu_mcore_kx2, constraints, Vivado script, make synth
kx2 the whole KX2 design in Verilog as built into the 200 MHz bitstream (the small MAC, Linux, AME from user programs), make synth to synthesise it again; that bitstream and its reports
linux what the board's Linux is built from: the buildroot tree with the kernel's AME patch, its hooks and the /dev/tpu driver, the device trees, the SBI firmware. The toolchain needs no patch
examples the Linux user programs of the manual, the super-resolution network with its data among them
host the PC's side: the debug link's client, the loader, the JTAG programming script
sw the bare-metal program ame_bare.c and ame.h

The archive's parts were put together on 2026-11-25 and have not been run from the archive yet. The built kernel image is not in it (it would carry its builder's ssh key): linux/build.sh builds it.

The KX2 build: what it uses, how full it runs, what the DDR3 allows

The figures of the bitstream the board runs were made on (the Mercury+ KX2, an XC7K160T; the baseline of 2026-11-25: the small MAC, AME from Linux user programs). The tables of this page are read from that build's own reports when the page is made.

Timing

Routed: worst setup slack +0.003 ns at 200 MHz, 0 of 246816 endpoints failing, worst hold slack +0.033 ns. The unit, its pages, the DMA and the DDR3 port run at 200 MHz; the hart at a quarter of it.

Utilization

every unit's share of the device

unit LUTs flip-flops block RAM tiles DSP48s what it is
MPU (the lane array) 10183 17844 48.0 512 16 columns x 32 DSP48s, their sums and accumulators
VPU 9099 6034 8.0 50 4 lanes, the channels' table, softmax and layernorm
store 9452 5352 0.0 0 the accumulators' words narrowed into a page
pages 2924 1620 121.0 0 the two pages' A and B copies (block RAM)
DMA 2938 1132 0.0 0 DDR3 lines to and from the pages
engine, front, registers 1702 2027 0.0 2 the queue, the AME front, the job registers, the counters
hart 8857 4048 8.0 4 RV32IMA, caches, Sv32, CLINT, PLIC, 16550
EMAC (small) 3916 3293 3.0 0 Linux's eth0 and the debug link's queue
the core's bridges and crossings 4953 4098 2.5 0 the hart's memory bridge, the clock crossings
debug link, workbench, merge 5427 5241 8.0 0 the debugger's bus, the memory merge, the Ethernet port
DDR3 controller (MIG) 12212 10173 0.0 0 Xilinx's controller with l8's port adapter
top 373 394 1.0 0 clocks, reset, pads
all 72036 61256 199.5 568
the XC7K160T has 101400 202800 325 600
used 71.0 % 30.2 % 61.4 % 94.7 %

How full the DSPs run

A DSP of the array does a multiply-add in every clock in which the array takes a row of A. Measured on the board (the unit's own counters: the rows taken, and the clocks from a product's first row to its last):

int8 int16 int32
array DSPs working, while a product runs 99.4 % 99.1 % 99.4 %
multiply-adds a second, while a product runs 101.8 G 101.5 G 25.4 G
the bound (512 DSPs x 200 MHz; at int32 four DSPs a product) 102.4 G 102.4 G 25.6 G
clocks lost at each change of tile 23 of 4119 39 of 4135 23 of 4119
array DSPs working over a whole job (B's load, the drain and C's store included; 16 tiles of K) 82.3 % 81.0 % 72.0 %

What the DDR3 allows

The unit's operands come from the DDR3 and its results go back, over one 512-bit port at 200 MHz: 12.8 GByte a second if every clock moved a line.

Measured on this board (2026-11-08, a traffic generator on the same port, three rounds, equal):

traffic GByte a second of the 12.8 peak
reads alone 9.1 to 9.4 72 %
writes alone 6.1 48 %
reads and writes at once 7.75 61 %
the pattern of an int8 tile (read, then written) 6.85 54 %
the pattern of an int16 tile 7.04 55 %

What the array asks of it (from the tiles' sizes and the measured time of a tile, 4096 rows and the gap):

bytes a tile (A + B) a tile takes the DDR3 must deliver of the reads' bound
int8 32768 + 16384 20.6 us 2.4 GByte/s 26 %
int16 65536 + 32768 20.7 us 4.8 GByte/s 51 %
int32 32768 + 16384 20.6 us 2.4 GByte/s 26 %

Software user manual: the TPU from a program

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.


1 TPUle -- Swabian etymology: the diminutive of TPU, 'little TPU' (the dialect's -le ending, as in Haisle, a small house).

[back]