Adapters #
Firecrest applies low-rank adapters at run time, beside the quantized base
weights, which stay untouched. A request names the adapters it wants and a
scale for each; policy scripts may choose them; the resolved set is part of
the session's cache lineage. The crate firecrest-adapters owns the file
formats, the mapping to weight sites, the reference math and the prepared
buffers the engine uploads. This page describes all of them and ends with a
worked example that imports a set of steering vectors and applies it.
Terms #
An adapter is a list of terms. Each term sits at one site, a base linear
map y₀ = W x with W of shape [out, in], and has a rank r:
| kind | contribution | A |
B |
|---|---|---|---|
| input-side (LoRA) | Δy = s · B (A x) |
[r, in] |
[out, r] |
| output-side (projection) | Δy = s · B (A y₀) |
[r, out] |
[out, r] |
Both matrices are stored row-major in f32. The output-side form is written
s·B(Aᵀy₀) in the architecture document when A is viewed as an [out, r]
matrix of columns; the rows of the stored A are those columns. Removing
the component along a unit direction q, y ← y − s·q qᵀy, is the
output-side term with A = q (one row) and B = −q.
Composition. All terms at a site, from every active adapter, read the
same input x and the same base output y₀:
y = y₀ + Σ_terms Δy
No term sees another term's output. The result is therefore independent of
the order of adapters and terms, up to float summation order, which the
prepared form fixes (see Fingerprints). ds4 composes its steering banks
the same way. With orthonormal directions, two rank-1 removals composed this
way equal the rank-2 removal −s·QQᵀy; applying them one after the other
would not, for directions that are not orthogonal.
Grouped maps. DeepSeek V4.1's attn_output_a (wo_a) is one
[8192, 4096] weight applied in 8 groups: output rows [1024g, 1024(g+1))
read heads 8g..8g+7 (input slice [4096g, 4096(g+1))), see
spec 01 section 1.8.
An input-side term there uses one A
for all groups, exactly like the weight: Δy_g = s·B_g (A x_g) with B_g
the group's rows of B. That is the result of merging the LoRA delta
ΔW = s·BA into wo_a. An output-side term reads the whole 8192-wide
output as usual.
Scales #
Three scalars meet in a term's contribution:
- the term's static scale, fixed by the file: PEFT
lora_alpha / r(lora_alpha / √rwith rsLoRA), llama.cppalpha / r(1 when alpha is 0), a DS4STV1 bank's site weight; - the request scale, per adapter per request (
AdapterUse::scale); - nothing else: the effective factor is
static × request.
Preparation folds the static scale into B. The request scale stays a
separate scalar, so one uploaded copy serves every request scale. Request
and default scales must be finite with |s| ≤ 100. A scale of 0 removes the
adapter from the set.
Each loaded adapter has a default scale. The model's default set is
every loaded adapter whose default scale is nonzero; it applies when a
request (or the policy decision) does not name adapters
(PolicyDecision::adapters = None). An explicit empty list turns all
adapters off, as does "steering": [] or "adapters": null.
Sites of DeepSeek V4.1 Flash #
Site names are blk.<layer>.<kind>, blk.<layer>.<kind>.<expert> for
routed experts and <kind> for global sites (lm_head). Dimensions follow
nn.Linear (in → out); GGUF lists the same tensor as [in, out]. The
checkpoint module is the tensor name in the release checkpoint's
safetensors index, which PEFT keys use after base_model.model. (an extra
model. prefix is accepted).
| kind | GGUF tensor (blk.L.) |
checkpoint module (layers.L.) |
in | out | layers |
|---|---|---|---|---|---|
attn_q_a |
attn_q_a.weight |
attn.wq_a |
5120 | 1280 | 0-39 |
attn_q_b |
attn_q_b.weight |
attn.wq_b |
1280 | 32768 | 0-39 |
attn_kv |
attn_kv.weight |
attn.wkv |
5120 | 512 | 0-39 |
attn_output_a |
attn_output_a.weight |
attn.wo_a |
4096 ×8 groups | 8192 | 0-39 |
attn_output_b |
attn_output_b.weight |
attn.wo_b |
8192 | 5120 | 0-39 |
compressor_kv |
attn_compressor_kv.weight |
attn.compressor.wkv |
5120 | 512 | 2, 8, 14, 20 |
compressor_gate |
attn_compressor_gate.weight |
attn.compressor.wgate |
5120 | 512 | 2, 8, 14 |
indexer_k |
indexer.attn_k.weight |
attn.indexer.wk |
512 | 128 | 2, 8, 14, 20 |
indexer_q_b |
indexer.attn_q_b.weight |
attn.indexer.wq_b |
1280 | 4096 | 2, 8, 14, 20, 24, 28, 32, 36 |
indexer_proj |
indexer.proj.weight |
attn.indexer.weights_proj |
5120 | 32 | same as indexer_q_b |
ffn_router |
ffn_gate_inp.weight |
ffn.gate |
5120 | 384 | 0-39 |
shexp_gate |
ffn_gate_shexp.weight |
ffn.shared_experts.w1 |
5120 | 2304 | 0-39 |
shexp_up |
ffn_up_shexp.weight |
ffn.shared_experts.w3 |
5120 | 2304 | 0-39 |
shexp_down |
ffn_down_shexp.weight |
ffn.shared_experts.w2 |
2304 | 5120 | 0-39 |
expert_gate |
ffn_gate_exps.weight (expert = dim 2) |
ffn.experts.E.w1 |
5120 | 2304 | 0-39, 384 experts |
expert_up |
ffn_up_exps.weight |
ffn.experts.E.w3 |
5120 | 2304 | 0-39, 384 experts |
expert_down |
ffn_down_exps.weight |
ffn.experts.E.w2 |
2304 | 5120 | 0-39, 384 experts |
engram_kv |
engram_kv.weight |
engram.wkv |
6144 | 25600 | 1, 14 |
lm_head |
output.weight (global) |
head (global) |
5120 | 129280 | - |
That is 46,470 sites (46,080 of them routed experts). A unit test checks
every row against engines/deepseek-v4.1/docs/spec/gguf-main-dump.txt. Not sites: the token
embedding (a lookup), the hyper-connection mixers hc_* and norms, the
Engram tables, and the MTP and vision towers.
The vocabulary is model-agnostic: a model describes its kinds, dims,
layers, expert counts and name patterns in a SiteCatalog;
dsv41::Dsv41Dims builds this one from the constants or from the model's
text_config.
Formats #
Native (*.safetensors) #
The only format the server loads; every importer converts into it. One
safetensors file whose __metadata__ holds format = "firecrest-adapter",
version = "1" and adapter, a JSON document:
{"meta": {"name": "steer-v1",
"base": {"model": "deepseek41", "catalog_fingerprint": "d11696a6…"},
"default_scale": 1.0,
"provenance": {"format": "ds4sv", "sources": [{"name": "…", "bytes": 819264, "blake3": "…"}],
"converter": "firecrest-adapters 0.1.0", "params": {}}},
"terms": [{"site": "blk.0.attn_output_b", "kind": "output", "rank": 2, "scale": 1.0}]}
Each term has the tensors <site>.<kind>.a ([rank, a_dim]) and
<site>.<kind>.b ([out, rank]) in F32, or F16/BF16 when written so. A
file whose catalog_fingerprint differs from the model's is refused.
base.weights (optional) names the exact base weights for adapters whose
values depend on them (the input-side form of an output-side edit).
PEFT LoRA #
A directory with adapter_config.json and adapter_model.safetensors
(safetensors read by the crate's own reader; adapter_model.bin pickles are
refused). Keys base_model.model.<module>.lora_A[.<name>].weight ([r, in])
and …lora_B… ([out, r]). Supported config fields: r, lora_alpha,
use_rslora, rank_pattern and alpha_pattern (PEFT's rule: the first key
k in file order whose regex (.*\.)?k matches the whole module name),
target_modules (recorded only, the keys decide). The rank in the tensors
must equal the configured rank for the module. Rejected with a message:
use_dora or lora_magnitude_vector (DoRA rescales whole weight columns,
not a low-rank side term), lora_bias or lora_B.bias,
target_parameters, other peft_types, and full module weights saved by
modules_to_save. Embedding LoRAs (lora_embedding_A/B) have no site and
count as unmapped.
Routed experts. The release checkpoint stores each routed expert as its
own module, layers.L.ffn.experts.E.w{1,2,3}, not as one stacked 3-D
parameter, so PEFT LoRA on experts is per-expert and maps directly to
blk.L.expert_*.E. Adapters trained against a reimplementation that stacks
experts into one parameter (PEFT target_parameters such as
experts.gate_up_proj) are rejected; their layout (fused gate/up order,
expert-major rank blocks) is not defined by this checkpoint. No Hugging Face
transformers modeling file for DeepseekV41ForCausalLM was available to
check other naming schemes (UNVERIFIED).
peft::export writes input-side terms back as a PEFT directory (F32,
rank_pattern/alpha_pattern per module so every scale is 1, static scales
folded into B).
llama.cpp GGUF adapters #
general.type = "adapter", adapter.type = "lora", general.architecture
equal to the model's (deepseek41), optional adapter.lora.alpha, and for
each adapted tensor <name> the pair <name>.lora_a (GGUF dims [in, r])
and <name>.lora_b ([r, out]). Stacked expert tensors add the expert as
the third dimension. Scale as llama.cpp: alpha / r, or 1 when alpha is 0.
Tensor types F32, F16, BF16 and Q8_0 (decoded by firecrest-quant); the file
is read through firecrest-gguf. Expert matrices that are all zero are
dropped. gguf::export writes input-side terms (F32, alpha 0, stacked
experts zero-padded).
DS4STV1 steering banks (*.ds4sv) #
ds4's steering-vector format
(spec 02
section 9.1): a 64-byte header (magic DS4STV1\0, layers, width,
operation, flags, layer mask, three site weights) and layers × width f32
rows, validated with ds4's rules. A
project bank with site weight w contributes, at each masked layer l with
stored row d, the output-side rank-1 term A = d, B = −d, scale w;
the attention weight maps to attn_output_b, the shared-expert weight to
shexp_down. All banks given to one import become one adapter, the banks of
one site and layer concatenated into one term. Add banks (a constant offset)
and residual-site weights (the mean of the four hyper-connection streams,
not a weight site) are rejected.
Validation #
Every import checks dims against the site catalog, finite values, the rank
limit (512 by default, per term after merging), name rules (1-64 of
[A-Za-z0-9._-]), and lists modules or tensors that map to no site. Unmapped
modules are an error unless ImportOptions::allow_unmapped is set, in which
case they are skipped and reported. Terms that are exactly zero are dropped.
Projection edits as adapters #
A weight edit of the form W' = W − s_l·QQᵀW, with Q a few
orthonormal directions of the site's output width and s_l a scale per
layer and site, needs no modified weights: it is an adapter.
Equivalences. For every input x,
W'x = Wx − s_l·Q(Qᵀ(Wx)) = y₀ + (−Q)(Qᵀy₀)·s_l, which is
- the output-side term
A = Qᵀ,B = −Q, scales_l, applied at every position (term::projection_edit_output), and equally - the input-side LoRA
B = −s_l·Q,A = QᵀW(term::projection_edit_input, orterm::output_to_inputfor any output-side term; it needs the dequantized base rows through theBaseWeighttrait, andgguf::GgufBaseWeightsupplies them from a model GGUF).
tests/math.rs checks both against an explicit W' in f64. For a rank-2
edit on the Q8_0 weights of layers 0 and 31 (attn_output_b) and 25
(shexp_down) of the model, the two forms agreed to 1.2e-7 while the edit moved outputs by up to
0.06. The input-side form is exact only for the base the engine actually
multiplies by; the Q8_0 kernels also quantize activations to int8 (spec 01
section 1.10), so in the engine the output-side form is the one that follows
the edit exactly.
Differences from ds4's steering. ds4 applies its steering banks only to
generated tokens and the last prompt token, and leaves prefill unsteered
(spec 02 section 9.4). A Firecrest adapter applies at every position, which
is what a weight edit does. ds4 also has separate reasoning and
answer strengths; a Firecrest request has one scale per adapter, and the
server refuses a steering entry whose reasoning_strength and
answer_strength differ. On the shared-expert site the engine does what ds4
does: it rounds the output to BF16, applies the terms to that rounded output
and rounds again (see Where terms enter).
Fingerprints and lineage #
- Catalog fingerprint: blake3 of the catalog structure (model id, kinds, dims, groups, layers, experts). Recorded in every adapter; loading checks it.
- Content fingerprint (
PreparedAdapter::fingerprint): blake3 of the catalog fingerprint and, per prepared term in (site, kind) order, the site name, kind, rank and the f32 bytes ofAand the scale-foldedB. It does not depend on the name, default scale or provenance. - Active-set fingerprint (
ActiveSet::fingerprint): blake3 of the catalog fingerprint and, for each active adapter sorted by content fingerprint, its content fingerprint and request scale. All zeros for the empty set. Two requests with the same adapters and scales get the same fingerprint whatever names and order they used; replacing an adapter's file under the same name changes it. Sessions must record this fingerprint:firecrest_core::AdapterSet::fingerprinthashes names only and would let a session computed with an old file be reused after the file is replaced.
The canonical adapter order (by content fingerprint) is also the term order at every site, so the float summation order of a set is fixed.
Engine contract #
AdapterRegistry (one per loaded model) holds PreparedAdapters. Its
generation counts content changes (load, replace, unload); the engine
re-uploads when it differs from the generation it uploaded. Default-scale
changes do not bump it. resolve(&AdapterSet) and resolve_or_default
return an ActiveSet holding Arcs, so an adapter unloaded during a
request stays alive until the request ends.
Buffers. Per prepared term: a [rank, a_dim] and b [out, rank]
f32, row-major, static scale folded into b (a_dim = in per group for
input-side, out for output-side); optional f16 copies (a_f16, b_f16).
Terms are sorted by (site, kind); terms_at(site) and layer_terms(layer)
are contiguous slices. Routed-expert terms are also available per
(layer, site kind, term kind) as an ExpertPack: slot[expert] (−1 when
the expert has no term), a [slots, rank, a_dim], b
[slots, out, rank], ranks zero-padded to the pack's maximum.
Where terms enter. At a site with active terms, for each token:
y₀is the site's base matmul output in f32, before any rounding that follows the site (for exampleattn_output_bbeforebf16(block),shexp_downafter its firstbf16(the engine and the reference round the shared expert's output, apply the terms and round again, as ds4 does;firecrest-dsv41-gpuphases::ffn::FfnKernels::post),attn_q_abefore itsbf16andq_a_norm, routed experts before the routing weight and the 1.5 factor,lm_head= the logits).- Input-side terms read
x, the activation the base matmul consumes, before the kernel's own activation quantization (forattn_output_a, the FP8-rounded head outputs grouped by 8 heads). For each termt = A x([rank], one per group on grouped sites). - Output-side terms read
y₀:t = A y₀. y = y₀ + Σ_terms scale_req · B t, then the site's usual rounding.
The reference implementation is reference::apply (f64 accumulation,
one rounding to f32) and ActiveSet::apply_reference.
Sites the engine hooks. The DeepSeek V4.1 engine applies terms at two
sites, attn_output_b and shexp_down, in both the CPU reference backend
and the GPU backend, and refuses a set with a term at any other site. The
GPU backend takes up to 8 adapters in one set, at most 8 terms per site and
a summed rank of at most 256 per site. It uploads a set's terms to every
rank once per active-set fingerprint. An input-side term's T = A x is
formed by the rank that owns that part of the site's input and travels to
the peer with the part's dense partial; an output-side term's T = A y₀ is
formed on every rank from the combined base output. The combine adds
Σ s·B·T in float-float and rounds once (twice at shexp_down, as the
reference does). A decode step batches only sessions with the same adapter
set.
Worked example: a steering-vector adapter #
The example turns a set of ds4 steering-vector banks into a Firecrest
adapter named steer-v1, loads it with the model, and applies it per
request or by default. The banks are *.ds4sv files of project operation
with directions for the attention and shared-expert sites; the names below
are placeholders.
1. Import. All banks given to one import become one output-side
adapter:
cargo run --release -p firecrest-adapters --example firecrest-adapter -- \
import -o steer-v1.safetensors --name steer-v1 --default-scale 0 \
BANKS/attention.ds4sv BANKS/shared.ds4sv
cargo run --release -p firecrest-adapters --example firecrest-adapter -- \
info steer-v1.safetensors
info prints the metadata, the content fingerprint, the number of sites and
terms, the largest rank and, per site kind, the layers it covers. A default
scale of 0 loads the adapter without putting it in the model's default set,
so it applies only when a request or a policy names it. Without
--default-scale the stored default is 1 and every request that names no
adapters gets it.
2. Load it with the model. In the model block of the configuration, a
relative path resolves against dir:
[model.options.adapters]
dir = "/var/lib/firecrest/adapters"
preload = [{ path = "steer-v1.safetensors", name = "steer-v1", default_scale = 0.0 }]
Every *.safetensors in dir is loaded at start under its stored name and
default scale; preload entries load after the scan and replace an adapter
of the same name. A running server also loads one through the management
API, until the next restart:
curl -s -X POST 127.0.0.1:7081/api/models/deepseek-v4.1-flash/adapters \
-d '{"name": "steer-v1", "path": "/var/lib/firecrest/adapters/steer-v1.safetensors", "default_scale": 0}'
curl -s 127.0.0.1:7081/api/models/deepseek-v4.1-flash/adapters | jq
3. Select it per request. A generation request names the adapter and a
scale in adapters:
{"model": "deepseek-v4.1-flash",
"messages": [{"role": "user", "content": "Describe the harbour at dawn."}],
"adapters": [{"name": "steer-v1", "scale": 1.0}]}
The ds4 form "steering": [{"id": "steer-v1", "strength": 1.0}] selects
the same adapter at the same scale (up to 8 entries, strengths within
±100). The response's request-log row lists the adapters it ran with.
4. Apply it by default through a policy. The example policy
crates/firecrest-policy/examples/policies/10-default-adapter.py, copied
into the [policy] dir, adds steer-v1 at scale 1 to every request and
tags it steering: steer-v1. A client opts out with "steering": []: the
script removes the field, clears the adapters and tags steering: off.
Policies describes the script and the 20-adapters-by-alias.py
example, which maps model aliases such as deepseek-steered and
deepseek-mild to steer-v1 at scales 1 and 0.5.
Without a policy, setting the adapter's default scale to 1 (in preload,
or live with PATCH /api/models/ID/adapters/steer-v1 and
{"default_scale": 1}) makes it the default as well; a request then turns
it off with "steering": [], "adapters": [] or "adapters": null.
Each scale gives its own active-set fingerprint, so sessions computed with the adapter, without it, or at another scale never share cached context.
Tool #
firecrest-adapter is an example program of firecrest-adapters:
cargo run --release -p firecrest-adapters --example firecrest-adapter -- COMMAND ...
firecrest-adapter import -o OUT.safetensors [--name N] [--default-scale S] [--max-rank R] [--allow-unmapped] [--f16] INPUT...
firecrest-adapter info FILE.safetensors
firecrest-adapter export-peft FILE.safetensors DIR
firecrest-adapter export-gguf FILE.safetensors OUT.gguf
firecrest-adapter to-input FILE.safetensors MODEL.gguf -o OUT.safetensors [--name N]
INPUT is a PEFT directory, a llama.cpp GGUF adapter, one or more .ds4sv
banks, or a native file. The name defaults to the output file's stem and
the default scale to 1. to-input rewrites output-side terms as input-side
terms on the model's dequantized base weights; it maps the model GGUF and
reads only the affected tensors.
Tests #
cargo test -p firecrest-adapters needs no model files; one test also
compares the site catalog with the release checkpoint's config.json when
FIRECREST_CHECKPOINT names the checkpoint directory. Engine and GPU
tests that compare outputs with an adapter applied read a native adapter
file from FIRECREST_ADAPTER and skip when it is unset or absent.
Limits #
- Output-side terms cannot be exported to PEFT or GGUF; convert them with
to-inputfirst (ungrouped sites only). - An output-side term on a grouped map has no input-side form with one
shared
A. - Rank limit 512 per term by default; scales within ±100.
- Adapters are read whole into memory (adapters touching every routed expert at high rank can reach gigabytes).
- DoRA, LoRA biases, embedding LoRA, additive steering, residual-site
steering and stacked-parameter (
target_parameters) adapters are not supported. - The DeepSeek V4.1 engine applies terms only at
attn_output_bandshexp_down(see Sites the engine hooks); the GPU backend takes at most 8 adapters per set, 8 terms and a summed rank of 256 per site.