Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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."]
SourceFROM example
Hugging Face checkpointFROM hf.co/Qwen/Qwen3.5-0.8B
Pinned revisionFROM hf.co/ORG/NAME:REVISION
Checkpoint directory in the build contextFROM checkpoint/
GGUF repository and quantizationFROM hf.co/Qwen/Qwen3-0.6B-GGUF:Q8_0
GGUF file in the build contextFROM 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:

ImageENTRYPOINTCMDshem run image …
A program (FROM scratch)A program in the image, run on the vCPUIts default argumentsReplace the arguments
A modelA driver: ["shem:generate", "--max-tokens", "128"]The default promptYour prompt

A shem: entrypoint selects a host-side driver, not a guest executable.

shem:generate optionMeaning
--max-tokens NMaximum reply length; default 256
--dtype bfloat16Compute in bfloat16, which halves the memory weights and sessions take and is faster on GPUs; default float32
--adapter PATHMerge a LoRA adapter into the weights as the model loads: see adapters
--quantize int8Hold 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 int4As 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 NDraw tokens, seeded, rather than take the likeliest: see above; defaults greedy, 1, all, random
--system TEXTSystem prompt
--system-file PATHAppend a file from the image to the system prompt
--stop TEXTEnd the reply at this text; useful for base models
--tools DIROffer programs in this directory as tools
--chatRead turns, a line each, as shem run -i does
--keepKeep a Docker session open after replying
--serve [HOST:]PORTServe 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:

FileContents
shem.jsonEmbedding, ordered blocks, head and tokenizer; block types, parameters and tensor names
block-NNN-TYPE.safetensorsOne block’s weights, with original tensor names and dtypes
embed.safetensors, head.safetensorsEmbedding and output weights
model.safetensors.index.jsonTensor-to-file index
Checkpoint metadataConfigs, 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 typeWhat it doesIts state in a session
attentionGrouped-query attention; optional rotary scaling, biases, fused projections, QK norms, sliding windows, softcapping and output gatesGrowing KV cache
gated_deltanetCausal convolution and gated delta-rule matrix memoryFixed-size convolution and memory state
mambaCausal convolution and selective scanFixed-size convolution and scan state
mlpSwiGLU or GeGLU; optional biases and fused projectionsNone
moeRouted gated experts; optional shared expertNone

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

ModelBlocksImageVerified
Qwen/Qwen3-0.6B28 attention, 28 MLP59 layers, 892 MBLogits within 1e-3 of transformers, and the same 24 greedy tokens
Qwen/Qwen3.5-0.8B18 Gated DeltaNet, 6 attention with output gates and partial rotary positions, 24 MLP51 layersThe same, against transformers’ Qwen3.5
HuggingFaceTB/SmolLM2-360M-Instruct32 attention, 32 MLP67 layersThe same, against transformers’ Llama
Qwen/Qwen2.5-0.5B-Instruct24 attention with query, key and value biases, 24 MLP51 layersThe same, against transformers’ Qwen2
google/gemma-3-270m-it18 attention (15 with sliding windows) with norms around them and on queries and keys, 18 GeGLU MLP39 layersThe same, against transformers’ Gemma 3
allenai/OLMo-2-0425-1B-Instruct16 attention with norms after them and on all queries and keys, 16 MLP35 layersThe same, against transformers’ OLMo 2
ibm-granite/granite-3.1-1b-a400m-instruct24 attention, 24 mixtures of 32 stacked experts, 8 per token, with Granite’s multipliers51 layersThe same, against transformers’ GraniteMoe
HuggingFaceTB/SmolVLM-256M-Instruct30 attention, 30 MLP, and the image encoder: 12 SigLIP-style layers and a pixel-shuffle connector60 layers and the encoderThe 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-hf24 attention with query, key and value biases, 24 MLP, and the image encoder: 26 SigLIP layers and a two-layer projector51 layers and the encoderThe same, against transformers’ LLaVA, with an image: the processor’s tokens and pixels, and the logits of the pass
state-spaces/mamba-130m-hf24 Mamba27 layersThe same, against transformers’ Mamba, with a template that runs a base model’s text together
Qwen/Qwen3-0.6B-GGUF :Q8_0As Qwen3-0.6B, dequantized59 layersLogits 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:

ModelBlocksVerified
unsloth/Llama-3.2-1B-Instruct16 attention with Llama 3’s rotary scaling, 16 MLPLogits within 1e-3 of transformers, and the same 24 greedy tokens
mistralai/Mistral-7B-Instruct-v0.332 attention, 32 MLPThe same, against transformers’ Mistral
microsoft/Phi-3.5-mini-instruct32 attention with fused projections and longrope, 32 MLPThe same, against transformers’ Phi-3
google/gemma-3-4b-it34 attention (5 of 6 with sliding windows), 34 GeGLU MLP; the vision encoder left outThe same, against transformers’ Gemma 3 vision-language model
allenai/Olmo-3-7B-Instruct32 attention (24 with sliding windows) with YaRN scaling, 32 MLPThe same, against transformers’ OLMo 3
allenai/OLMoE-1B-7B-0125-Instruct16 attention, 16 mixtures of 64 experts, 8 per tokenThe same, against transformers’ OLMoE
Qwen/Qwen1.5-MoE-A2.7B-Chat24 attention, 24 mixtures of 60 experts, 4 per token, and a gated shared expertThe same, against transformers’ Qwen2-MoE
Qwen/Qwen3-30B-A3B48 attention, 48 mixtures of 128 experts, 8 per tokenThe same, against transformers’ Qwen3-MoE
mistralai/Mixtral-8x7B-Instruct-v0.132 attention, 32 mixtures of 8 experts, 2 per tokenIn 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:

