Metadata-Version: 2.4
Name: vc4infer
Version: 1.2.11
Summary: ONNX inference engine for the Raspberry Pi VideoCore IV (V3D) QPUs
Author-email: rughinnit <rughinnit@users.noreply.github.com>
License: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/rughinnit/vc4-stack
Project-URL: Documentation, https://github.com/rughinnit/vc4-stack/blob/main/docs/VC4INFER.md
Keywords: onnx,videocore,raspberrypi,qpu,yolo,inference
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: POSIX :: Linux
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: numpy
Requires-Dist: onnx>=1.14
Requires-Dist: pillow

# libvc4infer 0.1.0

An inference engine layer for the Raspberry Pi's VideoCore IV GPU (V3D, Pi 3B,
stock clocks), built on top of the hand-written, element-verified QPU GEMM from
`/home/raspi/work/asm3`.

It is a **C library** (`libvc4infer`) plus tests, a kernel generator and a
Python/ctypes binding.  Everything GPU-side is a QPU kernel; the CPU only moves
bytes (padding, layout), never multiply-accumulate.  Any op, shape, layout or
dtype that is not implemented returns `VC4_ERR_UNSUPPORTED` — there is no CPU
compute fallback anywhere.

```
include/vc4infer.h      public API
src/vc4_dev.c           dma-buf arena, /dev/mem, V3D launch, L2/SLC handling
src/vc4_dev_remote.c    VC4INFER_DAEMON=1 backend: vc4d client (unprivileged)
src/vc4_kern.c          kernel blob cache + JIT, the asm3 two-launch rule
src/vc4_gemm.c          vc4_matmul: QPU pack -> verified QPU GEMM
src/vc4_conv.c          vc4_conv2d: QPU im2col -> GEMM (bias folded as a k term)
src/vc4_ew.c            add/mul/relu/sigmoid/silu/relu_bwd/rsqrt kernels
src/vc4_api.c           the op registry (strict dispatch) + coverage table
../training/src/vc4_train.c    transpose, C=A*B^T, fused softmax+CE backward
../training/src/vc4_convbwd.c  im2col/col2im, conv dX/dW, maxpool fwd/bwd
tools/kgen.py           QPU kernel generator (reuses the asm3 encoder)
tests/                  CPU-oracle verification, no fallback paths
python/vc4infer/        the Python package (ctypes binding, executor, CLI)
run_tests.sh            serialised, health-checked test runner
```

## Build and run

```sh
make                       # libvc4infer.a, libvc4infer.so, tests
mkdir -p kcache             # generated kernel blobs live here
sudo ./build/test_matmul 5  # 5 runs, every element checked
sudo ./build/test_conv 5
sudo ./build/test_ew 5
./run_tests.sh              # all of the above, with the GPU lock + health checks
```

The tests take `/tmp/vc4-gpu.lock` themselves and print a board state after
each stage.  **One GPU user at a time**: two concurrent workloads (or a wild
kernel) can hang the V3D hard enough to require a power cycle.

## Engine artifacts: `vc4infer build`

`vc4infer build model.onnx -o model.vc4x` writes the model after the
optimiser: the rewritten graph with its provenance records, conv weight panels
already packed into the arena layout, the arena plan with fixed offsets, and
the kernel blobs the plan launches.  `Engine("model.vc4x")` loads that plan
instead of planning and packing, and refuses a file whose kernel generator,
ABI, engine version or board was not the one it was built with.  The artifact
is hardware-specific; the ONNX file is not.

```sh
vc4infer build yolov8n_160.onnx -o yolov8n_160.vc4x   # 12.4 s, 25.1 MiB
vc4infer verify yolov8n_160.vc4x                      # hashes + every key
vc4infer bench  yolov8n_160.vc4x
```

On YOLOv8n at 160 the outputs are bit-identical to the ONNX path and the
steady-state launch count is the same 536; load falls from 3.21 s to 0.48 s and
the first run from 1.78 s to 1.46 s.  `--no-artifact` plans from the ONNX graph
the artifact carries.  Format, keys and measurements:
[`../docs/ENGINE-ARTIFACT.md`](../docs/ENGINE-ARTIFACT.md).

## Unprivileged mode: `VC4INFER_DAEMON=1`

By default the library maps `/dev/mem` itself and must run as root.  With
`VC4INFER_DAEMON=1` it instead talks to `vc4d` over `/run/vc4d.sock`; the
process needs no privilege, no `/dev/mem` and no capabilities.

