Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The neural vCPU

The neural vCPU is an RV32IM CPU compiled into network weights. For a program built with the C extension, which the ELF header says, its fetch also reads a halfword’s row of a 65,536-row table of expansions (rvc.py: a compressed instruction is one instruction of the base set, so no unit is added) and goes on with that, 2 bytes on, as the reference vCPU does; the table is built at run time, and a digest of it, which a Rust test holds the reference’s own expansion to, says the two are one. One forward pass executes one instruction per guest in a batch. It implements the same Vcpu interface as the reference interpreter, accessed over a Unix socket.

Like Qwenputer, it uses compiled CPU layers and delta-rule memory. Unlike Qwenputer, it is a standalone network, not part of a pretrained language model.

Running it

With uv installed, start the server from the shem-neural release that matches shem:

uvx --from "shem-neural==$(shem --version | cut -d' ' -f2)" shem-neural-server

It listens at $XDG_RUNTIME_DIR/shem/neural.sock (/tmp/shem-neural-UID.sock without one), or /run/shem/neural.sock as root, which is where shem and the containerd shim look; --socket PATH and --neural-socket PATH choose another. shem refuses a socket that a user other than its own, or root, listens at, so another user cannot take the path in /tmp and read a guest.

From a repository checkout, just neural-server runs the checkout’s own.

In another terminal, compile and run a guest (compilation needs Docker):

just cc -O2 -o hello guests/hello.c
shem run --vcpu neural hello

The server uses the CPU. GPU execution is currently available only through the benchmark harness.

Compiled, not trained

isa.py defines 48 RV32IM instructions: decode patterns, operand formats, result routing, next pc and exits. compile.py turns that table into tensors:

TensorShapeRole
decode_w, decode_c48 × 32, 48A layer that counts, for each instruction, how many masked bits of the word differ from its pattern. relu(1 − count) is a one-hot over instructions, and all zeros for an illegal one.
index_w, index_c32 × 5, 32The same trick for 5-bit register numbers and shift amounts
imm_bits5 × 32 × 32Selection matrices from instruction bits to immediate bits, one per format, sign extension included
format_route, result_route, next_pc_route, branch_route, exit_route48 × nRouting tables: which format, result, next pc, comparison and exit each instruction uses
uses_imm, load_size, store_size48Per-instruction flags and sizes
sll, srl32 × 32 × 32One shift matrix per shift amount; the shifter is attention over them
sra_fill32 × 32Sign-bit fill for each arithmetic-right-shift amount
byte_bits, powers256 × 8, 32Byte-to-bits lookup table, and the weights that turn bits into a value

Weights are saved as safetensors for inclusion in images.

State

PartShapeRepresentation
Register fileB × 32 × 32A delta-rule state with one row of bits per register
MemoryB × mem_sizeA delta-rule state with one row per byte
pcB, plus its two low bitsThe pc’s low bits drive the alignment check
instretBInstructions retired
baseBThe guest address where memory starts: 0 for containers, 0x80000000 in VM mode

Both the register file and memory are written with the delta rule, S ← S + β (v − S k) kᵀ, with a one-hot key k. With β = 1 that replaces the keyed row exactly; with β = 0 it changes nothing. A read is S q with a one-hot query q, which returns the row. This is how Gated DeltaNet layers hold memory in Qwenputer.

One forward pass