FlagComparisons
SHEM_MODEL_TESTS=1Small checkpoints: float32 logits, greedy tokens, templates and session resumes
SHEM_LARGE_MODEL_TESTS=1Gemma-2-2B, Phi-4-mini, SmolLM3-3B and Granite-3.3-2B in bfloat16
SHEM_HUGE_MODEL_TESTS=1Larger 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:

  1. Pixels. The picture is decoded with Pillow (the images extra of shem-neural, in the shem-neural image), 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.
  2. 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.
  3. 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.

DetailBehavior
Tar layersShared unchanged with the artifact. Use modctl build --raw=false to produce them.
Raw layersmodctl’s default; each file must be wrapped in a new tar blob.
Model pathFiles land at /; dev.shem.model=/. The driver accepts /model or /.
WeightsOriginal checkpoint shards, not re-split by block. Requires safetensors and a supported family.
LabelsModel metadata becomes OCI labels; org.opencontainers.image.base.digest identifies the artifact.
NamespacesReads vnd.cncf.model / org.cncf.model and legacy vnd.cnai.model / org.cnai.model.
Docker buildsThe 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?"
RequestAnswer
GET /v2/ORG/NAME/manifests/TAGThe 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/listlatest, 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, DELETE405: 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.

NameFiles
files/ORG/NAMEAll of the repo’s but .gitattributes
safetensors/ORG/NAMEWithout 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 16G refuses 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 Range requests, 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
CommandWhat it does
docker run IMAGE "prompt"Answer once, then exit
docker run -i IMAGEOne 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 IMAGE2Pause, save tokens and block state into /.shem; IMAGE2 resumes the conversation
docker logs, stop, rm, psStandard 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
EndpointAnswers with
POST /v1/chat/completionsA reply to the messages; with "stream": true, server-sent events as it comes
POST /v1/completionsA continuation of a text, with no chat template: prompt is one text; max_tokens, stop, stream and logprobs apply
POST /v1/embeddingsA 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/modelsThe model, by the repository it came from
GET /health200 once the model is loaded
GET /metricsPrometheus 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; then top_p, top_k and seed apply too, and the same seed draws the same reply. n must be 1. max_tokens and stop apply.
  • 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 429 with Retry-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.
  • tools in a chat request are offered to the model through its chat template, and a reply that calls them comes back as tool_calls with finish_reason tool_calls (in a stream, as a chunk of tool_calls); tool and assistant messages with tool_calls carry the conversation on. The caller runs the tools, as with OpenAI. tool_choice is auto or none: shem does not force a call.
  • A user’s message can hold image_url parts with data: URLs for a model that reads images.
  • logprobs (with top_logprobs in 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_format can be text, {"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 are type (one or a list), enum and const of scalars, properties (only those keys are written, each once), required, items, minItems and maxItems, with additionalProperties only as false; anything else is refused with a 400 rather than quietly ignored. The top level must be an object. Neither can go with shem_receipt, which cannot replay a mask yet.
  • It listens on 127.0.0.1 unless given --host. Set SHEM_API_KEY in the environment, and every request but /health must send Authorization: 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 that ps does not show it.
  • A page in a browser may call the API only from an origin that --cors-origin ORIGIN allows (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 error event before [DONE].
  • An image serves when it starts with ENTRYPOINT ["shem:generate", "--serve", "8000"] and EXPOSE 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:rv32im deterministically compiles CPU weights, machine config and model card. Both builders support it; releases publish the same weights.
  • --tools DIR exposes programs using the chat template’s tool format (JSON or <function=...> tags). A sibling NAME.json defines the description and parameters, mapped to arguments in order; without it, the interface accepts args and stdin. See mul.json.
  • Calls run through shem run --vcpu neural with 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}}
}
  • image is 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 --state adds state, the session’s reference and digest. An OCI layout directory is recorded by its digest alone.
  • tokens are the tokens the model chose, in order: each reply’s and the token that ended it, tool calls included.
  • margins say how firmly: each chosen token’s logit less the runner-up’s. For a run that drew its tokens, a sampling field 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 replay draws again from the seed.
  • runtime is 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.

StatusVerdictMeaning
0verifiedThe model chose the receipt’s tokens again
1mismatchThe 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
3undecidedThe tokens differ at a close call, which another device may make otherwise: replay on the receipt’s device
125The 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 typeLargest logit difference99th percentileLargest move of a marginChoices flippedLargest margin that flipped
L4, float320.000080.000030.000070 of 1,536
A100, float320.000070.000030.000070 of 1,536
CPU, bfloat160.870.371.2533 and 39 of 1,536 (two hosts)0.25
L4, bfloat160.800.320.7227 of 1,5360.25
A100, bfloat161.140.320.7122 of 1,5360.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:

ModelCPU tokens/sL4 tokens/s
Qwen3-0.6B7.127.8
Qwen3.5-0.8B5.631.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.