```sh
# once
make -C /home/raspi/work/vc4d && sudo /home/raspi/work/vc4d/tools/install.sh
sudo usermod -aG vc4 raspi        # log in again

# unprivileged, through the daemon
REPS=5 VC4INFER_DAEMON=1 ./run_tests.sh
VC4INFER_DAEMON=1 ./build/bench_matmul 256 5
```

`make` links `$(VC4D_DIR)/build/libvc4client.a` (default
`VC4D_DIR=/home/raspi/work/vc4d`; override for another checkout).  The flag is
read at `vc4_init()`: unset or `0` keeps the direct path exactly as it was.

**What the backend does.**  `src/vc4_dev_remote.c` connects, `ALLOC`s one
region, `mmap`s the dma-buf fd the daemon passes over SCM_RIGHTS, and makes
that mapping `ctx->arena`; `ctx->gpu_bus` is the region's bus address from the
ALLOC reply.  Kernels are still generated by `tools/kgen.py` client-side and
uploaded on first use.  A launch is **one** round trip (`LAUNCH` with
`UNI_IN_ARENA|WAIT`): the op code has already written its uniforms through
`vc4__uni()` into the arena, the daemon validates every word and kicks the
QPUs.  `vc4_gemm.c`, `vc4_ew.c`, `vc4_conv.c`, `vc4_convbwd.c` and
`vc4_train.c` are unchanged apart from cache dirty marks at CPU-write sites.

**Security model.**  The client only ever holds a unix socket and a dma-buf
mapping.  `/dev/mem`, the V3D register block and the physical-base discovery
live in `vc4d`, which closes those fds and drops to `nobody` with
`CapEff=0` before serving requests.  The daemon still validates every uniform
word as "inside this arena" or "a literal outside the bus/arena/MMIO
windows", enforces one launch in flight, bounds the timeout and goes
permanently dead after a GPU timeout.  The honest caveat is unchanged: a QPU
program is raw machine code and can DMA anywhere, so `vc4d --strict` (program
SHA-256 allowlist, no raw SRQ writes) is the profile for an appliance.  The
`vc4` group is a mutual-trust group: all clients share one arena.

**Coherency.**  The CMA dma-buf mapping is *cacheable* on this kernel (not
write-combining), so the backend tracks CPU-dirtied ranges — uploads,
`vc4__write`, uniform blocks, per-op scratch and the output copies — and
`dc civac`s exactly those before each launch; `vc4_download` and
`vc4__l2_flush` invalidate the lines the CPU is about to read.  A full 62 MiB
clean would cost milliseconds; a 256³ matmul dirties ~1.5 MiB.

**Measured cost** (Pi 3B, stock core 400 MHz / V3D 300 MHz, same boot,
`bench_matmul`, 5 reps, best wall; `gpu` is the engine's pack+kernel time):

| size | path | gpu ms | gpu GFLOP/s | wall ms | wall GFLOP/s | wall overhead |
|---|---|---:|---:|---:|---:|---:|
| 256³ | direct root | 3.962 | 8.47 | 3.980 | 8.43 | — |
| 256³ | through vc4d | 3.998 | 8.39 | 4.289 | 7.82 | **+0.309 ms (7.8%)** |
| 128³ | direct root | 0.706 | 5.94 | 0.723 | 5.80 | — |
| 128³ | through vc4d | 0.771 | 5.44 | 0.942 | 4.45 | **+0.219 ms (30%)** |

At 256³ the QPU work is within 1% of the direct path and the caller-visible
wall time is 7.8% higher: two launches = two round trips (~50 µs each) plus a
~1.5 MiB dirty-range clean.  At 128³ the same fixed cost is 30% of a 0.72 ms
call (two round trips + ~320 KiB of cache maintenance, both size-independent),
so the 15% target is met for the size the engine is actually used at; 128³ is
launch-bound, not compute-bound.  The first 128³ run after boot is colder
(1.25 ms wall) because the client library and kernel blobs are not resident
yet; the direct path is insensitive to that.

The client-side proof is printed by `run_tests.sh` in this mode: the test
process has uid 1000, `CapEff=0`, and no `/dev/mem` in `/proc/PID/fd`.

## API surface

```c
vc4_status vc4_init(vc4_ctx **ctx, const char *cache_dir, size_t arena_bytes);
void       vc4_shutdown(vc4_ctx *ctx);
size_t     vc4_arena_bytes / vc4_arena_used;
vc4_status vc4_alloc(vc4_ctx*, size_t, vc4_buf*);          /* persistent   */
vc4_status vc4_upload / vc4_download / vc4_host_ptr / vc4_bus_addr;

vc4_status vc4_matmul (ctx, A, B, C, M, N, K, layout);
vc4_status vc4_conv2d (ctx, in, Cin, H, W, wt, Cout, KH, KW, bias,
                       stride, pad, out, &HO, &WO);
vc4_status vc4_elementwise(ctx, op, a, b, out, n);
vc4_status vc4_relu / vc4_sigmoid / vc4_silu (ctx, a, out, n);

const vc4_op_info *vc4_supported_ops(size_t *n);           /* coverage table */
int  vc4_op_supported(vc4_op);
void vc4_print_supported_ops(FILE*);
void vc4_get_stats(ctx, vc4_stats*);   /* launches, pack/kernel ns, FLOPs */
```

Buffers are `{off, bytes}` inside **one** dma-buf arena (64 MiB by default,
falling back to 32/16/8 MiB if CMA is tight).  Persistent buffers are bump
allocated; each op also uses a scratch region that is reset when it returns.

## How the GEMM works

`vc4_matmul` is two QPU launches in one process against one arena:

1. **pack** — `tools/kgen.py`'s panel builder: per 16x16 tile, a VDR (VPM DMA
   load, memory pitch = K\*4) followed by a *vertical* VDW, which the hardware
   writes out transposed as 16 consecutive 64 B vectors, i.e. the k-major panel
   `PANEL[(rb*K + k)*16 + r] = A[rb*16 + r][k]`.  No ALU data movement.
