Skip to content

Exporting weights

The core API is a beta preview and may change between minor versions.

Every model in the zoo loads its weights from one .safetensors file. Your own fine-tune or a quantized copy loads the same way as the hosted file.

float file as isCheckpointPyTorch / HFExport.safetensorsQuantize optionalint8 / int4modelPathcreate<Task>()LoadGPU uploadfloat fileas isCheckpointPyTorch / HFExport.safetensorsQuantize optionalint8 / int4modelPathcreate<Task>()LoadGPU upload

A trained model is a list of named weights. In PyTorch, model.state_dict() gives you that list, and a .safetensors file stores it on disk. For all-MiniLM-L6-v2 it starts like this:

embeddings.word_embeddings.weight [30522, 384]
encoder.layer.0.attention.self.query.weight [384, 384]
encoder.layer.0.attention.self.query.bias [384]
...

ruNNtime builds these names the same way PyTorch does. A model is a tree of modules, like nn.Module: each layer is a field, and a weight’s name is the path of field names from the top, joined with dots. A list of layers adds the index, like layer.0. These two models give the same names:

# PyTorch
class Block(nn.Module):
def __init__(self):
super().__init__()
self.query = nn.Linear(384, 384)
class Encoder(nn.Module):
def __init__(self):
super().__init__()
self.layer = nn.ModuleList([Block() for _ in range(6)])
# layer.0.query.weight, layer.0.query.bias, layer.1.query.weight, ...
// ruNNtime
import {
(alias) namespace nn
import nn
nn
} from 'runntime/core';
class
class Block
Block
extends
(alias) namespace nn
import nn
nn
.
class index_d_exports.Module<In extends unknown[] = [Value], Out = Value>
export index_d_exports.Module
Module
{
Block.query: nn.Linear
query
= new
(alias) namespace nn
import nn
nn
.
new index_d_exports.Linear(inFeatures: number, outFeatures: number, opts?: {
bias?: boolean;
activation?: SlotAct;
}): nn.Linear
export index_d_exports.Linear
Linear
(384, 384);
}
class
class Encoder
Encoder
extends
(alias) namespace nn
import nn
nn
.
class index_d_exports.Module<In extends unknown[] = [Value], Out = Value>
export index_d_exports.Module
Module
{
Encoder.layer: nn.ModuleList<Block>
layer
= new
(alias) namespace nn
import nn
nn
.
new index_d_exports.ModuleList<Block>(items: readonly Block[]): nn.ModuleList<Block>
export index_d_exports.ModuleList
ModuleList
(
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<unknown, Block>(iterable: Iterable<unknown> | ArrayLike<unknown>, mapfn: (v: unknown, k: number) => Block, thisArg?: any): Block[] (+3 overloads)
from
({
ArrayLike<T>.length: number
length
: 6 }, () => new
constructor Block<[Value], Value>(): Block
Block
()));
}
// layer.0.query.weight, layer.0.query.bias, layer.1.query.weight, ...

When ruNNtime loads a file, it looks up each of its weights by that name and uploads it to the GPU. So a file saved straight from the PyTorch model works: no renaming, no reshaping, no conversion script.

Weights can be stored as F32, F16 or BF16. F16 is half the download of F32 and doesn’t change how the model computes.

If a weight is missing or has the wrong shape, loading stops with a CHECKPOINT_MISMATCH error that names it (see Error handling).

A tensor in the file that the model doesn’t read, like the pooler in a plain Hugging Face checkpoint, is skipped with a console warning. Pass { strict: true } to loadStateDict to make it the same error.

Pick the case that fits:

  • The model is on Hugging Face and has one model.safetensors. Download that file and load it. If a name doesn’t match, the error says which one.

  • You fine-tuned it with transformers, or want a smaller F16 copy. Save it with save_pretrained, as one file:

    Terminal window
    uv run --with transformers --with torch python -c "
    from transformers import AutoModel
    import torch
    model = AutoModel.from_pretrained('path/to/your-model', dtype=torch.float16)
    model.save_pretrained('export', max_shard_size='100GB') # one file, not shards
    "
  • You trained it with your own PyTorch code. Save the state dict: safetensors.torch.save_file(model.state_dict(), 'model.safetensors').

Write the model in ruNNtime so it gives the same names, like the Encoder above:

  • Name each field after the PyTorch attribute: self.query = nn.Linear(...) becomes query = new nn.Linear(...).
  • Use nn.ModuleList where PyTorch does. It adds the index to the name.
  • Give each layer the same sizes.

Layers that read the same input, like an attention block’s query, key and value, can run as one matmul. Keep them as fields, so the names still match, and add an nn.FusedLinear over them:

class
class Block
Block
extends
(alias) namespace nn
import nn
nn
.
class index_d_exports.Module<In extends unknown[] = [Value], Out = Value>
export index_d_exports.Module
Module
{
Block.query: nn.Linear
query
= new
(alias) namespace nn
import nn
nn
.
new index_d_exports.Linear(inFeatures: number, outFeatures: number, opts?: {
bias?: boolean;
activation?: SlotAct;
}): nn.Linear
export index_d_exports.Linear
Linear
(384, 384);
Block.key: nn.Linear
key
= new
(alias) namespace nn
import nn
nn
.
new index_d_exports.Linear(inFeatures: number, outFeatures: number, opts?: {
bias?: boolean;
activation?: SlotAct;
}): nn.Linear
export index_d_exports.Linear
Linear
(384, 384);
Block.value: nn.Linear
value
= new
(alias) namespace nn
import nn
nn
.
new index_d_exports.Linear(inFeatures: number, outFeatures: number, opts?: {
bias?: boolean;
activation?: SlotAct;
}): nn.Linear
export index_d_exports.Linear
Linear
(384, 384);
Block.qkv: nn.FusedLinear
qkv
= new
(alias) namespace nn
import nn
nn
.
new index_d_exports.FusedLinear(parts: readonly nn.Linear[]): nn.FusedLinear
export index_d_exports.FusedLinear
FusedLinear
([this.
Block.query: nn.Linear
query
, this.
Block.key: nn.Linear
key
, this.
Block.value: nn.Linear
value
]);
}
// block.qkv.forward(x): query, key and value of x side by side, [rows, 1152]

The file doesn’t change. Call qkv.forward(x) instead of the three layers: a layer inside a FusedLinear can’t run on its own.

Then load the file:

const
const model: Encoder
model
= new
constructor Encoder<[Value], Value>(): Encoder
Encoder
();
await
const model: Encoder
model
.
Module<[Value], Value>.loadStateDict(sd: LazyStateDict | string | MemoryStateDict, opts?: nn.LoadStateDictOpts): Promise<void>
loadStateDict
('/models/model.safetensors');

Full / half-precision files work as is. Optionally, you can quantize your model which can reduce the download size, memory usage, and can make the inference faster.

__metadata__ runntime.quant ={"version":1,"scheme":"symmetric"}…query.weightI8 [384, 384]int8 weight…query.weight_scaleF16 [384, 12]its scales…query.biasF16 [384]float…LayerNorm.weightF16 [384]float

How the runtime recognizes it. A quantized file has a runntime.quant entry in its header metadata. Each quantized weight is stored as I8 (int8) or U8 (two int4 values per byte), with its scales next to it under the same name plus _scale. Each weight takes its bits from its dtype and its group size from the shape of its scales. Every other tensor is a normal float tensor. An int tensor in a file without runntime.quant fails to load.

What is in the file. runntime quantize quantizes every float tensor named *.weight that has 2 or more dims: Linear and conv weights. Biases and norms stay float. By default it also skips every tensor whose name matches *embed*, *pos_emb* or lm_head.*. It stores each quantized tensor as rows, [first dim, everything else], so a Conv1d weight [out, in, k] becomes [out, in·k], and groups of --group-size values run along that row. The group size has to divide the row: in for a Linear, in·k for a conv. A tensor it doesn’t divide stays float. The runtime loads each tensor back into its layer’s shape.

Which layers run quantized. Linear, Conv1d and ConvTranspose1d run on the int weights. Any other quantized tensor, like a Conv2d weight, a depthwise Conv1d weight or an embedding table you chose to quantize, is turned back into floats at load. It keeps the rounding of its ints, so the download is smaller but the model is no faster and uses no less memory than the float one.

A Linear or conv weight whose shape the quantized kernels can’t take also loads as float, and a console warning names it. To stay on the quantized kernels, keep --group-size a multiple of 4.

The layers of a FusedLinear run quantized together or not at all. If only some of them are quantized, or they differ in bits or group size, the whole fused layer loads as float, with the same warning.

Making a file. runntime quantize lives in the repository under tools/python and runs with uv:

Terminal window
git clone https://github.com/software-mansion/runntime
cd runntime/tools/python
uv run --no-dev runntime quantize model.safetensors model.int8.safetensors --bits 8 --f16
  • --bits 8 or --bits 4. Required.
  • --f16 stores the tensors that stay float as F16. Without it they stay as they are in the source: a default int8 file of all-MiniLM-L6-v2 made from the F32 checkpoint is 59 MB, more than the 45 MB F16 file. With --f16 it is 35 MB.
  • --group-size N: how many values of a row share one scale. Default 32.
  • --include GLOB: which tensors to quantize. Default *.weight.
  • --exclude GLOB: tensors to keep float, like a layer that loses too much. Replaces the default *embed*, *pos_emb* and lm_head.*. --exclude none skips nothing.
  • --drop GLOB: tensors to leave out of the file, like a pooler the model never reads.

The tool prints one line per tensor with its error against the float weights, or why it was skipped.

Embedding tables. The default skips are by name, so they keep the embedding tables float, and any other layer with such a name, like an embedding_projection. To quantize them too, add --exclude none:

Terminal window
uv run --no-dev runntime quantize model.safetensors model.int8.safetensors --bits 8 --f16 --exclude none

Whether your model tolerates that is yours to check: compare its outputs with the float model’s before you ship the file.

Picking a setting. We ran the command above on all-MiniLM-L6-v2 and searched 20 documents with 20 queries. With int8 every embedding stays at cosine similarity 0.9998 or higher against the float model, and the top 3 results come back in another order for 2 of the 20 queries. With --bits 4 the cosine drops to 0.94 and the top 3 change for 12 queries. The first result is the same for all 20 in both. Use int8. Try int4 only when the download size matters more, and check it on your own data.

Use int8 for models built on 2D convolutions. int4 breaks the outputs of MobileNetV4, DepthART and YOLO26.

A quantization-aware trained checkpoint quantizes the same way if it was trained on symmetric int8 or int4 with one scale per group of inputs.