shem
Run containers and VMs inside a model’s weights.
shem treats the host as a hypervisor and a model as the machine. The model supplies a CPU, compiled into its weights, and RAM, which is its recurrent state. The host supplies everything else: system calls, devices, scheduling and storage. Images are standard OCI images, built from Shemfiles with shem build or docker build, and they can carry a running guest, a booted kernel or a primed language model session.
Quick start
curl -fsSL https://jgalego.github.io/shem/install.sh | sh
shem run ghcr.io/jgalego/shem/hello:latest
From a repository checkout, with uv installed:
shem build -t qwen3 examples/qwen3
shem run qwen3 "What is a golem?"
Programs use the reference interpreter by default. --vcpu neural selects a standalone RV32IM network with compiled weights; it needs a neural server. Language-model sessions use PyTorch, not the vCPU.
Guides
| Task | Guide |
|---|---|
| Import a model, save a session or add tools | Model images |
| Build, push and pull images | Shemfile |
| Run with Docker or containerd | containerd and Docker |
| Configure nodes or mount model images | Kubernetes |
| Run on Windows without WSL | Windows |
| Boot Linux or save a booted VM | VM mode |
| Run and benchmark the compiled CPU | Neural vCPU |
| Understand the runtime and its limits | Architecture |
shem is experimental, and not fast: the project README says when to use it, and when not to, against Ollama, Docker Model Runner, RamaLama and KitOps.
The source is at github.com/JGalego/shem.
Architecture
shem’s host supplies system calls, devices, scheduling and storage. Programs run on either a reference RV32IM interpreter or a neural vCPU whose weights implement the CPU and whose state holds guest memory.
The neural vCPU is inspired by Qwenputer, but is a standalone compiled network, not part of a pretrained language model. Language-model sessions run separately and can call RV32 programs as tools.
How virtualization maps onto a model
| Virtualization | shem |
|---|---|
| vCPU | Compiled CPU layers |
| Guest RAM | DeltaNet state. A one-hot key writes one row and a one-hot query reads it back. |
KVM_RUN loop | Vcpu::run |
| VM exit | The vCPU stops on ecall, ebreak, an illegal instruction or a memory fault |
| DMA, virtio rings | The host reads and writes state rows directly, without decoding any tokens |
| Timer interrupt | The host stops decoding after a step budget |
| Snapshot | Save canonical machine state and the host-side process or device state |
| Multi-tenancy | The batch dimension |
What is in the weights, and what is not
The tagline says containers run inside a model’s weights. Precisely:
| Part | Where it runs | In a language model’s weights? |
|---|---|---|
| The neural vCPU | A standalone network of compiled weights: fetch, decode, units, writeback (neural.md) | No. It is its own network, published as jgalego/shem-rv32im |
| Its registers and memory | Delta-rule state of that network, or pages the fused executor keeps | No: the network’s own, not a model’s recurrent state |
| A language model | PyTorch, from the checkpoint’s own tensors, block by block (models.md) | Yes: it is the model |
| A model’s session | The model’s KV caches and recurrent state | Yes, but it holds a conversation, not guest memory |
| A tool call | The host runs the program on the compiled CPU and returns the output as text | The two meet only in text: the CPU does not share the model’s residual stream or state |
Qwenputer goes further than shem does: its CPU layers sit inside a pretrained model, so one forward pass is both. Joining the two here would take layers that read and write the residual stream directly, with a token’s embedding carrying an instruction and a Gated DeltaNet block’s state as the guest’s memory, a design the compiled CPU’s delta-rule state suggests but nothing has tested. Nothing of that is built. The pieces that exist are the part of the CPU that does not depend on it, the Vcpu interface, and the receipts that would let anyone check such a run. Until a model’s own forward pass executes the guest, “inside a model” means the model and the machine are both neural networks, driven by one host.
Two modes, one runtime
Container (shem run) | VM (shem boot) | |
|---|---|---|
| Guest runs | Programs, with the host as their kernel | A kernel and its programs |
| Guest exits on | System calls | Device access, traps, timer ticks |
| Host provides | Linux system calls (linux/) | The machine: CSRs, traps, a timer, a UART and a syscon (vm.md) |
| ISA needed | RV32IM (and C, for a program built with it: the ELF header’s RVC flag turns it on); the host emulates the A extension | RV32IM too; the host emulates A, the CSRs and traps |
| Start | Load an ELF into memory, or thaw a warm image | Boot a kernel, or thaw a booted VM |
The vCPU interface
vcpu.rs defines the Vcpu trait that both the reference interpreter and a neural vCPU implement:
run(budget)executes at mostbudgetinstructions and returns anExit.reg,set_reg,pc,set_pc,read_mem,write_memaccess registers and memory.snapshotandrestoreuseMachineState, a canonical, vCPU-independent format holding the pc, registers, instruction count and memory.
Exit semantics: except for Budget, the exit’s pc points at the instruction that caused it, and that instruction has not retired. For a system call the host writes the result to a0 and resumes at pc + 4.
Both vCPUs must satisfy:
- Trace equivalence. Registers, memory and exits match
ReferenceVcpuinstruction for instruction. - Canonical snapshots. All state can be restored from
MachineStateat any instruction boundary. A guest can boot on the reference vCPU and resume on the neural one.
Design rules that come from running on a model
- The host handles unsupported operations. The vCPU exits for system calls, atomics and, in VM mode, privileged instructions and device accesses.
emulate.rshandles the A extension because musl’s riscv32 port needs LR/SC. - Batching supports unrelated guests. Tensor routing lets one batch run different programs. Throughput and per-guest latency depend on batch size, workload and device (benchmarks).
- Instruction budgets provide preemption. The host drives execution and stops the vCPU after a bounded number of retired instructions.
fork()clones vCPU state. The reference interpreter copies memory; the neural server shares pages until a write. Threads share their process’s vCPU memory and save their registers between turns (container.rs).- The host manages memory backing. The fused CPU executor uses copy-on-write pages; the dense executor uses delta-rule state, and the GPU harness uses flat byte arrays. This is not a guest MMU.
- Builds are reproducible with fixed inputs. Time is virtual, randomness is seeded, directory listings are sorted, and layer metadata is normalized (reproducibility). Interactive replay also needs the external inputs.
Isolation
- The only way out of a guest is an exit, so the attack surface is the exit handler. The system-call layer treats every guest pointer and length as hostile: transfers are capped, and bad pointers return
EFAULT. - Guest paths resolve inside the root directory with chroot semantics (
rootfs.rs):..stops at the root, and symlinks, absolute ones included, resolve relative to it. Resolution and the final open are separate host calls, so a concurrent writer to the host directory could race them; a single guest cannot. On Linux 5.6 and later the open is made withopenat2, beneath the root, refusing any symlink on the way (RootFs::open_beneath), so a link swapped in after the path was resolved leads nowhere: opening a file, the call that would give a guest a host file’s contents, no longer races.mkdir,unlink,symlinkandrenameact on the directory that holds their path, opened beneath the root the same way, so they cannot be sent through a swapped link either.stat,readlink,utimensatand directory listings are read the same way, from a descriptor opened beneath the root. Only a host withoutopenat2(Linux before 5.6, or another system) does everything by path as before. - A container has a network of its own and no other: its processes can listen on
AF_UNIXpaths and loopback ports, connect to them and talk over stream sockets, andsocketpairworks, but no socket leaves the container, so an untrusted guest can serve and call its siblings and reach no host or network (linux/net.rs). A connection is two pipes, so it blocks, polls and closes as a pipe does. Not yet: datagrams,AF_INET6, addresses beyond loopback,sendmsgandrecvmsg, descriptor passing, and a file for a Unix socket’s path. - Tool calls run on a separate vCPU; the language model does not share its residual stream or state with the compiled CPU.
- Tool output is untrusted model context. Executing a tool on a vCPU does not prevent prompt injection through its output.
Tech stack
| Part | Implementation |
|---|---|
| Host runtime, CLI, reference vCPU and image store | Rust, in crates/shem |
| Neural vCPU and language-model runtime | Python and PyTorch, in neural/. The vCPU server runs on the CPU; the GPU vCPU harness is separate. Model sessions support CPU and GPU execution. |
| Host to neural server | Framed requests over a Unix socket |
| Images | OCI layouts and registries; ORAS for push and pull |
| Docker, containerd and Kubernetes | containerd shim and RuntimeClass |
| Builds | shem build and a Go BuildKit frontend |
| Guest toolchain | Zig targeting riscv32-linux-musl, in toolchain/Dockerfile |
| ISA | The reference vCPU passes the riscv-tests (rv32uc, the C extension, included), and agrees with QEMU’s user-mode emulator on random RV32IM programs, and on programs with compressed instructions among them, and with Spike, the ISA’s own simulator, on bare-metal ones that say what they computed in a signature (tests/external.rs, in CI) |
| Tests | cargo test --workspace, just guest-tests, just neural-tests, and the integration jobs in CI |
Roadmap
See ROADMAP.md for planned work.
Model images
A model image packages a language model’s weights, tokenizer and optional session state in OCI layers. shem run starts or resumes a text-generation session; shem push and shem pull transfer the image through a registry.
shem build -t qwen3 examples/qwen3 # Qwen3-0.6B from Hugging Face, one layer per block
shem run qwen3 "What is a golem?" # a session: the prompt in, the reply out
shem push qwen3 ghcr.io/your-user/qwen3:0.6b # to a registry
shem run ghcr.io/your-user/qwen3:0.6b "Olá" # elsewhere: pulled on first use, then run
shem run -i qwen3 has a conversation instead: each line you type is a turn of one session, which remembers them, until /exit or end of input (/clear starts over). With a prompt, it starts there; piped input works too, a turn to a line, and a driver started with no prompt on a terminal does the same.
Model imports and execution need uv; registry transfers need ORAS and a registry login. For docker build, use shem’s BuildKit frontend, as in the Qwen3 Dockerfile.
Shemfile
FROM hf.co/Qwen/Qwen3.5-0.8B
ENTRYPOINT ["shem:generate", "--max-tokens", "128"]
CMD ["Introduce yourself in one sentence."]
| Source | FROM example |
|---|---|
| Hugging Face checkpoint | FROM hf.co/Qwen/Qwen3.5-0.8B |
| Pinned revision | FROM hf.co/ORG/NAME:REVISION |
| Checkpoint directory in the build context | FROM checkpoint/ |
| GGUF repository and quantization | FROM hf.co/Qwen/Qwen3-0.6B-GGUF:Q8_0 |
| GGUF file in the build context | FROM model.gguf |
GGUF import uses transformers to dequantize into float32, from the gguf extra of shem-neural, which a release of shem fetches with its importer and the shem-neural image includes.
Model bases set ENTRYPOINT ["shem:generate"]. ENTRYPOINT and CMD keep their Docker meanings:
| Image | ENTRYPOINT | CMD | shem run image … |
|---|---|---|---|
A program (FROM scratch) | A program in the image, run on the vCPU | Its default arguments | Replace the arguments |
| A model | A driver: ["shem:generate", "--max-tokens", "128"] | The default prompt | Your prompt |
A shem: entrypoint selects a host-side driver, not a guest executable.
shem:generate option | Meaning |
|---|---|
--max-tokens N | Maximum reply length; default 256 |
--dtype bfloat16 | Compute in bfloat16, which halves the memory weights and sessions take and is faster on GPUs; default float32 |
--adapter PATH | Merge a LoRA adapter into the weights as the model loads: see adapters |
--quantize int8 | Hold the projections’ weights as int8 with a scale for each output row, a quarter of float32’s memory and half of bfloat16’s, applied with PyTorch’s int8 kernel on a CPU; embeddings stay as they are. Sessions and receipts record it (float32+int8), so they are not mixed with unquantized ones |
--quantize int4 | As int8, in 4 bits: two to a byte, in groups of 64 inputs with a scale each, an eighth of float32’s memory. Each matrix is made dense for the one call that uses it, so it is slower than int8, and coarser: check a model’s replies before you trust it |
--temperature T, --top-p P, --top-k K, --seed N | Draw tokens, seeded, rather than take the likeliest: see above; defaults greedy, 1, all, random |
--system TEXT | System prompt |
--system-file PATH | Append a file from the image to the system prompt |
--stop TEXT | End the reply at this text; useful for base models |
--tools DIR | Offer programs in this directory as tools |
--chat | Read turns, a line each, as shem run -i does |
--keep | Keep a Docker session open after replying |
--serve [HOST:]PORT | Serve OpenAI’s chat completions API instead of replying once |
Decoding is greedy and repeatable for the same model, session, prompt and device, which a receipt lets anyone check.
--temperature T draws each token from the model’s distribution instead, sharpened or flattened by T, cut by --top-k K and --top-p P, with numbers from a generator --seed N starts. The generator runs on the CPU and takes one number a token, so the same seed draws the same reply on any device that computes the same logits, and a receipt records the settings and the seed (a random one if none was given), to draw again. shem run --temperature 0.8 --seed 7 qwen3 "Tell me a story" takes them on the command line, the image’s ENTRYPOINT can set them, and the API takes temperature, top_p, top_k and seed in a request.
A session is held to the model’s context window, which the importer records as context in shem.json: a conversation that would pass it is refused (the API answers context_length_exceeded), and a reply stops, as length, where the window ends. A model with no window, such as Mamba, has no limit.
Sessions as layers
WARM --until=prompt primes a session at build time and freezes it into the image (examples/golem):
FROM hf.co/Qwen/Qwen3.5-0.8B
ENTRYPOINT ["shem:generate", "--system", "You are Shem, a golem made of clay and brought to life by a word."]
CMD ["Who are you?"]
WARM --until=prompt
The builder processes the conversation prefix before the user’s prompt and saves each block’s state: attention KV caches, convolution inputs and recurrent memory. shem run resumes there without processing the system prompt again.
To prime a model with a document, use --system-file (handbook example):
FROM hf.co/allenai/OLMo-2-0425-1B-Instruct
COPY handbook.md /etc/handbook.md
ENTRYPOINT ["shem:generate", "--system", "Answer questions about shem from its handbook, below.", "--system-file", "/etc/handbook.md"]
WARM --until=prompt
Attention caches grow with the token count. Gated DeltaNet’s convolution state and memory matrices are fixed-size. Qwen3.5 combines both block types, so its total session state still grows with its attention caches.
Sessions live under /.shem:
session.safetensors: block state, keyed by block number and name.session.json: consumed tokens, precision and block-type versions.
A change to a block’s saved-state semantics requires a version bump. If versions or precision differ, the runtime rebuilds state by replaying the saved tokens. Compatibility tests load sessions saved by earlier releases.
Sessions as artifacts
A session can be published separately from its model:
shem build -t golem examples/golem
shem build -t qwen3.5 examples/qwen3.5
shem push --state golem registry.example.com/team/golem:session
shem run --state registry.example.com/team/golem:session qwen3.5 "Who are you?"
--state reuses the image’s state-layer blob. The artifact’s subject is the model image without that layer, which is pushed alongside it. Use oras discover to list sessions referring to a model.
The config records the format (shem.session/v1), consumed tokens, precision, block versions and model fingerprint. The fingerprint hashes block definitions and tensor contents, independent of file layout. shem run --state accepts a registry reference or OCI layout directory and rejects mismatched weights, even if the model has the same shape.
The media type is application/vnd.shem.session.v1+json. Model state artifacts are also proposed in modelpack/model-spec#239; shem uses its own format.
The model as files
The importer writes these files into /model:
| File | Contents |
|---|---|
shem.json | Embedding, ordered blocks, head and tokenizer; block types, parameters and tensor names |
block-NNN-TYPE.safetensors | One block’s weights, with original tensor names and dtypes |
embed.safetensors, head.safetensors | Embedding and output weights |
model.safetensors.index.json | Tensor-to-file index |
| Checkpoint metadata | Configs, tokenizer, chat template, licence and notices |
Each weights file normally gets its own layer. Above 95 weights files, neighbouring blocks share layers to stay below overlay filesystem limits. Images based on the same model share weight blobs.
The directory remains a Hugging Face checkpoint: AutoModelForCausalLM.from_pretrained("/model") loads it. Manifest format shem.model/v2 resolves tensor names through the index, so files can follow blocks or the checkpoint’s original shards. The older shem.model/v1 format is still supported.
Models consist of an embedding, ordered blocks and a head. A decoder layer is split into a token mixer and an MLP:
| Block type | What it does | Its state in a session |
|---|---|---|
attention | Grouped-query attention; optional rotary scaling, biases, fused projections, QK norms, sliding windows, softcapping and output gates | Growing KV cache |
gated_deltanet | Causal convolution and gated delta-rule matrix memory | Fixed-size convolution and memory state |
mamba | Causal convolution and selective scan | Fixed-size convolution and scan state |
mlp | SwiGLU or GeGLU; optional biases and fused projections | None |
moe | Routed gated experts; optional shared expert | None |
Importers map each family’s tensor layout, norms, rotary settings and scaling onto these block types. Supported families include Llama, Mistral, Qwen2 through Qwen3.5, Gemma 2 and 3, Phi-3 and Phi-4-mini, OLMo 2 and 3, SmolLM3, Granite, Mamba, Mixtral, Qwen-MoE, OLMoE and GraniteMoe.
Unsupported settings, such as dynamic NTK scaling or activations other than SiLU and GELU, fail at import. A new family needs a tensor reader; a new layer kind needs a registered type in blocks.py. Neither requires an image-format change.
test_importers.py compares tiny random checkpoints with transformers without downloads. test_model.py also checks real model configs, logits, templates and session resumes.
Imported models
| Model | Blocks | Image | Verified |
|---|---|---|---|
| Qwen/Qwen3-0.6B | 28 attention, 28 MLP | 59 layers, 892 MB | Logits within 1e-3 of transformers, and the same 24 greedy tokens |
| Qwen/Qwen3.5-0.8B | 18 Gated DeltaNet, 6 attention with output gates and partial rotary positions, 24 MLP | 51 layers | The same, against transformers’ Qwen3.5 |
| HuggingFaceTB/SmolLM2-360M-Instruct | 32 attention, 32 MLP | 67 layers | The same, against transformers’ Llama |
| Qwen/Qwen2.5-0.5B-Instruct | 24 attention with query, key and value biases, 24 MLP | 51 layers | The same, against transformers’ Qwen2 |
| google/gemma-3-270m-it | 18 attention (15 with sliding windows) with norms around them and on queries and keys, 18 GeGLU MLP | 39 layers | The same, against transformers’ Gemma 3 |
| allenai/OLMo-2-0425-1B-Instruct | 16 attention with norms after them and on all queries and keys, 16 MLP | 35 layers | The same, against transformers’ OLMo 2 |
| ibm-granite/granite-3.1-1b-a400m-instruct | 24 attention, 24 mixtures of 32 stacked experts, 8 per token, with Granite’s multipliers | 51 layers | The same, against transformers’ GraniteMoe |
| HuggingFaceTB/SmolVLM-256M-Instruct | 30 attention, 30 MLP, and the image encoder: 12 SigLIP-style layers and a pixel-shuffle connector | 60 layers and the encoder | The same, against transformers’ Idefics3, with an image: the processor’s tokens, its tiles’ pixels and the logits of the pass over them |
| llava-hf/llava-interleave-qwen-0.5b-hf | 24 attention with query, key and value biases, 24 MLP, and the image encoder: 26 SigLIP layers and a two-layer projector | 51 layers and the encoder | The same, against transformers’ LLaVA, with an image: the processor’s tokens and pixels, and the logits of the pass |
| state-spaces/mamba-130m-hf | 24 Mamba | 27 layers | The same, against transformers’ Mamba, with a template that runs a base model’s text together |
Qwen/Qwen3-0.6B-GGUF :Q8_0 | As Qwen3-0.6B, dequantized | 59 layers | Logits within 1e-3 of transformers’ own dequantization, and the same chat template |
Larger float32 comparisons use a Hugging Face Job with 256 GB of memory (just models-job). Qwen3-30B-A3B alone needs 122 GB:
| Model | Blocks | Verified |
|---|---|---|
| unsloth/Llama-3.2-1B-Instruct | 16 attention with Llama 3’s rotary scaling, 16 MLP | Logits within 1e-3 of transformers, and the same 24 greedy tokens |
| mistralai/Mistral-7B-Instruct-v0.3 | 32 attention, 32 MLP | The same, against transformers’ Mistral |
| microsoft/Phi-3.5-mini-instruct | 32 attention with fused projections and longrope, 32 MLP | The same, against transformers’ Phi-3 |
| google/gemma-3-4b-it | 34 attention (5 of 6 with sliding windows), 34 GeGLU MLP; the vision encoder left out | The same, against transformers’ Gemma 3 vision-language model |
| allenai/Olmo-3-7B-Instruct | 32 attention (24 with sliding windows) with YaRN scaling, 32 MLP | The same, against transformers’ OLMo 3 |
| allenai/OLMoE-1B-7B-0125-Instruct | 16 attention, 16 mixtures of 64 experts, 8 per token | The same, against transformers’ OLMoE |
| Qwen/Qwen1.5-MoE-A2.7B-Chat | 24 attention, 24 mixtures of 60 experts, 4 per token, and a gated shared expert | The same, against transformers’ Qwen2-MoE |
| Qwen/Qwen3-30B-A3B | 48 attention, 48 mixtures of 128 experts, 8 per token | The same, against transformers’ Qwen3-MoE |
| mistralai/Mixtral-8x7B-Instruct-v0.1 | 32 attention, 32 mixtures of 8 experts, 2 per token | In bfloat16, as below: its 47 billion parameters take 188 GB in float32 |
Qwen3.5 and Gemma 3 4B imports are text-only: their vision encoders are omitted, as is Qwen3.5’s multi-token prediction layer, and the API takes no images for them. SmolVLM and Idefics3 are the vision-language families whose encoder shem runs.
Download-based tests in test_model.py require SHEM_MODEL_TESTS=1. Add the larger-model flags as needed:
| Flag | Comparisons |
|---|---|
SHEM_MODEL_TESTS=1 | Small checkpoints: float32 logits, greedy tokens, templates and session resumes |
SHEM_LARGE_MODEL_TESTS=1 | Gemma-2-2B, Phi-4-mini, SmolLM3-3B and Granite-3.3-2B in bfloat16 |
SHEM_HUGE_MODEL_TESTS=1 | Larger checkpoints above, including Mixtral in bfloat16 |
SHEM_MODEL_TESTS=1 SHEM_LARGE_MODEL_TESTS=1 \
uv run --project neural pytest neural/tests/test_model.py
Bfloat16 checks require next-token agreement at 90% or more of prompt positions and final-logit cosine similarity above 0.99. Gated models require access and a Hugging Face token; CI skips them, while just models-job forwards your token.
Images
A vision-language model of the SmolVLM family (its SmolVLMForConditionalGeneration and Idefics3ForConditionalGeneration checkpoints) or of LLaVA’s (LlavaForConditionalGeneration, with a CLIP or a SigLIP encoder) reads pictures. The import keeps its image encoder beside the language model, as a vision section of the manifest whose tensors count in the fingerprint, and writes into the tokenizer’s section how an image is written in the chat: the image token, how many of them an image takes, and the tokens around them. A model without one refuses an image with a 400 rather than ignoring it.
An image reaches the model in three steps:
- Pixels. The picture is decoded with Pillow (the
imagesextra of shem-neural, in theshem-neuralimage), converted to RGB and resized as the model’s processor does, then scaled to [0, 1] and normalized. For SmolVLM that is its longest edge made 4 times the encoder’s size with Lanczos resampling, then cut as below; for LLaVA, the checkpoint’s own preprocessing: a CLIP processor’s short edge made the encoder’s size and the middle cut out as a square, a SigLIP processor’s picture resized to the square, with the resampling it names (bicubic). The pixels match transformers’ for the same picture to 1e-7. Pictures past 64 megapixels are refused before they are decoded. - Rows. The encoder, a transformer over 14- or 16-pixel patches, and what takes it to the language model’s width, make one row for each image token. SmolVLM’s connector folds neighbouring patches into one (SmolVLM-256M: 1,024 patches into 64) and projects them. LLaVA reads the layer of the encoder the config names (LLaVA 1.5: the next to last, without the class token; llava-interleave: the last, with all its patches) through a projector of two linear layers: 576 rows for a 336-pixel picture and CLIP’s 14-pixel patches, 729 for a 384-pixel one with SigLIP’s. They are computed once for a picture and kept for the next turns of the conversation.
- Tokens. The chat template writes one
<image>where a message has an image, and the tokenizer expands it into the run the model was trained on, which the processor writes. SmolVLM’s: a picture is cut into 512-pixel tiles, each between<fake_token_around_image>and its own<row_R_col_C>and 64 image tokens, and the whole picture, resized to a tile, follows them after<global-img>. LLaVA’s is the image token as many times as there are rows, and nothing around them; its processor tokenizes a prompt as the tokenizer does by default, so a Llama tokenizer’s<s>begins it, as the chat template of LLaVA 1.5 does not write it, and shem does the same. The session puts the rows in place of those tokens’ embeddings as it reads them, so what the model attends to is the picture, and its state afterwards, saved or committed, is the same as for any session.
Tiles are how SmolVLM sees detail (LLaVA reads one square, so detail changes nothing for it): the processor makes a picture’s longest edge 2,048 pixels, whatever it was, and cuts the result into tiles, so a 4:3 picture is 4 by 3 of them and a square one 4 by 4, with the whole picture as the last view: 13 to 17 views of 64 tokens each, 832 to 1,088 tokens, and an encoder pass for each, a few seconds on a CPU. The tiles and their tokens match the processor’s (do_image_splitting, which the checkpoint’s preprocessor_config.json turns on or off, and shem follows). detail chooses per picture: high and auto (the default) cut it in tiles, and low reads the whole picture in one view, 64 tokens, as OpenAI’s API does with its low. --image-detail low on shem run and "detail": "low" in an image_url part, set it.
shem run takes --image FILE, as many as the first prompt needs:
shem run hf.co/HuggingFaceTB/SmolVLM-256M-Instruct --image cat.png --image-detail low "What is in this picture?"
The API takes them as OpenAI’s does, in a user’s message: {"type": "image_url", "image_url": {"url": "data:image/png;base64,...", "detail": "low"}}, beside text parts, in any order. The URL must be a data: URL: shem never fetches a link, which would let a request make the server reach into the network around it. The image’s tokens count in usage, and count against the context window. A shem_receipt carries the pictures, as data URLs, with the messages, so shem replay reads the same ones; check the receipt’s size before you share it.
What shem leaves out: videos; LLaVA-NeXT’s pictures cut to fit their shape (image_grid_pinpoints), and the encoders of other families. Gemma 3’s image tokens attend to each other in both directions, which no block does yet, and Qwen2-VL positions its tokens in three dimensions (M-RoPE) and reads pictures of any size, which would be new blocks of their own: both are text-only here.
Adapters as layers
A LoRA adapter, as PEFT saves one, is a few megabytes beside the model’s gigabytes, so an image for it is the model’s layers and one more. COPY it in and name it:
FROM hf.co/Qwen/Qwen3-0.6B
COPY golem-lora/ /adapters/golem/
ENTRYPOINT ["shem:generate", "--adapter", "/adapters/golem", "--system", "You are Shem, a golem."]
WARM --until=prompt
golem-lora/ holds adapter_model.safetensors and adapter_config.json. The adapter is merged into the weights it names as the model loads (--adapter may be given again, and they merge in order), so it costs nothing to run; the model’s own layers are the base image’s, pushed and pulled once for every adapter’s image, and the model server shares the loaded base between containers. Sessions and receipts record the adapters by name and a digest of their weights, so a session made with one is read again, not resumed, by a model without it. A --adapter that is not a path in the image is a name under /model/adapters/.
shem merges plain LoRA (and rsLoRA): DoRA, other PEFT types and adapters that train whole modules (modules_to_save) are refused, as is an adapter for weights the model does not have. Quantizing with --quantize int8 quantizes the merged weights.
ModelPack artifacts
ModelPack packages checkpoints as OCI artifacts. shem creates an image twin over the artifact’s layers, adds shem.json and any missing index or chat template, and sets the artifact as its subject.
shem run registry.example.com/team/llama:modelpack "What is a golem?"
shem push registry.example.com/team/llama:modelpack registry.example.com/team/llama:shem
FROM registry.example.com/team/llama:modelpack
ENTRYPOINT ["shem:generate", "--system", "You are a golem."]
WARM --until=prompt
FROM, shem run and shem push also accept artifact OCI layout directories. Twins are cached by artifact digest.
| Detail | Behavior |
|---|---|
| Tar layers | Shared unchanged with the artifact. Use modctl build --raw=false to produce them. |
| Raw layers | modctl’s default; each file must be wrapped in a new tar blob. |
| Model path | Files land at /; dev.shem.model=/. The driver accepts /model or /. |
| Weights | Original checkpoint shards, not re-split by block. Requires safetensors and a supported family. |
| Labels | Model metadata becomes OCI labels; org.opencontainers.image.base.digest identifies the artifact. |
| Namespaces | Reads vnd.cncf.model / org.cncf.model and legacy vnd.cnai.model / org.cnai.model. |
| Docker builds | The frontend can use artifacts as bases, but BuildKit creates new layers. Build on a pushed twin to retain shared blobs. |
Publishing an image as an artifact
shem push --modelpack qwen3 registry.example.com/team/qwen3:modelpack
shem push --modelpack --uncompressed qwen3 registry.example.com/team/qwen3:modelpack-tar
--modelpack publishes model-only layers with metadata from shem.json. The source image is pushed alongside it as the artifact’s subject; oras discover lists the relationship.
- Default: shares the image’s zstd blobs and preserves paths (
model/for imported models). modctl 0.2 cannot extract these. --uncompressed: creates plain tar blobs with files at the root, for modctl extraction and runtimes that mount weights. ModelPack recommends uncompressed weights.- Only layers containing model files alone are included. Tools, compiled layers and session state are excluded.
See the round-trip example and compatibility tests.
Images on Hugging Face
A Hugging Face repo can hold an image: its OCI image layout’s files, oci-layout, index.json and blobs/sha256/*, at the repo’s root. Each revision of the repo holds one image, so its branches, tags and commits are the image’s tags, and latest is main.
shem push qwen3 hf.co/your-user/qwen3-shem # to main, creating the repo
shem push --modelpack qwen3 hf.co/your-user/qwen3-shem:modelpack
shem run hf.co/your-user/qwen3-shem "What is a golem?" # pulled on first use
shem run hf.co/Qwen/Qwen3-0.6B "What is a golem?" # no image there: imported
shem pull and shem run download the layout a repo holds at the revision given. A repo that holds none, but a checkpoint, is imported as a Shemfile of FROM hf.co/ORG/NAME[:REVISION] alone would build it, and kept in the store like a pulled image. A push uploads the blobs first, then the index, removing the blobs only earlier pushes had, so every commit’s index finds its blobs. Pushes and private repos use your Hugging Face token (HF_TOKEN, or hf auth login).
A registry over the Hub
shem registry serves these repos as a read-only OCI registry, for clients other than shem:
shem registry --port 5000 &
oras pull localhost:5000/your-user/qwen3-shem:latest
docker run --rm --runtime io.containerd.shem.v1 --platform linux/riscv32 localhost:5000/your-user/qwen3-shem "What is a golem?"
| Request | Answer |
|---|---|
GET /v2/ORG/NAME/manifests/TAG | The first manifest the revision’s index.json lists, or, in a repo without one, a ModelPack artifact of its files |
GET /v2/ORG/NAME/manifests/sha256:… | That blob, from main or a revision already served |
GET /v2/ORG/NAME/blobs/sha256:… | Up to 1 MB, the blob; larger, a redirect to where Hugging Face keeps it, so weights never pass through the registry |
GET /v2/ORG/NAME/tags/list | latest, the other branches, and the tags |
GET /v2/files/ORG/NAME/… | The same, for an image of a checkpoint’s files; safetensors/ORG/NAME and other formats’ names, for the files of one format of weights |
PUT, POST, PATCH, DELETE | 405: push with shem push IMAGE hf.co/ORG/NAME |
A repo that holds a checkpoint rather than an image is served as a ModelPack artifact made on request: a raw layer for each file but .gitattributes, at its path, typed as weights, documents, code or configs, and a model config from what the Hub says of the repo. A large file’s layer is the file itself, named by the sha256 the Hub keeps for it, so it redirects to the Hub like any large blob; small files are downloaded once to learn their digests. The same commit makes the same artifact. oras pull localhost:5000/huggingfacetb/smollm2-135m-instruct downloads the repo’s files, and shem run localhost:5000/huggingfacetb/smollm2-135m-instruct runs its image twin, which wraps each file in a tar of its own. The artifact is the whole repo, ONNX exports and all, where shem run hf.co/… downloads only what the import needs.
Requests to Hugging Face use this host’s token, so whoever reaches the registry can pull the private repos it can read; it listens on 127.0.0.1 unless given --host. Hugging Face resolves repo names in any case, so a client that needs lowercase names, as Docker does, can pull qwen/qwen3-0.6b-shem for Qwen/Qwen3-0.6B-shem.
shem registry --public is for a registry anyone can reach. It never uses this host’s token, only each client’s, through the distribution spec’s token flow: /v2/ asks clients to log in, and /token gives them back the Hugging Face token they logged in with, once the Hub has confirmed it, or an anonymous one for public repos. A client asked for a gated or private repo without a token of its own is asked to log in. What the registry keeps of a repo, such as small blobs and the artifacts it made, is served only to clients the Hub lets read the repo, which it asks every 5 minutes for each token. The home page lists only repos that aren’t private. Behind a proxy that terminates TLS, as a Space’s does, the registry takes the scheme from X-Forwarded-Proto.
shem registry --public --host 0.0.0.0 --port 5000 &
echo "$HF_TOKEN" | docker login localhost:5000 -u hf --password-stdin # only for gated and private repos
The shem registry Space runs shem registry --public over the whole Hub, at jgalego-shem-registry.hf.space:
docker pull --platform linux/riscv32 jgalego-shem-registry.hf.space/jgalego/smollm2-135m-instruct-shem
oras pull jgalego-shem-registry.hf.space/qwen/qwen3-0.6b
/metrics has the registry’s Prometheus metrics: pulls, the bytes it sent itself, those it had the Hub send and those it streamed, the repos and images it has, and the digests it has learnt. Those digests, the tars of weights’ layers, never go stale (a tar is a function of the files’ contents), so they are kept in a file, registry-digests.json in --cache-dir (shem/ in your cache by default), and a registry that restarts does not read every large file through again; a Space keeps them where it has persistent storage.
Outside /v2/, the registry serves pages for people. / has a search box, counts of the repos served, the pulls, and the bytes sent from the Hub, from the Hub as tars and from the registry, and the repos pulled since it started, last pulled first. /ORG/NAME?tag=TAG shows an image as a model page: badges for its comparison with transformers (from the repo’s comparison.json), size, precision, licence and primed session; its system prompt, the model from its shem.json, its entrypoint and its layers; and beside them, the commands to use it with shem, oras or Docker, its digest, its source checkpoint and its tags. Open pages stay current: they ask /live whether what they show has changed, every 3 seconds for the home page and every 15 for a repo’s, which asks the Hub for the revision’s commit, and show the new version without reloading.
Checkpoints as images of their files
Docker, containerd and Kubernetes take images, not artifacts: layers that are tars, listed for the host’s platform. The registry serves every checkpoint’s repo that way too, under files/, with the repo’s files at the root of the filesystem:
docker pull localhost:5000/files/huggingfacetb/smollm2-135m # every file of the repo
docker pull localhost:5000/safetensors/huggingfacetb/smollm2-135m-instruct # without its ONNX exports
FROM python:3.12-slim
COPY --from=localhost:5000/safetensors/huggingfacetb/smollm2-135m-instruct / /models/smollm2/
The image is listed for linux/amd64 and linux/arm64, and has no entrypoint: it is files, for a Dockerfile to copy, or to mount as a Kubernetes image volume or with docker run --mount type=image. A mounted image is not copied into another: the weights stay on the Hub, and no registry keeps a copy of them.
| Name | Files |
|---|---|
files/ORG/NAME | All of the repo’s but .gitattributes |
safetensors/ORG/NAME | Without those of other formats of weights, by the extensions in their names: no model.onnx, model.onnx_data or pytorch_model.bin |
gguf/, onnx/, bin/, pt/, pth/, ckpt/, h5/, msgpack/, tflite/ | The same, for that format |
- Files up to 1 MB, and those Git keeps itself, share the first layer, which the registry makes and serves.
- Each larger file is a layer of its own: an uncompressed tar of the file, which is the file between a 512-byte header and padding. Past 95 such files, neighbours share layers.
- A tar’s digest is not the file’s, which is the one the Hub knows. The registry reads each large file through once to learn it, so the first pull of a repo waits for that, and afterwards sends the layer as it reads the file from the Hub again. It keeps the digests in memory, by file, and stores no weights. A commit that changes other files reads none of them again.
- These layers pass through the registry, as nothing else does.
--files-limit 16Grefuses to make an image of a checkpoint with more weights than that left to read, which a registry anyone may reach should set. The artifact, at the repo’s own name, is served whatever its size. - Tags are the repo’s revisions, as for the artifact. A repo that holds an image has no image of its files: pull it by its own name.
- A layer answers
Rangerequests, so an interrupted pull resumes.
Comparing an import with transformers
shem-neural-verify runs the check test_model.py makes of each supported model on any import: the prompt’s logits within 1e-3 of transformers’ in float32, and the same greedy reply, one token at a time from the session’s state. It needs transformers, which the gguf extra installs.
uv run --project neural shem-neural-verify Qwen/Qwen3-0.6B ./model --report comparison.json
The Space
space/ is a Hugging Face Space that runs these steps for a checkpoint: it checks the architecture and size before downloading, builds the image with an optional system prompt primed by WARM, compares it with transformers, pushes it to YOU/NAME-shem with a ModelPack artifact on its modelpack branch, and writes a model card and comparison.json. Its convert.py runs the same steps from a terminal.
It runs at jgalego/shem-my-repo. Log in with Hugging Face, name a checkpoint, and the image lands in your account.
Sessions under Docker
Model sessions run in shem-neural-server, keyed by container ID. Containers of images with the same weights share one loaded model, found by the fingerprint in its shem.json, which the server checks against the weights as it loads them (an image that claims another’s fingerprint gets the real weights if they are loaded, and otherwise a model of its own, which no other image is given), and a model loading holds up only the containers that want that model. Install the shim, then start the server as root so it can read containerd-mounted root filesystems. The install script can run it as a systemd service, from the shem-neural release that matches shem:
curl -fsSL https://jgalego.github.io/shem/install.sh | SHEM_NEURAL_SERVICE=1 sh
To start it yourself, give sudo the full path of each program, since its PATH leaves out ~/.local/bin, where uv installs itself and its tools:
sudo env SHEM_BIN="$(command -v shem)" "$(command -v uv)" tool run \
--from "shem-neural==$(shem --version | cut -d' ' -f2)" \
shem-neural-server
Run as root, it listens at /run/shem/neural.sock, where the shim looks. From a repository checkout, run the checkout’s own:
uv sync --project neural
sudo env SHEM_BIN="$(command -v shem)" \
neural/.venv/bin/shem-neural-server
The socket is accessible only to its owner and root. In another terminal:
shem save golem | docker load
docker run -d --name clay --runtime io.containerd.shem.v1 \
--platform linux/riscv32 golem --keep "Who are you?"
docker exec clay shem:generate "What are you made of?"
docker commit clay golem:remembers
docker stop clay
docker rm clay
| Command | What it does |
|---|---|
docker run IMAGE "prompt" | Answer once, then exit |
docker run -i IMAGE | One conversation turn per input line; -t adds shim-side echo and backspace handling |
docker run -d --name c IMAGE --keep "prompt" | Answer and keep the session open |
docker exec c shem:generate "follow-up" | Continue the conversation |
docker commit c IMAGE2 | Pause, save tokens and block state into /.shem; IMAGE2 resumes the conversation |
docker logs, stop, rm, ps | Standard container operations |
The docker run rows omit the required --runtime io.containerd.shem.v1 --platform linux/riscv32 flags for brevity.
A container can write a receipt of a reply. --receipt PATH on a docker run command line, or on a docker exec’s, writes it to PATH inside the container, which docker cp brings out, whether the container is still running or has stopped:
docker run --name clay --runtime io.containerd.shem.v1 --platform linux/riscv32 golem \
--receipt /receipt.json --subject image=ghcr.io/me/golem@sha256:DIGEST "Who are you?"
docker cp clay:/receipt.json . && docker rm clay
shem replay receipt.json
The model server may be root and the container’s files are the image’s, so it opens each name of the path from the directory before it without following a link, and refuses ..: no path leads the write out of the container’s root (directories that are not there are made, and a file is replaced). A path outside the container is the host’s to name, so --warm, --session, --replay and --image stay refused on a container’s command line.
Runtimes do not tell a container which image it came from, so a receipt names it only if the command line says (--subject image=NAME@sha256:DIGEST, the digest of the image as a registry has it, which docker images --digests shows); shem replay needs it, and refuses an image with another digest. Without it the receipt is still a record of the reply, which shem-neural-generate --replay checks on the model’s directory.
A later turn of a kept container’s session has a receipt too, of the whole conversation so far and of the tokens the session had read when it replied, since a conversation read a turn at a time is not always the tokens its whole text makes. A sampled session’s later replies are drawn again from where its generator stood (sampling.after draws in). Receipts are for runs without tools.
Serving OpenAI’s API
shem serve serves a model image as OpenAI’s chat completions API, for the clients and tools written for it:
shem serve golem --port 8000
curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
-d '{"messages": [{"role": "user", "content": "Who are you?"}]}'
Under Docker, --serve PORT serves in the container’s network, which -p publishes. The model server runs the model, as it does a session:
docker run -d -p 8000:8000 --runtime io.containerd.shem.v1 --platform linux/riscv32 golem --serve 8000
| Endpoint | Answers with |
|---|---|
POST /v1/chat/completions | A reply to the messages; with "stream": true, server-sent events as it comes |
POST /v1/completions | A continuation of a text, with no chat template: prompt is one text; max_tokens, stop, stream and logprobs apply |
POST /v1/embeddings | A unit vector for each text of input: the model’s final hidden state at the last token ("shem_pooling": "mean" averages them all), floats or base64. It is a language model’s, so it is as good an embedding as that model is, and best from one trained for it |
GET /v1/models | The model, by the repository it came from |
GET /health | 200 once the model is loaded |
GET /metrics | Prometheus metrics: requests by path and status, their latency, tokens read and made, requests waiting, and replies per pass over the weights; a key is asked for, as for the rest, when there is one |
- Replies are greedy, as the driver’s are, unless the image or a request gives a
temperature; thentop_p,top_kandseedapply too, and the same seed draws the same reply.nmust be 1.max_tokensandstopapply. - The image’s system prompt comes first unless a request gives its own, and a conversation that starts with the image’s primed session goes on from it rather than reading it again.
- Requests are answered together: up to 16 replies share each pass over the model’s weights, which decoding is bound by reading, so several clients cost far less than one after another (a prompt is read alone, in turn, and a reply that fails or whose client leaves does not stop the others). Up to 32 requests wait, after which the API answers
429withRetry-After. Gated DeltaNet and Mamba blocks step their sessions one after another within a pass, so batching helps those models less. Messages are text; tools in requests, and images, are not understood yet. toolsin a chat request are offered to the model through its chat template, and a reply that calls them comes back astool_callswithfinish_reasontool_calls(in a stream, as a chunk oftool_calls);toolandassistantmessages withtool_callscarry the conversation on. The caller runs the tools, as with OpenAI.tool_choiceisautoornone: shem does not force a call.- A user’s message can hold
image_urlparts withdata:URLs for a model that reads images. logprobs(withtop_logprobsin a chat request) gives the log probability of each token of the reply and of the likeliest others, from the model’s own distribution, before any temperature; in a stream, each chunk carries those of the tokens chosen since the last.response_formatcan betext,{"type": "json_object"}or{"type": "json_schema", "json_schema": {"name": ..., "schema": {...}}}. With the last two, only tokens that keep the reply the start of a JSON object (of the schema) can be chosen (a mask on the model’s logits, each step), and once the object closes only the end of the reply can, so what comes back parses and fits, whatever the model would have said. The schema keywords shem enforces aretype(one or a list),enumandconstof scalars,properties(only those keys are written, each once),required,items,minItemsandmaxItems, withadditionalPropertiesonly asfalse; anything else is refused with a 400 rather than quietly ignored. The top level must be an object. Neither can go withshem_receipt, which cannot replay a mask yet.- It listens on
127.0.0.1unless given--host. SetSHEM_API_KEYin the environment, and every request but/healthmust sendAuthorization: Bearer KEY; under Docker, the model server’s environment is the one that counts. A key is read from the environment, not an option, so thatpsdoes not show it. - A page in a browser may call the API only from an origin that
--cors-origin ORIGINallows (or*). - A request body may be 8 MiB, and a client that stays silent for 60 seconds is dropped. A failure after a stream has begun is sent as an
errorevent before[DONE]. - An image serves when it starts with
ENTRYPOINT ["shem:generate", "--serve", "8000"]andEXPOSE 8000.
Compiled layers and tools
A model image can include the compiled RV32IM CPU and call programs on it (tools example):
FROM --platform=$BUILDPLATFORM alpine:3.22 AS tools
RUN apk add --no-cache zig
COPY mul.c .
RUN zig cc -target riscv32-linux-musl -mcpu=generic_rv32+m+a -static -O2 -o mul mul.c
FROM hf.co/Qwen/Qwen3-0.6B
COPY --from=shem:rv32im / /model/compiled/rv32im/
COPY --from=tools /mul /usr/local/bin/mul
COPY mul.json /usr/local/bin/mul.json
ENTRYPOINT ["shem:generate", "--tools", "/usr/local/bin", "--system", "Use the tools for arithmetic."]
CMD ["What is 123456789 times 987654321?"]
$ shem run tools
shem: ran mul 123456789 987654321 on the compiled RV32IM layer, 2,881 instructions
121932631112635269.
COPY --from=shem:rv32imdeterministically compiles CPU weights, machine config and model card. Both builders support it; releases publish the same weights.--tools DIRexposes programs using the chat template’s tool format (JSON or<function=...>tags). A siblingNAME.jsondefines the description and parameters, mapped to arguments in order; without it, the interface acceptsargsandstdin. Seemul.json.- Calls run through
shem run --vcpu neuralwith the image’s weights and filesystem. Output returns as a tool reply; the CPU does not share the language model’s residual stream. - Use a model that calls tools. Qwen3-0.6B does in this example; Qwen3.5-0.8B attempts the multiplication itself and answers incorrectly.
Receipts
shem run --receipt writes down what a model was asked and what it replied. shem replay checks it, on any machine that can run the image:
$ shem run --receipt receipt.json hf.co/jgalego/smollm2-135m-instruct-shem "Who are you?"
I am a Shem, a golem created by the word of the Lord.
shem: wrote a receipt of 18 tokens, the closest call by 0.0238 at token 14, to receipt.json
$ shem replay receipt.json
I am a Shem, a golem created by the word of the Lord.
shem: verified: the model chose the receipt's 18 tokens again
{
"format": "shem.receipt/v1",
"image": "hf.co/jgalego/smollm2-135m-instruct-shem@sha256:5339b1f9226f33bdf3a557e21349dd7a4ad498f29dcebf1a9ef3601dcf9134fd",
"prompt": "Who are you?",
"reply": "I am a Shem, a golem created by the word of the Lord.",
"tokens": [57, 744, 253, 334, 1676, 28, 253, 685, 12164, 2312, 411, 260, 2229, 282, 260, 5151, 30, 2],
"margins": [1.468582, 3.081518, 0.482496, 0.352477, 4.440741, 2.73415, 3.147675, 0.110825, 4.741564, 0.202389, 2.020863, 0.145825, 0.144969, 0.023771, 0.029436, 0.159035, 0.954207, 0.645074],
"runtime": {"shem": "0.3.0", "torch": "2.15.0+cpu", "device": "cpu", "machine": "x86_64", "precision": "float32", "blocks": {"attention": 1, "mlp": 1}}
}
imageis the reference the run was given and the image’s manifest digest. The digest covers everything the reply depends on besides the prompt: the weights, the tokenizer, the system prompt, the primed session, the tools and the compiled CPU they run on. A run with--stateaddsstate, the session’s reference and digest. An OCI layout directory is recorded by its digest alone.tokensare the tokens the model chose, in order: each reply’s and the token that ended it, tool calls included.marginssay how firmly: each chosen token’s logit less the runner-up’s. For a run that drew its tokens, asamplingfield holds the settings and the seed, and each margin is how far the draw was, in probability, from the edge of its token’s share;shem replaydraws again from the seed.runtimeis what computed them: the neural package, torch, the device, the precision and the block versions.
shem replay RECEIPT [IMAGE] pulls the image the receipt names if the store lacks it, refuses an image whose digest is not the receipt’s, replies to the receipt’s prompt and compares each choice. IMAGE names the same image somewhere else, such as a mirror or a layout directory, and --state REF the same session.
| Status | Verdict | Meaning |
|---|---|---|
| 0 | verified | The model chose the receipt’s tokens again |
| 1 | mismatch | The tokens differ where the choice was firm, or are not the reply the receipt gives: this image does not give that reply to this prompt |
| 3 | undecided | The tokens differ at a close call, which another device may make otherwise: replay on the receipt’s device |
| 125 | The receipt could not be replayed: no such image, or one with another digest |
Decoding repeats exactly on one device, while two devices round sums differently. A choice holds on any device whose logits are within half its margin of the receipt’s. shem calls a choice close under a margin of 0.002 in float32, twice the tolerance imports are held to against transformers, and 0.5 in bfloat16. A receipt’s closest call is printed when it is written.
Those tolerances are checked against measurement. neural/jobs/devices.py, a Hugging Face Job, runs 12 conversations of 64 tokens through SmolLM2-360M and Qwen3-0.6B (768 positions each) on the job’s CPU in float32, and along the same path on the same CPU in bfloat16 and on an NVIDIA L4 and an A100 in both types. The largest differences from the CPU’s float32 logits (of the 16 likeliest tokens), over both models:
| Device and type | Largest logit difference | 99th percentile | Largest move of a margin | Choices flipped | Largest margin that flipped |
|---|---|---|---|---|---|
| L4, float32 | 0.00008 | 0.00003 | 0.00007 | 0 of 1,536 | |
| A100, float32 | 0.00007 | 0.00003 | 0.00007 | 0 of 1,536 | |
| CPU, bfloat16 | 0.87 | 0.37 | 1.25 | 33 and 39 of 1,536 (two hosts) | 0.25 |
| L4, bfloat16 | 0.80 | 0.32 | 0.72 | 27 of 1,536 | 0.25 |
| A100, bfloat16 | 1.14 | 0.32 | 0.71 | 22 of 1,536 | 0.15 |
In float32 the devices are 28 times closer than the tolerance (a margin moved by 0.00007 at most, against 0.002, and the closest call among the positions, a margin of 0.003, did not flip). In bfloat16 no choice with a margin over 0.25 flipped, half the tolerance, but the logits differ by up to 1.14, so a firm margin by the half-the-difference rule would be 2.3: 0.5 is what measurement supports, and a receipt of a bfloat16 run is more often undecided on another device for it. The sample is two models and 12 prompts, not a proof.
A replay shows that this image gives this reply to this prompt. It does not show who ran it, or when: for that, sign the receipt. shem sign receipt.json hands it to cosign (keyless, by your identity, or with --key) and writes receipt.json.sigstore.json beside it; shem verify receipt.json --certificate-identity ME --certificate-oidc-issuer ISSUER checks it, and the signature’s entry in Sigstore’s transparency log says when. SHEM_COSIGN names another cosign. To see what a change to the prompt does, run the changed prompt: nothing is sampled, so any difference in the reply comes from the change.
The shem replay Space checks a receipt in a browser: paste one, and it pulls the image, replays the prompt, and shows the verdict and each token marked by its margin. It then runs a changed prompt on the same image and shows how the reply differs, a word at a time. It takes receipts of images in public Hugging Face repos, up to 2.5 GB and 512 tokens, whose entrypoints run a model and nothing else: no tools and no server. Its steps are space/replay.py, which runs from a terminal too:
uv run --project neural python space/replay.py receipt.json --prompt "Who am I?"
Receipts come from shem run, from a container’s command line with --receipt, and from the API on request: a chat completion request with "shem_receipt": true gets a receipt of its reply in the response, and in a stream’s last chunk. It holds the messages the model was given (the image’s system prompt included), the request limits (max_tokens, stop) and the image shem serve named, and shem replay reads the conversation again and draws the reply as the API did; under Docker the server does not know its image’s digest, so those receipts name none. Sessions under Docker write none yet. A receipt names its image by the reference the run was given, so once a repo is pushed to again, checking an older receipt takes the image it was made with, given to shem replay RECEIPT IMAGE.
Running
A plain shem run of a model asks your own model server to reply, and starts one if none is running: it keeps the model loaded for 10 minutes after each run, so the second run of a model skips reading its weights (a few seconds for a small model, against one for the first), and exits after 15 minutes with no connection. Its log is server.log in shem’s home. SHEM_DAEMON=0 runs the driver in a process of its own instead, as -i, --receipt and a terminal’s prompt always do.
The server defaults to --device auto; use --device cpu or --device cuda to select explicitly:
uv run --project neural shem-neural-server --device cuda
Recorded results from jobs/models_gpu.py:
| Model | CPU tokens/s | L4 tokens/s |
|---|---|---|
| Qwen3-0.6B | 7.1 | 27.8 |
| Qwen3.5-0.8B | 5.6 | 31.2 |
shem run caches unpacked images at $SHEM_HOME/rootfs/<digest>. Computation uses float32 unless the entrypoint gives --dtype bfloat16, which halves the memory: Qwen3-30B-A3B’s weights take 61 GB instead of 122 GB. Results are repeatable on the same device, not guaranteed bit-identical across devices. A session records the type it was computed in, and a model computing in another reads its tokens again.
Next
- Compiled layers that read and write the residual stream directly.
Shemfile
A Shemfile uses Dockerfile syntax to build OCI images. WARM adds a build-time snapshot of a program, VM or model session.
just toolchain
shem build -t hello examples/hello # build into the local image store
shem run hello # run it
shem images # list the store
shem tag hello hello:1.0 # store it under another name too
shem inspect hello # its ID, settings and layers, as JSON
shem history hello # the instruction behind each layer
shem build -o hello.oci examples/hello # or write an OCI image layout directory
shem push hello ghcr.io/your-user/hello:1.0 # push to an OCI registry
shem pull ghcr.io/your-user/hello:1.0 # pull into the store, and run it by that name
docker save hello | shem load # or load an image docker build made
shem rmi hello # remove it from the store
shem prune # delete unpacked copies of images no longer stored
shem prune --all # and every copy, and the build cache
shem images --format takes json, or a Go template as docker images --format does, such as '{{.Repository}}:{{.Tag}} {{.Size}}', after table for aligned columns with headers. Its fields are .Repository, .Tag, .ID, .Digest, .Kind (program, vm or model), .Size and .Bytes, and its functions Docker’s json, upper, lower, title, truncate, pad, join, split and len. shem images -q prints the IDs alone, which shem rmi takes as well as names: an ID tagged more than once needs -f to remove every tag. tag, inspect and history take IDs too, or an OCI layout directory. shem history takes --format as well, with the fields .ID, .Digest, .CreatedBy, .Comment, .Size and .Bytes, and shem inspect -f a template over the JSON it prints, such as '{{.Config.Entrypoint}}'.
With docker build
To use shem’s BuildKit frontend, start the Dockerfile with its syntax directive:
# syntax=ghcr.io/jgalego/shem/dockerfile:latest
FROM hf.co/Qwen/Qwen3.5-0.8B
ENTRYPOINT ["shem:generate", "--system", "You are Shem, a golem made of clay."]
CMD ["Who are you?"]
WARM --until=prompt
The published frontend and runtime images are built for linux/amd64 and linux/arm64.
docker build --platform linux/riscv32 -t golem .
Run it with docker run through the containerd shim, or with docker save golem | shem load and shem run golem.
The frontend translates shem instructions into Docker build stages:
| Instruction | BuildKit behavior |
|---|---|
FROM hf.co/... | Import in shem-neural, then copy weights into layers |
ModelPack base or COPY --from source | Fetch the artifact and lay files out as its image twin, without sharing the original blobs |
WARM --until=prompt | Prime the model and copy session state into /.shem |
KERNEL | Set dev.shem.kernel and dev.shem.bootargs labels |
| Other stages | Ordinary Docker stages on the build platform |
The frontend and runtime images support linux/amd64 and linux/arm64; the resulting shem image uses linux/riscv32. RUN is not allowed in shem stages. Program and VM WARM require shem build, not docker build.
Build options:
| Option | Use |
|---|---|
--secret id=HF_TOKEN,env=HF_TOKEN | Access gated Hugging Face models |
--secret id=docker_config,src=$HOME/.docker/config.json | Authenticate to a registry |
--allow network.host | Reach a registry on localhost |
--build-arg SHEM_NEURAL_IMAGE=IMAGE | Select another runtime image |
Model downloads are cached between builds. Use docker push and docker save normally; shem run also accepts an extracted OCI layout from docker save.
Examples
The hello example cross-compiles in a Docker stage:
FROM shem-toolchain AS build
WORKDIR /src
COPY hello.c .
RUN rv32-cc -O2 -o hello hello.c
FROM scratch
COPY --from=build /src/hello /bin/hello
ENTRYPOINT ["/bin/hello"]
CMD ["from", "a", "shem", "image"]
The warm-shell example freezes BusyBox before its first read:
FROM shem-busybox AS busybox
FROM scratch
COPY --from=busybox / /
ENV PATH=/bin:/sbin:/usr/bin:/usr/sbin
ENTRYPOINT ["/bin/sh"]
WARM --until=syscall:read
Build it after creating shem-busybox:
just busybox-image
shem build -t warm-shell examples/warm-shell
$ printf 'echo hello from a warm shell\nuname -m\n' | shem run warm-shell
hello from a warm shell
riscv32
shem-toolchain and shem-busybox are Docker images built from toolchain/Dockerfile by just toolchain and just busybox-image.
Stages
The last stage produces the image. It must use one of the FROM sources below. Other stages supply files through COPY --from; Docker stages build only when needed. Local paths are relative to the build context, and registry bases are pulled on first use.
Instructions
| Instruction | In a shem stage |
|---|---|
FROM | scratch, a Hugging Face model, checkpoint directory or GGUF file (models.md), or a shem image or a ModelPack artifact (models.md), in a registry or a layout directory |
COPY --from=shem:rv32im src dest | Compiles and copies the RV32IM CPU for model tools |
COPY [--from=stage] src... dest | As in Docker: a directory’s contents are copied into dest; a file goes to dest, or into it when dest ends in / or there are several sources. Each COPY is one layer. Sources must stay inside the context. |
ENV, WORKDIR, ENTRYPOINT, CMD, ARG, LABEL | As in Docker, including shell and exec forms, and $NAME and ${NAME} substitution from ARG and ENV |
WARM | Save build-time state; see below |
KERNEL path [command line] | Select a kernel; see VM images |
RUN | Not allowed. Build in a Docker stage and COPY --from it. |
Set resource limits with shem run --mem and --max-steps, not Shemfile instructions.
WARM
WARM --until=<condition> [--max-steps=<n>]
Runs the entrypoint at build time until the condition holds, then freezes the container into a state layer. shem run resumes from that point instead of starting the process again.
Conditions:
syscall:<name>orsyscall:<number>: stop before servicing the first matching call. At run time it receives live input. Names includeread,write,openat,execve,wait4andclock_nanosleep.steps:<n>: stop onceninstructions have retired.ebreak: stop when the guest executesebreak, and resume after it. A program can use this to mark itself ready.
--max-steps fails the build if the condition is not reached in time (default: 4 billion instructions). A later WARM resumes from the previous one’s state.
The guest runs with an empty stdin; its output goes to the build’s stderr. The frozen container must be a single process with only stdin, stdout and stderr open: other open files live on the host and are not part of the snapshot yet.
A state layer holds:
machine.state: canonicalMachineState, with pc, registers, retired instruction count and memory.container.json: working directory, umask, memory map, signal state, LR/SC reservation, virtual clock and PRNG state.
Files the guest wrote during WARM become an ordinary filesystem layer, with whiteouts for deletions.
Program and VM snapshots are built on the reference vCPU. Their canonical state can resume on either vCPU. Model images instead use WARM --until=prompt to save a primed language-model session (models.md).
A warm program image takes no arguments or environment at run time, and runs with the memory it was frozen with.
VM images
KERNEL <path> [command line]
shem run boots this kernel from the image filesystem in VM mode, with the console on stdio. The default command line is earlycon=uart8250,mmio,0x10000000,1000000 console=ttyS0; default memory is 64 MiB, configurable with --mem.
In a VM image, WARM boots the kernel at build time and freezes the machine. Its conditions are:
output:TEXT: stop once the console’s output ends withTEXT, such as a shell’s prompt. Quote it to include spaces; in double quotes, JSON escapes such as\nwork.steps:<n>: stop onceninstructions have retired.
The state layer holds machine.state and vm.json, the host’s half of the hardware (see vm.md).
Image format
A shem image is a standard OCI image for linux/riscv32, stored as an OCI layout. Settings use these labels:
| Label | Value |
|---|---|
dev.shem.machine | Machine type |
dev.shem.memory | Warm image’s memory size |
dev.shem.kernel, dev.shem.bootargs | VM kernel path and command line |
dev.shem.model | Model directory |
A warm image’s last layer holds its state under /.shem. The config’s history records the Shemfile line behind each layer, and the instructions that made none between them, as shem history and docker history show it. The WARM that made the state layer comes last, commented state, even when later lines added layers before it.
Layouts in shem’s earlier format, with these media types, can still be read:
| Media type | Contents |
|---|---|
application/vnd.shem.config.v1+json | Entrypoint, cmd, env, workdir, labels, the machine (rv32im), a warm image’s memory size, and a VM image’s kernel and command line |
application/vnd.oci.image.layer.v1.tar+zstd | Guest filesystem layers, in the standard format |
application/vnd.shem.state.v1.tar+zstd | A WARM snapshot, always the last layer: a container’s (machine.state, container.json) or a VM’s (machine.state, vm.json) |
New layers use zstd-compressed tars. A booted Linux image is about 2 MB despite containing 64 MiB of RAM, mostly zeros. Uncompressed layers remain readable; inherited layers keep their original blobs and compression. A manifest can identify a related artifact through subject, as ModelPack twins do.
Images in the local store live under $SHEM_HOME/images/<name>/<tag>, by default ~/.local/share/shem/images. Program and VM runs unpack a fresh filesystem and remove it afterwards. Model images cache their unpacked filesystem.
A builder, a pull, a load, shem tag, shem rmi and shem prune take a lock on the store while they change it, so processes at once, builds of one tag among them, never leave half an image or remove one a build is storing; a built or pulled image is written whole beside the store and moved in. Reading takes no lock.
Registry transfers use ORAS and preserve manifest digests. Use --plain-http for a local registry without TLS.
The build cache
A model imported at a pinned revision, a commit (FROM hf.co/ORG/NAME:COMMIT), is imported once: later builds link the files the first one made, and a WARM --until=prompt that primes the same session on the same layers and driver options takes it from the cache too, so rebuilding such an image takes a fraction of a second where the first build took the import and the prime. A model at a branch, as FROM hf.co/ORG/NAME is, could be another model by now, so it is imported again, as are checkpoints and GGUF files in the build context. The cache sits beside the image store, links its files rather than copying them, and shem build --no-cache or SHEM_NO_CACHE=1 goes without it; shem prune --all empties it. A program’s or VM’s WARM is cached too: it runs the same for the same layers, configuration, limits and memory, since its clock and its host are virtual, so a build that has run it before takes its state, and the files it wrote, from the cache. COPY is not cached.
Reproducibility
Layers have sorted entries, timestamps of 0 and root ownership. Compression is deterministic; guest builds use a virtual clock, a seeded PRNG and empty stdin. With the same resolved base image, source files and build options, builds produce the same manifest digest, warm images included. Pin model revisions and Docker-stage inputs when repeatable builds are required.
Copy-on-write
- Shared layers. Images that hold the same layer keep one copy of it on the disk: a pulled, loaded or installed image’s blobs are hard links to the store’s own file for each (
$SHEM_HOME/blobs), and the unpacked copies hold a file of a mebibyte or more as a link to one in$SHEM_HOME/files, named for its content and mode. Two models with the same weights, or a model and the image built on it, take their space once, in the layouts and again in the copies unpacked to run them. A shared file is read-only in the unpacked copy, which a write would change for every image that holds it; a run’s overlay copies it up when a guest changes it, so a run on an overlay can still write to one. A file’s last link going, with the image or the copy that held it, takes it from the pool:shem rmiandshem prunedo. Where the store’s directories are not on one filesystem, or the system links no files, each image keeps its own, as before. - Filesystems. A program or VM run’s files are an overlay of the image’s, as far as the system lets a user mount one: the image is unpacked once, into a copy that
shem pruneremoves with the image, and each run mounts the kernel’s overlayfs over it, with an empty directory for what the guest creates, changes and deletes, removed when the run ends. Nothing is unpacked or copied for a run, and a guest cannot change the copy the next run starts from. The mount is made in theshemprocess’s own user and mount namespaces, so it needs Linux 5.11 or later and a user the kernel lets make them (Ubuntu 24.04 does not by default:sysctl kernel.apparmor_restrict_unprivileged_userns=0); elsewhere, and withSHEM_NO_OVERLAY=1, a run unpacks every layer into a directory of its own, as it did before.shem doctorsays which. A buildFROMan image already built (a program, a VM or a model image, as againstscratchor a Hugging Face checkpoint) is on one too: the base is that unpacked copy, and the build’sCOPYandWARMwrite above it, so a base of gigabytes is not unpacked again for each build; the image made is the same, digest for digest, as one built from unpacked layers. A Shemfile with Docker stages unpacks the base, since those run as programs of the build, in the namespaces the overlay is mounted in, which may not reach Docker.shem run --root DIR --root-overlay PROGRAMruns an executable on an overlay of a directory the same way, so that what it writes never reachesDIR(where the system cannot mount one, a warning says so and the changes go toDIR): the model server’s--toolsuse it, since the programs it runs would otherwise write to the image’s kept copy, which every later run reads. The containerd shim has nothing to add: containerd gives it an overlay of the image’s layers for each container, as for any runtime. - Reference memory.
forkcopies the guest’s memory. - Neural memory. The server shares 4 KiB pages between forks and restored snapshots, copying a page on its first write. The dense executor and GPU harness do not share pages (neural.md).
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:
| Tensor | Shape | Role |
|---|---|---|
decode_w, decode_c | 48 × 32, 48 | A 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_c | 32 × 5, 32 | The same trick for 5-bit register numbers and shift amounts |
imm_bits | 5 × 32 × 32 | Selection matrices from instruction bits to immediate bits, one per format, sign extension included |
format_route, result_route, next_pc_route, branch_route, exit_route | 48 × n | Routing tables: which format, result, next pc, comparison and exit each instruction uses |
uses_imm, load_size, store_size | 48 | Per-instruction flags and sizes |
sll, srl | 32 × 32 × 32 | One shift matrix per shift amount; the shifter is attention over them |
sra_fill | 32 × 32 | Sign-bit fill for each arithmetic-right-shift amount |
byte_bits, powers | 256 × 8, 32 | Byte-to-bits lookup table, and the weights that turn bits into a value |
Weights are saved as safetensors for inclusion in images.
State
| Part | Shape | Representation |
|---|---|---|
| Register file | B × 32 × 32 | A delta-rule state with one row of bits per register |
| Memory | B × mem_size | A delta-rule state with one row per byte |
| pc | B, plus its two low bits | The pc’s low bits drive the alignment check |
| instret | B | Instructions retired |
| base | B | The 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:
- 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. - Decode. The mismatch-counting layer gives the instruction one-hot. Three more give one-hots for
rd,rs1andrs2. - Operands. Attention reads of the register file with the
rs1andrs2one-hots give the operands’ bits. The selection matrices give the immediate’s bits. The second operand is the immediate orrs2, chosen byuses_imm. - Units. Every unit computes its result for every guest: adder, logic (
a·b,a + b − a·b,a + b − 2a·bon bits), shifter (attention over the shift matrices, with sign fill forsra), 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. - 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.
- Routing. The instruction one-hot times the routing tables picks the result for
rd, the comparison that decides a branch, and the next pc. - 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:
| Unit | Dense | Fused |
|---|---|---|
| Memory | A float64 delta-rule state, one row per byte; one-hot keys and matrix products, O(memory) per access | Bytes in shared 4 KiB pages with copy-on-write (see below); indexing, O(1) per access |
| Register file | One-hot reads, and delta-rule writes over the whole matrix | Gathers of the two operand rows, and the same write to the one row it can change |
| Shifter | Attention over the shift matrices | Integer shifts |
| Bits of a value | 35 threshold layers | Shifts and masks |
| Byte to bits, 5-bit index | One-hot times a table | Index into the table |
| Division | 32 unrolled layers | Integer 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.
CLONEcopies the page table; writes copy shared pages on demand.RESTOREinterns 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:
| Guests | Instructions/s, total | Per guest | Memory pages |
|---|---|---|---|
| 1 | 1,569 | 1,569 | 2 |
| 8 | 10,999 | 1,375 | 9 |
| 32 | 41,468 | 1,296 | 33 |
| 64 | 76,320 | 1,193 | 65 |
| 128 | 82,897 | 648 | 129 |
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.
| Op | Arguments | Result |
|---|---|---|
1 CREATE | u32 memory size, optionally u32 base address (default 0) | u32 id |
2 DROP | ||
3 CLONE | u32 id of the copy | |
4 RUN | u64 budget | u8 exit reason, u32 detail, u32 pc, u64 instructions |
5 GET_REG | u8 index | u32 |
6 SET_REG | u8 index, u32 value | |
7 GET_PC | u32 | |
8 SET_PC | u32 | |
9 READ_MEM | u32 address, u32 length | bytes |
10 WRITE_MEM | u32 address, bytes | |
11 RESET | ||
12 SNAPSHOT | canonical machine state | |
13 RESTORE | canonical machine state | |
18 SET_COMPRESSED | u8: 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):
| Guests | CPU | L4, best mode (before → with byte registers) | A100, eager | A100, compiled + graph | A100, eager + graph |
|---|---|---|---|---|---|
| 1 | 881 | 4,818 → 6,655 | 192 | 12,859 | 2,086 |
| 64 | 27,985 | 278,995 → 390,706 | 12,187 | 577,138 | 121,028 |
| 1,024 | 891,211 → 1,351,532 | 189,646 | 2,821,098 | 1,399,234 | |
| 4,096 | 998,556 → 2,727,032 | 760,787 | 3,549,051 | 3,664,716 | |
| 16,384 | 945,402 → 3,648,414 | 3,026,696 | 3,986,316 | 6,556,971 | |
| 32,768 | 968,596 → 3,320,424 | 6,118,754 | 3,166,873 | 7,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.
VM mode
shem boot boots a no-MMU Linux kernel with its console on stdio. WARM saves a booted VM so shem run can resume at the shell prompt.
just linux-image # a prebuilt Linux 6.8 for RV32 without an MMU, with a BusyBox initramfs
shem boot target/linux/Image # boots to a root shell in about two seconds
shem build -t linux examples/linux # boots it once, at build time, and freezes it at the prompt
printf 'uname -a\npoweroff\n' | shem run linux # resumes at the prompt, in a fraction of a second
[ 0.000000] Linux version 6.8.0-rc1mini-rv32ima ...
[ 0.000000] Machine model: shem
...
Welcome to mini-rv32ima Linux
~ # uname -sm
Linux riscv32
~ # poweroff
The host is the machine
In VM mode the host emulates hardware, not system calls (vm.rs). Both modes use an RV32IM vCPU:
| The guest does | The vCPU | The host |
|---|---|---|
A CSR instruction, mret, wfi | Exits: illegal instruction | Carries it out against machine-mode CSRs it keeps: mstatus, mie, mip, mtvec, mscratch, mepc, mcause, mtval, and the counters |
ecall, ebreak, an illegal instruction, a bad access | Exits | Delivers a trap, as hardware does: mepc, mcause and mtval set, interrupts disabled, the previous privilege saved, and a jump to mtvec |
| Atomics | Exits: illegal instruction | Emulates them, as in container mode |
| A load or store outside RAM | Exits: memory fault | Decodes the instruction and emulates the device, as KVM leaves MMIO to userspace |
| Waits for its timer | Raises the timer interrupt between slices, and on wfi skips straight to it |
The virtual timer ticks at 1 MHz, once per 100 instructions. Execution stops exactly when mtime reaches mtimecmp, independent of slice boundaries or snapshots. wfi skips idle time.
The machine
The machine is compatible with mini-rv32ima:
| Address | Device |
|---|---|
0x80000000 | RAM (64 MiB by default), with the kernel at its start and the device tree at its top |
0x10000000 | 16550 UART: the console |
0x11000000 | CLINT: the timer (mtime, mtimecmp) |
0x11100000 | syscon: writing 0x5555 powers off, 0x7777 reboots |
The host generates the device tree (fdt.rs) for the memory size it is given, and boots the kernel by the RISC-V boot protocol: in machine mode, at the start of RAM, with the hart id in a0 and the device tree’s address in a1.
Booted snapshots
A snapshot contains canonical vCPU state and vm.json: CSRs, privilege level, timer state, skipped idle time, LR/SC reservation and instruction count. It can resume on either vCPU.
A VM image selects its kernel with KERNEL and optionally boots it at build time with WARM:
FROM scratch
COPY Image /boot/Image
KERNEL /boot/Image
WARM --until=output:"~ # "
--until=output:TEXT stops when console output ends with TEXT; --until=steps:N stops after N instructions. The image includes RAM (64 MiB by default). Without WARM, shem run boots from scratch. The Linux example downloads a checksum-pinned kernel.
Tests
tests/vm.rs: CSRs, traps, timer interrupts, UART, poweroff, snapshots and VM image builds.just vm-tests: Linux boot, shell commands, snapshot resume and reproducible image digests.
On the neural vCPU
Boot on the reference vCPU, then resume on the neural one. A cold boot takes about 350 million instructions: days at roughly 1,000 instructions/s. A shell command after resume takes about 180,000 instructions, or several minutes.
Start the server in a separate terminal:
just neural-server
Then resume the linux image built above:
printf 'echo $((6 * 7))\npoweroff\n' | \
shem run --vcpu neural linux
VM RAM starts at 0x80000000; the network uses this base for fetches, loads and stores. shem boot --vcpu neural also works, but does not skip the cold boot.
Not yet
- Interrupt controller, block devices and networking. The UART is polled.
containerd
containerd-shim-shem-v1 (crates/containerd-shim-shem) runs static RV32 Linux executables from OCI images on a shem vCPU. Docker and Kubernetes reach it through containerd. Model images use the same shim with a host-side session driver (models.md).
With Docker
cargo build --release -p containerd-shim-shem
sudo install target/release/containerd-shim-shem-v1 /usr/local/bin/
docker build --platform linux/riscv32 -t shem-hello examples/hello
docker run --rm --runtime io.containerd.shem.v1 --platform linux/riscv32 shem-hello one two
Docker 23+ accepts the shim name directly as --runtime; no daemon configuration is needed. The hello program exits with its argument count: 3 here.
To use the neural vCPU, start the neural server as root, so that it listens where the shim looks, /run/shem/neural.sock, and add:
docker run --rm --runtime io.containerd.shem.v1 --platform linux/riscv32 \
--annotation dev.shem.vcpu=neural shem-hello one two
With -t, a program gets a terminal of its own, which echoes what is typed and lets the program set it up, as a shell does to edit lines. Ctrl-C, Ctrl-\ and Ctrl-Z send their signals to the program’s foreground processes, init included, and the window takes the size of the terminal docker run -it runs in.
docker commit freezes a running program into the image it makes, and a container of that image goes on where the program was, its memory and registers as they were. With an image of tally.c, which prints a running total of the numbers it reads:
$ docker run -i --name tally --runtime io.containerd.shem.v1 --platform linux/riscv32 tally
1
total 1
2
total 3
In another terminal, while it waits for more:
$ docker commit tally tally:at-3
$ echo 4 | docker run -i --rm --runtime io.containerd.shem.v1 --platform linux/riscv32 tally:at-3
total 7
A program can be frozen when it is a single process with only its standard streams open; otherwise the commit holds its files alone.
To load an image built with shem build, including its WARM snapshot:
shem save IMAGE | docker load
Keep both --runtime io.containerd.shem.v1 and --platform linux/riscv32. Without the runtime, Docker tries the host CPU and fails with exec format error.
Docker Desktop
Docker Desktop, on macOS, Windows and Linux, runs containerd in a VM of its own, which cannot see a shim installed on the host. Build images with Docker there, and run them with shem:
docker build --platform linux/riscv32 -t shem-hello examples/hello
docker save shem-hello | shem load
shem run shem-hello one two
shem load stores each image of the archive under the name docker save gave it, or under --tag, and refuses images for other platforms. Model images run the same way: shem run starts their session driver itself, without the model server.
With containerd
docker build --platform linux/riscv32 -t shem-hello examples/hello
docker save shem-hello | sudo ctr images import -
sudo ctr run --rm --runtime io.containerd.shem.v1 \
docker.io/library/shem-hello:latest demo /bin/hello one two
Install the shim as above, on containerd’s PATH. The command after the container ID (demo) replaces the image entrypoint, so include /bin/hello.
How it works
containerd calls the shim’s task service over ttrpc:
| Request | Action |
|---|---|
create | Mount the root filesystem prepared by the snapshotter |
start | Read arguments, environment, working directory and memory limit from config.json; run with containerd’s FIFOs as stdio. Default guest memory: 64 MiB. |
wait, state | Report init’s exit status; publish lifecycle events so Docker observes it |
kill | Stop at the next instruction slice, or in a wait for input, with the signal’s shell exit status |
resize_pty | Set the window size of a program’s terminal, and send the program SIGWINCH |
pause, resume | Freeze a program into /.shem, where docker commit takes it, until it goes on; save a model session there |
delete | Unmount the root filesystem |
Implementation: bundle.rs loads bundles; service.rs handles the protocol. Run just docker-test or just containerd-test for integration tests.
Exec and statistics
docker exec CONTAINER PROGRAM starts another program in a running program container, with its own memory and streams, in the container’s filesystem and network (its sockets included: a program and a client exec adds can talk), and ends with the program’s status. -i gives it stdin, and -t a terminal of its own (as for docker run -t, but the program’s: its settings, its window size, and the keys that send signals, which go to its foreground process group and not the container’s). The program joins at the next slice, about a hundredth of a second on the reference vCPU. A container whose processes are all blocked for good on something only a client would give it (an accept waiting for an exec’d client) waits, as on Linux, for a program to join or for a stop, so a server can be started first and its client added with docker exec.
docker stats and kubectl top read the container’s statistics, which the shim reports as cgroup v2 metrics: the processes it has, the CPU time its instructions took on the virtual clock (one nanosecond each), and its guest memory.
Not yet
- Checkpoints.
Model containers support exec, commit and terminal input too; see sessions under Docker.
Kubernetes
Kubernetes runs shem containers through a RuntimeClass, the way it runs WebAssembly with runwasi: the kubelet asks containerd for the shem runtime, and containerd starts the shim (containerd.md).
On each node
Install the shim on containerd’s PATH:
sudo install containerd-shim-shem-v1 /usr/local/bin/
Add the runtime to containerd’s configuration (/etc/containerd/config.toml, configuration version 3), and tell its image service that the runtime’s images are for linux/riscv32.
[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.shem]
runtime_type = 'io.containerd.shem.v1'
[plugins.'io.containerd.cri.v1.images'.runtime_platforms.shem]
platform = 'linux/riscv32'
Restart containerd.
sudo systemctl restart containerd
Images for the node’s platform
containerd through 2.4 selects images by the node’s platform, even for a different runtime class. An image listed only for linux/riscv32 can fail to pull. Also list it for the node’s platform:
shem push --platform linux/amd64,linux/arm64 hello ghcr.io/your-user/hello:latest
shem save --platform ... works for local imports. With Docker, use docker build --platform linux/riscv32,linux/amd64,linux/arm64; the guest remains RV32.
containerd’s development branch supports selection by runtime class using runtime_platforms above and the kubelet’s RuntimeClassInImageCriApi feature gate.
In the cluster
From the repository checkout:
kubectl apply -f examples/kubernetes/runtimeclass.yaml
kubectl apply -f examples/kubernetes/hello.yaml
kubectl logs shem-hello
Model Pods also require a model server on the node. just kubernetes-test configures a kind node and runs the hello Pod.
Model images as image volumes
A model image’s /model is a Hugging Face checkpoint. Mount it as an image volume to use another inference server without running shem.
Publish for the node’s platform and enable the ImageVolume feature gate where required:
shem build -t smollm2 examples/smollm2
shem push --platform linux/amd64 smollm2 ghcr.io/your-user/smollm2:shem
Pod spec fragment:
volumes:
- name: model
image:
reference: ghcr.io/your-user/smollm2:shem
containers:
- name: server
# Set the server image and point it at /models/model.
volumeMounts:
- name: model
mountPath: /models
readOnly: true
The complete Pod example loads the checkpoint with transformers. Replace your-user in the manifest before applying it. just kubernetes-model-volume-test checks volume mounting in kind.
Hugging Face checkpoints as image volumes
shem registry serves any checkpoint on Hugging Face as an image of its files, listed for the node’s platform. A Pod mounts it without shem on the node, an init container to download it, or a copy of the weights in a registry of yours:
volumes:
- name: model
image:
reference: jgalego-shem-registry.hf.space/safetensors/huggingfacetb/smollm2-135m-instruct
containers:
- name: server
# Set the server image and point it at /models/smollm2.
volumeMounts:
- name: model
mountPath: /models/smollm2
readOnly: true
The node pulls each file of weights once, as a layer, and Pods that mount the same checkpoint share it. Pin a revision with a tag, as in …/smollm2-135m-instruct:COMMIT, or an image with its digest. The complete Pod example loads the checkpoint with transformers.
The reference above is the shem registry Space, which makes images of checkpoints with up to 16 GB of weights. For more, or for private repos read with a token of the cluster’s, run shem registry where the nodes reach it.
shem on Windows
shem.exe runs on Windows 10 and later without WSL: the runtime, the image store and the commands that need no Linux kernel. Build it with cargo install --path crates/shem (Rust 1.88 or later), or take shem-VERSION-x86_64-pc-windows-msvc.tar.gz from a release. Models need uv on the PATH, as everywhere.
shem build -t hello examples/hello
shem run hello
shem run qwen3 "What is a golem?"
The store is in %LOCALAPPDATA%\shem (or SHEM_HOME). Everything else in the docs works the same, with these exceptions.
What Windows does not have yet
| Left out | Why | What happens |
|---|---|---|
The model server that outlives shem run, and --vcpu neural | Both are reached over Unix sockets, which Rust’s standard library has not got on Windows | A model run starts the driver itself and loads the weights each time; --vcpu neural is refused. |
| Overlays for runs and builds | overlayfs is Linux’s | A run unpacks its image into a directory of its own, as it did before overlays; --root-overlay warns, and the guest’s changes go to the directory. |
| Layers shared between images | Needs the link counts of Unix’s file metadata | Each image keeps its own blobs and unpacked files. |
| A raw terminal | Windows’ console is not a termios terminal | A guest reads lines from the console; a full-screen program or a shell that edits its own lines does not work. Ctrl-C ends shem. |
The containerd shim and docker run --runtime io.containerd.shem.v1 | The shim is Linux’s, and Docker Desktop runs containers in a VM | Build with Docker and shem load, as on Docker Desktop. |
| Special files | Windows has no FIFOs, device nodes or sockets as files | A guest that makes one gets an error. |
What differs
- A guest’s file names must be names Windows can have: one with
\ : * ? " < > |is refused, and a name that is not UTF-8 cannot be made. - Files have no permission bits beyond read-only: every file looks executable to the guest, and a layer built on Windows records its files that way, so an image built there is not digest for digest the one built on Linux or macOS.
- Symbolic links need a user the system lets make them: an administrator, or developer mode. Without it, a guest’s
symlinkfails. - Inode numbers and link counts are made up (a file’s creation time, and one link), and access times are the host’s to move.
- A registry’s port in an image name (
localhost:5000/app) is kept in the store underlocalhost%5000.
The Windows build is checked by CI on every change (cargo test -p shem on a Windows runner), with the tests of what it has not got skipped. It has not had the breadth of use the Linux build has.