2. **gemm** — the asm3 kernel: 16x16 C tile per QPU request, 16 lanes = 16
   columns, A read from the panel (one 64 B line per k), B row-major, packed
   `fmul`+`fadd`, hardware rotate+replicate broadcast, 39-word k loop,
   VPM->DMA store of 4 chunks of 4 rows.

The k-loop body is emitted by `emit_kloop()` and is **bit-identical** to
`asm3/gemm2_128_d3_v1.bin` (39 words, same branch offset; checked during
development and reproducible with `tools/kgen.py gemm ...` + a 39-word
compare).  That is the correctness anchor of this library: the part that
computes is the part that was verified.

Generalising square N x N to arbitrary M x N x K changed only addressing:
the tile loop became a two-level (row block x column block) loop, every
stride/offset is a uniform chosen by the ARM, and the row-block loop has a
compile-time bound plus an in-loop guard (asm3's own pattern), so a corrupted
register cannot turn it into an unbounded DMA march.

## The two-launch rule

asm3 found that overwriting the code area and launching again can execute the
*previous* program, because the QPU instruction fetch goes through the L2 and a
clean line at the same address shadows the new code.  This library gives every
distinct kernel blob its own code area and its own uniform area
(`VC4_CODE_SLOT` / `VC4_UNI_SLOT` in `src/vc4_int.h`) and invalidates
`SLCACTL` before every launch.  Kernels are cached by shape in `kcache/`
(generated on first use by `tools/kgen.py`; `VC4INFER_NO_JIT=1` makes a cache
miss an error instead).

Every QPU kernel also obeys the asm3 rule that a TMU *pop* never shares an
instruction word with a write to a TMU address register (that shared word is
the 12-QPU corruption root-caused in `asm3/NOTES.md`).

## Writing QPU code safely

`tools/kgen.py` tracks every register write and read it emits and inserts nops
so a dependent read is never closer than three words (the QPU has no
forwarding), except inside the verified k loop and store, which keep asm3's
proven schedule verbatim.  Kernel loop bounds are compile-time constants, not
uniforms, wherever they drive DMA.  Both rules exist because a wrong counter
in a panel builder turns a 64-tile transpose into an unbounded VPM DMA march
over physical memory — see `../docs/results/engine.md`.

## conv2d backward, col2im and pooling

The training path now covers a small convolutional net:

* `vc4_im2col` writes the row-major im2col matrix `A[M][Cin*KH*KW]`
  (`vout='r'`: the same VDR/VPM gather with a vertical VDW, i.e. `[pixel][k]`
  instead of the GEMM's `[k][pixel]` panel).
* `vc4_col2im` scatters the im2col gradient back into the padded input image.
  The kernel is a **branch-free, one-task-per-QPU** kernel: a task owns one
  (row block, channel block) 16x16 destination tile, accumulates the taps in
  fixed order in 16 registers and stores once with the verified 4-chunk
  VPM->DMA store.  There is no read-modify-write and no cross-QPU
  accumulation, so the result does not depend on QPU scheduling.  The
  overlapping-patch sum is fp32 with the QPU's truncating `fadd`; it is
  deterministic but not IEEE (see ../docs/NUMERICS.md).  Guard row blocks of zeros
  around the packed panel make the source gather legal at the image border.
* `vc4_conv2d_backward` = row-major im2col (dW path) + `gemm3` for
  `dA = dY*W^T` and `dW = dY^T*A` + `transpose` + `col2im` for `dX`.
  Bias gradients are not implemented (the conv bias is forward-only).
* `vc4_maxpool2x2` / `..._backward`: 2x2 stride 2 over `[C][H][W]`
  (`H % 8 == 0`, `W % 16 == 0`), four rows per task so the store is the
  verified 4-row VPM->DMA shape.  The backward routes `dy` to the 2x2 group
  maximum (ties share the gradient, a valid subgradient).  The forward output
  row pitch is a multiple of 16 (lanes past `W/2` are zero), because the DMA
  writes full 64 B rows.

Both new kernel families are **branch-free** and take one task per QPU; the
host enumerates tasks and launches ceil(tasks/12) times.  That shape was
adopted after a counter loop around a long body hung the V3D (softmax notes)
and after a wrapper bug (a missing uniform word) produced a wild TMU address
and killed the queue.  The kernels are also exercised offline against
`asmq/vsim.py` before running on the board.

## Results

`../docs/CONV-RESULTS.md` has the measured conv-backward gradient checks and the toy
conv-net training curve / throughput (SGD and Adam, bit-identical across two
runs).

## Op coverage (strict dispatch)

`vc4_print_supported_ops()` prints the table; `src/vc4_api.c` is the single
source of truth.  Supported: `matmul`, `conv2d/3x3`, `conv2d/1x1`, `add`,
`mul`, `relu`, `sigmoid`, `silu`, `relu_bwd`, `rsqrt`, `transpose`,
`matmul_bt` (C = A*B^T), `softmax_ce_bwd` (fused softmax + cross-entropy
gradient), `softmax`, `im2col`, `col2im`, `conv2d/bwd_dx`, `conv2d/bwd_dw`,
`maxpool/2x2s2`, `maxpool/NxNsS` (any window/stride/pad), `maxpool_bwd`,
`softmax_fwd` (the `softmax` row; <=16 classes) (22 of 34 entries).
Explicitly unsupported (and listed as such, so the table is an honest
coverage statement): `conv2d/5x5`, `conv2d/stride2`, `conv2d/depthwise`,
`conv2d/grouped`, `matmul/f16`, `batched-matmul`, `avgpool`, `layernorm`,
`concat/slice`, arbitrary `permute`, `upsample`, `quantize/dequantize`.

The ONNX graph path (`tools/onnx/`, documented in `../docs/ONNX.md`) composes
the supported ops into stride-2 and depthwise convolutions and uses host byte
copies for concat/nearest-resize.  It is a graph-level layer; the engine
dispatch above remains strict.

## Training path

`vc4_train.c` adds the backward-side primitives without touching the verified
GEMM: a dense 16x16-tile transpose (the packer with a strided VDW
destination), `vc4_matmul_bt` (the same packer on B plus the asm3 GEMM with
`bmode=1`), the relu mask, `rsqrt`, and one fused softmax+cross-entropy
backward kernel.  The kernel computes, per row, max (rotate+fmax), exp
(degree-5 2^f polynomial), sum, 1/S (bit-trick + 3 Newton), `dlogits =
(p - onehot)/B`, the row loss and the argmax==label flag.  All reductions are
on the QPU; the host only reduces per-group (loss, correct) totals with a
GPU GEMM.

`tests/test_train.c` is a full-batch 64-32-10 MLP trainer (SGD or Adam) on a
deterministic synthetic 10-class dataset.  `tests/test_grad.c` checks the
matmul dA/dB, relu and softmax gradients against central finite differences
(h = 0.1 / 0.02) with a CPU checker.  `../docs/results/training.md` has the measured
numbers and the honest limits.

## conv2d

`vc4_conv2d` never materialises an im2col matrix:

1. the padded NCHW image is built in the arena (zero fill + one `memcpy` per
   row: layout, not arithmetic);
2. a QPU kernel builds the packed A panel directly from it.  For one row block
   (16 output pixels, contiguous in the padded image) and one filter tap, a
   single VDR loads 16 channels x 16 pixels with the pitch set to the padded
   plane size, and the vertical VDW writes the transposed 1 KB block
   `PANEL[rb][tap*Cin + ci_block*16 .. +15][0..15]`;
3. the weights `[Cout][Cin*KH*KW]` are transposed into a k-major B panel by the
   same pack kernel;
4. the GEMM runs with `bmode=1` (B from the packed panel).  `bias` is folded in
   as one extra k term (A row = 1.0, B row = bias), so even the bias add is on
   the GPU.

Constraints (from the VDR's 13-bit pitch field and the 16-wide panel tiles):
`stride == 1`, `KH == KW in {1,3}`, `Cin % 16 == 0`, `Cout % 16 == 0`, and
`(H + 2*pad) * align16(W + 2*pad) * 4 <= 8191` bytes of padded plane.  Taps are
unrolled at generation time, so a 5x5 is a generator change, not a new kernel.
The final store into NCHW `[Cout][HO][WO]` is a strided gather on the ARM
(bytes only).

## Elementwise

One iteration = 16 vectors = 256 floats per QPU: 16 TMU gathers per operand
(16 lanes = 16 consecutive floats = one 64 B line), the arithmetic, then the
verified 4-chunk VPM->DMA store with stride 0.  `add`/`mul`/`relu` are exact
IEEE fp32.  `sigmoid` is `1/(1+exp(-x))` with `exp(-x) = 2^(-x*log2 e)`, a
degree-5 minimax polynomial for `2^f` on [-0.5, 0.5] and a bit-trick seed plus
three Newton steps for the reciprocal; `silu = x*sigmoid(x)`.  Measured error
is printed by `tests/test_ew.c`.

## Python binding

```python
import vc4infer, numpy as np
with vc4infer.Engine() as eng:
    a = eng.upload(np.random.rand(256,256).astype(np.float32))
    b = eng.upload(np.random.rand(256,256).astype(np.float32))
    c = eng.alloc(256*256*4)
    eng.matmul(a, b, c, 256, 256, 256)
    print(eng.download(c, 256*256*4).reshape(256,256))
```

## PyTorch `PrivateUse1` integration path (not built here)

The engine is deliberately the *backend* only: a thin C++ extension would own
the tensor plumbing.  The path that keeps strict dispatch intact:

1. **Register the backend.** `torch.utils.rename_privateuse1_backend("vc4")`
   then `torch.utils.generate_methods_for_privateuse1_backend()` gives
   `torch.device("vc4:0")` and `Tensor.to("vc4")`.
2. **Allocator.** Implement `at::Allocator` over the single `vc4_ctx` arena.
   `data_ptr` is an opaque handle; store the arena *offset* and let the kernels
   recover it (`off = ptr - arena_bus`).  Nothing else may dereference it —
   which is exactly what strict dispatch guarantees.
3. **Hooks.** `PrivateUse1HooksInterface` must report
   `hasPrimaryContext() == true`, `getDefaultGenerator` throwing, and **no
   `DeviceGuard` fallback** to CPU.
4. **Kernels.** `TORCH_LIBRARY_IMPL(aten, PrivateUse1, m)` for the subset the
   engine implements: `mm`, `addmm`, `convolution`, `add.Tensor`, `mul.Tensor`,
   `relu`, `sigmoid`, `silu`.  Each one calls `vc4_matmul` / `vc4_conv2d` /
   `vc4_elementwise` and translates `VC4_ERR_UNSUPPORTED` into a thrown
   `c10::Error`.  NCHW in, NCHW out (the engine wants row-major fp32).
5. **No fallback.** Do *not* register `CompositeImplicitAutograd` for these ops
   (that would decompose to CPU kernels) and do not install a catch-all
   fallback key.  An op outside the list then fails loudly with
   `NotImplementedError: Could not run 'aten::...' with arguments from the
   'vc4' backend`, which is the behaviour we want while coverage grows.
6. **Inference only.** No autograd kernels: run under `torch.inference_mode()`,
   with weights pre-packed once (the pack kernel costs ~10 % of a matmul).

## Limits worth knowing

- fp32 only, row-major only, `Cin`/`Cout` multiples of 16 for conv.
- conv is stride-1; large feature maps hit the VDR pitch limit (padded plane
  <= 8191 bytes), which the natural next step removes by tiling channels or by
  repacking to NHWC.
- one process per arena; the arena is not shared between processes.
- the direct backend needs `/dev/mem` (root) and `/dev/dma_heap/linux,cma`;
  `VC4INFER_DAEMON=1` moves both into vc4d and runs unprivileged.