cpu.py, in order:

  1. Fetch. Four one-hot reads of memory at the pc’s offset from the base give the instruction’s bytes, and a table lookup turns them into 32 bits. A clamp flags a pc that is misaligned or out of range. The offset is pc − base + 2³² · clamp(base − pc): below the base it wraps past the end of memory, so it faults, as on the reference vCPU. Loads and stores use the same offset.
  2. Decode. The mismatch-counting layer gives the instruction one-hot. Three more give one-hots for rd, rs1 and rs2.
  3. Operands. Attention reads of the register file with the rs1 and rs2 one-hots give the operands’ bits. The selection matrices give the immediate’s bits. The second operand is the immediate or rs2, chosen by uses_imm.
  4. Units. Every unit computes its result for every guest: adder, logic (a·b, a + b − a·b, a + b − 2a·b on bits), shifter (attention over the shift matrices, with sign fill for sra), comparator, load extractor, multiplier (on 16-bit halves, so every partial value stays exact) and divider (restoring division, 32 unrolled compare-and-subtract layers). Values are integers, linear in the bits. A stack of threshold layers, decompose, turns a value back into bits.
  5. Exits. ecall and ebreak come from the decode, illegal is “no instruction matched”, and memory faults compare the address against the memory size. They are combined in the reference vCPU’s order: fetch, then decode, then execute.
  6. Routing. The instruction one-hot times the routing tables picks the result for rd, the comparison that decides a branch, and the next pc.
  7. Writeback. Delta-rule writes to the register file and memory, and the pc update, all gated by commit, which is 0 when the instruction exits. An exiting instruction therefore changes nothing, as on the reference vCPU.

Routing is per guest, so one batch can run unrelated programs.

The operations it uses

The dense executor uses products with compiled weights (linear layers and one-hot attention), element-wise sums and products (gating), and clamps, which are piecewise-linear like ReLU. State changes only through gated delta-rule writes.

Integer intermediates are held exactly in float64. Lower-precision execution would need smaller arithmetic units, such as bytes rather than words.

Two executors

The dense executor defines the network. The fused executor computes the same function with cheaper operations:

UnitDenseFused
MemoryA float64 delta-rule state, one row per byte; one-hot keys and matrix products, O(memory) per accessBytes in shared 4 KiB pages with copy-on-write (see below); indexing, O(1) per access
Register fileOne-hot reads, and delta-rule writes over the whole matrixGathers of the two operand rows, and the same write to the one row it can change
ShifterAttention over the shift matricesInteger shifts
Bits of a value35 threshold layersShifts and masks
Byte to bits, 5-bit indexOne-hot times a tableIndex into the table
Division32 unrolled layersInteger division, with RISC-V’s rules for zero

Both skip multiplication, division and the shifter, and the fused one the memory read and write, when no guest in the batch needs them: an ALU loop’s instruction costs about half of what it did. What would cut it further is not done: several instructions per forward pass, narrower types for bits, and the server’s vCPUs on a GPU (only the harness runs there). Tests compare unit results, edge cases and whole programs.

For GPUs, static mode runs every unit and uses flat memory: one byte array per guest, with disabled writes sent to a scratch byte. This removes data-dependent control flow for compilation and CUDA graphs (On GPUs).

Verification

  • Unit tests: instruction semantics, M-extension edge cases, exits, non-mutating faults, snapshots, executor equivalence and batching.
  • Differential tests: all 60 official riscv-tests, random ALU programs, cross-vCPU snapshot resume, fork/pipe/wait, VM traps and timers.
  • Linux resume: boot no-MMU Linux 6.8 on the reference vCPU, resume on both, and run echo $((6 * 7)). About 180,000 instructions; final registers, host device state and all 64 MiB of RAM must agree. Neural execution takes about four minutes.

Run with just neural-tests.

Density

Paged memory with copy-on-write (memory.py). The fused executor shares a pool of 4 KiB byte pages across vCPUs of the same memory size:

  • A fresh guest maps the zero page everywhere, so memory it never touches costs nothing.
  • CLONE copies the page table; writes copy shared pages on demand.
  • RESTORE interns whole pages by content, so guests from the same warm image share unchanged pages.

Continuous batching (server.py). One executor thread groups pending RUN requests by CPU weights and memory size. It stacks registers and page tables, steps each group together, and returns guests that exit or exhaust their budget. New runs join between steps.

Speed

Recorded CPU results from bench.py, using one core and a sum loop with a different bound for each guest:

GuestsInstructions/s, totalPer guestMemory pages
11,5691,5692
810,9991,3759
3241,4681,29633
6476,3201,19365
12882,897648129

At 64 guests, aggregate throughput is about 49 times the single-guest result, but per-guest throughput has fallen from 1,569 to 1,193 instructions/s. (An earlier release’s numbers on another machine were 881 and 28,000 at 1 and 64 guests; CI checks the ratio, bench.py --check, as machines’ speeds differ.) Batching improves throughput, not individual guest latency. The pages column includes the shared zero page and one private 4 KiB page per guest; a dense float64 state for 1 MiB of guest RAM takes 8 MiB.

The protocol

The host talks to the server (server.py, neural.rs) over a Unix socket. Every message is a frame: a little-endian u32 length, then the payload. A request is an op byte, the vCPU id (except for CREATE) and the arguments; a response is a status byte, 0 for OK, 1 for an error with a message, 2 for a memory fault, and then the result. All integers are little-endian.

OpArgumentsResult
1 CREATEu32 memory size, optionally u32 base address (default 0)u32 id
2 DROP
3 CLONEu32 id of the copy
4 RUNu64 budgetu8 exit reason, u32 detail, u32 pc, u64 instructions
5 GET_REGu8 indexu32
6 SET_REGu8 index, u32 value
7 GET_PCu32
8 SET_PCu32
9 READ_MEMu32 address, u32 lengthbytes
10 WRITE_MEMu32 address, bytes
11 RESET
12 SNAPSHOTcanonical machine state
13 RESTOREcanonical machine state
18 SET_COMPRESSEDu8: 1 to run compressed instructions, 0 not to

Exit reasons are 0 budget, 1 ecall, 2 ebreak, 3 illegal instruction (detail: the word, or a compressed instruction’s 16 bits), and 4 memory fault (detail: the address). Snapshots use the canonical format of MachineState in vcpu.rs, so a snapshot from either vCPU restores on the other.

On GPUs

The network runs on whatever device its weights are on. gpu.py steps a batch of guests in place with the static executor and flat memory, in four modes: eager, compiled with torch.compile (which generates Triton kernels), eager in a CUDA graph that captures 64 steps so they launch as one, and both.

jobs/gpu.py runs on Hugging Face Jobs:

just gpu-job l4x1

It compares 1,024 random-program guests against the CPU executor for 512 steps in each GPU mode, then benchmarks batches of 1–32,768 guests with 64 KiB each. Registers, memory, pc, instruction count and exits match bit-for-bit on L4 and A100. Integer intermediates stay below 2^53 and are exactly representable in float64.

Instructions per second, with torch 2.15 and CUDA 13.2 (the CPU row is the paged executor on one core, from Speed, as measured for an earlier release):

GuestsCPUL4, best mode (before → with byte registers)A100, eagerA100, compiled + graphA100, eager + graph
18814,818 → 6,65519212,8592,086
6427,985278,995 → 390,70612,187577,138121,028
1,024891,211 → 1,351,532189,6462,821,0981,399,234
4,096998,556 → 2,727,032760,7873,549,0513,664,716
16,384945,402 → 3,648,4143,026,6963,986,3166,556,971
32,768968,596 → 3,320,4246,118,7543,166,8737,434,596
  • Small batches are launch-bound; compilation and graphs reduce launches.
  • Large batches are memory-bound by what the state holds. The A100 reaches 7.4 million instructions/s (before byte registers); the L4 levelled off near one million, and now reaches 3.6 million.
  • Register bits are stored as bytes between instructions, 1 KiB per guest where float64 took 8, and are float64 again while an instruction computes with them. The arithmetic values stay float64, which the multiplier and divider need to stay exact. On the L4 this took the best mode at 16,384 guests from 945,402 to 3,648,414 instructions/s (the A100 columns were measured before it), with every mode still identical to the CPU’s result, as the job checks.