# Knowledge Distillation

Source: https://docs.surogate.ai/engine/guides/distillation/

Knowledge distillation trains a small *student* model to imitate a larger *teacher*. Surogate does offline top-K logit distillation on the [SFT](/engine/reference/cli/#sft) path. The teacher runs once over your tokenized training data and its top-K next-token log-probabilities are stored on disk. The student then trains on a combined cross-entropy + KL loss that pulls its output distribution towards the teacher's.

The teacher runs offline, once, before training, so the training loop pays no teacher-inference cost. The native DataLoader streams the teacher signal from disk alongside the token shards.

**Hard requirement: the teacher and student must share a tokenizer.** The sidecar stores teacher-vocab token ids against the student's token stream. Distilling within a model family (such as Qwen3-1.7B → Qwen3-0.6B) meets this. For a teacher with a different tokenizer, see [Cross-tokenizer distillation](#cross-tokenizer-distillation): a vocabulary transplant turns it into a same-tokenizer setup.

## When to use it

- To compress a model: move a large model's behavior into a smaller, cheaper one from the same family.
- For better soft targets: the teacher's full next-token distribution carries more signal per token than the one-hot label, which usually improves a small model's quality on the same data.
- For pure distillation on unlabeled text: with `kd_weight: 1.0` and `ce_weight: 0.0`, the labels only select which positions are trained, and all of the training signal comes from the teacher.

## Two-step workflow

Both steps read the same config file, one with a `distillation:` block (see [Knowledge distillation](/engine/reference/config/#knowledge-distillation) in the config reference):

```bash
# Step 1: run the teacher over the tokenized shards, write .kd sidecars
surogate distill-capture config.yaml

# Step 2: train the student against the sidecars
surogate sft config.yaml
```

[`distill-capture`](/engine/reference/cli/#distill-capture) first tokenizes the datasets if the shards are missing or stale (the same hash-cached flow `surogate sft` uses). It then writes one `train-NNN.bin.kd` sidecar next to each `{output_dir}/train-NNN.bin` token shard. It skips shards that already have a valid sidecar, so you can re-run an interrupted capture.

### Capture CLI flags

```bash
surogate distill-capture config.yaml [--api-base URL] [--device cuda:0] [--hub_token TOKEN]
```

| Flag | Default | Description |
|------|---------|-------------|
| `--api-base` | none | OpenAI-compatible base URL of a served teacher (e.g. `http://localhost:8000/v1`); overrides `distillation.teacher_api_base` and switches capture to the API backend (below). |
| `--device` | `cuda:0` | Device to run the local teacher model on (e.g. `cuda:1`). Ignored with a warning in API mode. |
| `--hub_token` | none | Hugging Face token for private model access |

By default the teacher loads locally with `transformers`, in bf16, with `sdpa` attention. Packed documents are kept apart by transformers' own packed-sequence support: it reads the shard's per-document `position_ids` resets and builds a block-diagonal causal mask, so a token can only attend within its own document. You don't need flash-attn.

This depends on capture passing `use_cache=False`, and the transformers source makes it easy to misread why. The model's `forward` declares `use_cache: bool | None = None` and allocates a cache only under `if use_cache and past_key_values is None`, so leaving the argument out looks safe. It isn't. A `@merge_with_config_defaults` decorator substitutes `config.use_cache` (normally `True`) before the body runs. A cache is allocated, packed detection is skipped, and the teacher silently attends across document boundaries. In our measurement, leaving the argument out diverged from per-document gold by 0.535, the same as passing `use_cache=True`.

We measured this path against a per-document reference (each document run alone, which is what capture should reproduce), scored on the top-64 id set the sidecar stores, at `sequence_len` 2048 with `teacher_batch_size` 4 on one L4. It reaches **98.46%** overlap against flash-attention varlen's **98.32%**, a tie within bf16 kernel noise. Attention with *no* isolation reaches only **42.67%**. The cost is about +18% capture time compared with flash-attn, and +0.4% peak memory at that
`sequence_len`. The memory figure depends on scale: this path builds a
dense `[batch, 1, S, S]` mask where flash-attn's varlen kernel built none, so it
grows with the square of `sequence_len`. The mask is a bool `(batch, 1, S, S)` tensor
(1 byte per element), so with `teacher_batch_size` 4 it is roughly 17 MB at 2048,
268 MB at 8192 and 1073 MB at 16384. If that becomes a limit, `attn_implementation="flex_attention"`
expresses the same mask sparsely and also needs no flash-attn.

### Remote teacher (vLLM API)

Set `distillation.teacher_api_base` (or pass `--api-base`) to capture from an OpenAI-compatible vLLM server instead of loading the teacher locally. This helps when the teacher does not fit next to your capture GPU. In this mode `distillation.teacher_model` is the served model name.

```bash
# serve the teacher (must expose at least top_k prompt logprobs)
vllm serve Qwen/Qwen3-32B --max-logprobs 64

# capture against it
surogate distill-capture config.yaml --api-base http://localhost:8000/v1
```

Capture sends token-id prompts through vLLM's `prompt_logprobs` completions extension, one request per packed document (split at the shard's position-id resets, with a one-token lookahead). Each request holds one document, so context isolation is exact and there is nothing to mask. Up to `teacher_api_concurrency` requests are in flight at once (default 8), each with a `teacher_api_timeout` of 1200 s. Transient failures (transport errors, HTTP 429/5xx) are retried 3 times with backoff. The API key comes from the environment variable named by `teacher_api_key_var` (default `VLLM_API_KEY`). If it is unset, capture sends `EMPTY`, which local unauthenticated vLLM servers accept.

Two hard requirements:

- The server must be started with `--max-logprobs >= distillation.top_k`, or capture aborts with: `The server at <url> returned only <N> prompt_logprobs candidates but distillation.top_k=<K>; restart the vLLM server with --max-logprobs >= <K>.`
- It must be a vLLM-compatible server. OpenAI-compatible aggregators and providers (such as OpenRouter) do not expose per-position prompt logprobs or token-id prompts, and capture fails with: `The server at <url> did not return prompt_logprobs. distill-capture requires a vLLM-compatible inference server started with --max-logprobs >= <K>, serving a teacher that SHARES the student's tokenizer.`

## Configuration reference

```yaml
model: Qwen/Qwen3-0.6B          # the student

distillation:
  teacher_model: Qwen/Qwen3-1.7B
  top_k: 64
  temperature: 1.0
  kd_weight: 0.5
```

The `distillation:` block:

| Option | Type | Default | Used by | Description |
|--------|------|---------|---------|-------------|
| `teacher_model` | str | `null` | capture | Teacher model id or path. Required by `distill-capture`; ignored at train time. |
| `top_k` | int | `32` | both | Number of teacher logprobs stored per token. Must be in `[1, 1024]` and not exceed the teacher vocab size. Training validates that the sidecars were captured with exactly this value. |
| `temperature` | float | `1.0` | train | Distillation temperature τ. Must be > 0. |
| `kd_weight` | float | `0.5` | train | Weight of the KD (KL) term. Must be ≥ 0. |
| `ce_weight` | float | `1 - kd_weight` | train | Weight of the CE term. Must be ≥ 0. When `kd_weight > 1` the default would be negative, so `ce_weight` must then be set explicitly. |
| `teacher_batch_size` | int | `4` | capture | Local backend only: windows of `sequence_len` tokens per teacher forward pass during capture. Must be ≥ 1. Raise it until the teacher fills its GPU. |
| `kd_dir` | str | `null` | both | Sidecar directory override (default: alongside the token shards). The trainer validates the sidecars there and bridges them to the native DataLoader with `<shard>.kd` symlinks automatically. |
| `teacher_api_base` | str | `null` | capture | OpenAI-compatible base URL of a served teacher (e.g. `http://localhost:8000/v1`). When set, capture queries the API instead of loading `teacher_model` locally — see [Remote teacher](#remote-teacher-vllm-api). |
| `teacher_api_key_var` | str | `"VLLM_API_KEY"` | capture | Name of the environment variable holding the API key. Empty/unset resolves to `EMPTY` (accepted by local vLLM servers). |
| `teacher_api_concurrency` | int | `8` | capture | Concurrent in-flight capture requests in API mode. Must be ≥ 1. |
| `teacher_api_timeout` | int | `1200` | capture | Per-request timeout in seconds in API mode. Must be ≥ 1. |

Turning on distillation also changes two top-level settings for you (logged at startup):

- `use_cuda_graphs` is forced to `false`, because KD micro-steps run eagerly in v1.
- `lmhead_drop_ignored_rows` is forced to `false`, because the compact LM-head row path does not support KD in v1.

## The loss

Per valid token *t* (i.e. `target != -100`), with student logits *z*:

```
L_t = ce_weight · CE_t  +  kd_weight · τ² · KL(q ‖ p_τ)
```

where

- `CE_t = -log softmax(z)[target_t]` is the standard cross-entropy, at temperature 1;
- `p_τ = softmax(z / τ)` is the student distribution at temperature τ;
- `q` is the teacher's stored top-K logprobs `lp`, renormalized over the K entries at temperature τ: `q_k = exp(lp_k/τ) / Σ_j exp(lp_j/τ)`.

Probability mass outside the teacher's top-K is dropped, and the top-K is renormalized to sum to 1 (the "zero" missing-mass policy, DistillKit's default). The `τ²` factor keeps gradient magnitudes comparable across temperatures. The loss is a mean over valid tokens. Masked positions (`target == -100`, such as prompt tokens in completion-only SFT) add nothing to either term.

The KD term is fused into the LM-head cross-entropy backward kernel, so no extra logits are materialized and there is no separate KD pass.

## Choosing hyperparameters

- `top_k` (32–128) sets how much of the teacher distribution you keep. `32` already captures most of the mass for a confident teacher, and `64` is a good default trade-off. Go to `128` for high-entropy targets or higher temperatures: a flatter teacher puts more mass outside a small top-K, and renormalization throws it away. Storage grows linearly with K (see below).
- `temperature` (1–2): `1.0` matches the teacher distribution as it is. `1.5`–`2.0` softens both distributions and gives the "dark knowledge" in near-miss tokens more gradient weight. Values well above 2 work badly with top-K truncation, because renormalization drops an ever larger tail.
- `kd_weight` / `ce_weight`: the default `kd_weight: 0.5` (with `ce_weight` resolving to `0.5`) balances fitting the labels against matching the teacher. Use `kd_weight: 1.0`, `ce_weight: 0.0` for pure distillation. If you set `kd_weight > 1`, you must set `ce_weight` explicitly.

## Storage cost

A sidecar stores K uint32 ids + K fp16 logprobs per token, so 6·K bytes per token (plus a fixed 1 KiB header per shard):

| `top_k` | Bytes/token | 100M tokens | 1B tokens |
|---------|-------------|-------------|-----------|
| 32 | 192 B | ~19 GB | ~192 GB |
| 64 | 384 B | ~38 GB | ~384 GB |
| 128 | 768 B | ~77 GB | ~768 GB |

## The `kd_loss` metric

During KD training the step log line has an extra `kd_loss` field (see [Metrics](/engine/guides/metrics/#training-metrics)):

- `loss` is the plain (unweighted) cross-entropy mean per valid token, exactly as in normal SFT.
- `kd_loss` is the mean τ²-scaled KL divergence `τ² · KL(teacher_topk ‖ student)` per valid token, accumulated over the micro-steps of the optimizer step. It is reported for rank 0 only (like the GRPO metrics).

The objective being optimized is `ce_weight · loss + kd_weight · kd_loss`. In a healthy run `kd_loss` goes down as the student's distribution moves towards the teacher's. For MoE models the step log line shows the MoE metrics instead, and `kd_loss` is still in the structured step metrics.

Distillation does not affect evaluation. Eval loss is CE-only (the eval loader never reads sidecars), so eval numbers stay comparable with non-KD runs.

## The `.kd` sidecar format

One sidecar per token shard, named `train-NNN.bin.kd` next to `train-NNN.bin`:

```
[Header: 1024 bytes]
  bytes 0..7   : magic "KD.LOGP\n"
  int32 fields (little-endian, int32 index = byte offset / 4):
    [2] version = 1
    [3] k                (top-K per token, 1..1024)
    [4] n_tokens         (must equal the token shard's n_tokens)
    [5] vocab_size       (teacher vocab)
    [6] logprob_dtype    (0 = fp16; only fp16 in v1)
    [7] reserved = 0
  bytes 64..79 : tokenize hash (16 ASCII hex chars from .tokenize_hash,
                 zero-padded) — validated by the Python layer before
                 training (C++ ignores it)
[ids      : n_tokens × k uint32]   at byte 1024
[logprobs : n_tokens × k fp16]     at byte 1024 + 4·k·n_tokens
```

Alignment: row *i* holds the teacher's next-token distribution at input position *i*, the distribution that predicts `tokens[i+1]`. It lines up with `targets[i]`. The DataLoader reads sidecar rows `[chunk_pos, chunk_pos + sequence_len)` for a chunk starting at `chunk_pos`, with no extra shift.

Capture runs the teacher over non-overlapping `sequence_len` windows, which are exactly the chunks the DataLoader serves. The last row of each window is captured too: it predicts the first token of the next window, and training uses it because a chunk's targets are `tokens[chunk_pos+1 .. chunk_pos+S]`. Only rows past the last full window (the shard tail) are zero-filled, and training never reads past the last full chunk. Masked positions are captured normally and skipped at train time through `target == -100`.

Teacher top-K entries whose token id is outside the student's vocabulary (padded teacher LM-head rows) are masked to `-inf` logprob at capture time, so the renormalization in training drops their mass (missing-probability = zero). The trainer logs a warning when the sidecar's teacher vocab is larger than the student vocab. In API mode the header's `vocab_size` is the shard's (student) vocab, which equals the teacher's under the shared-tokenizer requirement.

To inspect or post-process sidecars, use the reader/writer in `surogate/distill/sidecar.py` (pure numpy).

## Cross-tokenizer distillation

The `.kd` sidecar stores teacher token ids, and training uses them to index the student's LM head. That is why the tokenizers must match. To distill from a teacher with a *different* tokenizer, first transplant the teacher's tokenizer onto the student with [`surogate transplant-tokenizer`](/engine/reference/cli/#transplant-tokenizer). It rebuilds the student's embedding and LM-head rows for the teacher's vocabulary (shared tokens are copied exactly, new tokens approximated). After that, the standard same-tokenizer pipeline runs unchanged.

**Decide this before you pick a teacher.** The transplant is a workaround with real costs. The model you train (and ship, unless you transplant back) carries the *teacher's* tokenizer and chat template, which changes your serving setup and your tokens-per-word economics. It also starts training with approximated vocabulary rows that the KD run has to heal before you see net gains (budget a few hundred million tokens; see the tied-embedding note below). Transplanting back afterwards is a second approximation plus a short healing SFT. With a large token budget these costs pay off, and production cross-family distillations are made this way. On a small fine-tuning budget, a weaker same-family teacher is often the better trade.

The default approximation is OMP with `--k 64` (arXiv:2506.06607). Each new token's teacher-space embedding is written as a sparse combination of at most k shared tokens, and the same coefficients are applied to the student's embeddings of those tokens. Arcee used this recipe to build SuperNova-Medius (Llama-3.1-405B logits distilled into Qwen2.5-14B: transplant → offline top-K capture → KD → transplant back).

Dependency: transplantation runs Arcee's `mergekit-tokensurgeon` as an external subprocess. mergekit is LGPL-3.0, so it is deliberately not a surogate dependency (never imported or vendored). Install it with `pip install mergekit` so `mergekit-tokensurgeon` is on `PATH`, or run it in a separate environment with `uvx --from mergekit ...` to avoid its dependency pins.

The workflow:

```bash
# 1) Transplant the teacher's tokenizer onto the student
surogate transplant-tokenizer --student Qwen/Qwen3-8B --teacher deepseek-ai/DeepSeek-V3 \
    --output ./qwen3-8b-dsv3-vocab --device cuda

# 2) Point the KD config's `model:` at ./qwen3-8b-dsv3-vocab
#    (distillation.teacher_model stays the real teacher)

# 3-5) Run the standard pipeline against it — now same-tokenizer by construction
surogate tokenize config.yaml          # optional; distill-capture tokenizes if needed
surogate distill-capture config.yaml
surogate sft config.yaml

# 6) Optional: restore the student's native tokenizer, then run a short
#    healing SFT on native-template data
surogate transplant-tokenizer --restore ./qwen3-8b-dsv3-vocab/transplant_manifest.json \
    --student ./output/merged --output ./qwen3-8b-distilled-native
```

Notes:

- The transplanted model carries the teacher's tokenizer *and chat template*, so tokenization, loss masking and capture agree end to end. The tokenize hash catches drift as usual.
- The forward transplant needs no separate healing stage, because the KD run itself sends dense gradients to exactly the rows that were approximated. After the *reverse* transplant (`--restore`), run a short SFT on native-template data before release (chat-template semantics shift back with the tokenizer).
- A `transplant_manifest.json` is written next to the transplanted model, and `--restore` reads it (the original student is the tokenizer donor, with the recorded method and k).
- Tied-embedding students: small models with `tie_word_embeddings=true` (e.g. Qwen3-0.6B/1.7B) share one matrix between input embeddings and LM head, so the transplant has to compromise between the two approximations. They do heal, but expect a few hundred million KD tokens before quality recovers. Prefer untied students where you can.
- `--method` accepts mergekit's other approximation methods (`common_interpolation`, `subword`, `mean`, ...), but `omp` is the recommended default.

## Limitations (v1)

- Cross-tokenizer teachers need a vocabulary transplant. The trainer only works when teacher and student share a vocabulary: sidecars store teacher token ids that index the student's LM head directly, with no translation layer. Same-family pairs (Qwen3-32B → Qwen3-0.6B) work out of the box. A different-tokenizer teacher works through a [transplant](#cross-tokenizer-distillation), but that is a project decision with costs. It modifies the student, spends part of the KD budget healing the approximated vocabulary rows, and changes the shipped tokenizer (with its chat template and tokens-per-word economics) unless you transplant back, which is a second lossy step plus a healing SFT. Capture checks that every shard token id is below the teacher's vocab size, but passing that check proves little. Pointing capture at a different-tokenizer teacher without transplanting first produces garbage supervision.
- Offline only. There is no live teacher during training, and the teacher signal is frozen at capture time. Capture can query a served teacher over the [vLLM API](#remote-teacher-vllm-api), but the result is still a fixed sidecar.
- CUDA graphs are turned off automatically (`use_cuda_graphs: false` is forced), and KD micro-steps run eagerly.
- Eval loss is CE-only. The KD term exists only at train time.
- Single node only. Combining `distillation:` with a `distributed:` block raises an error, and `parallelism: dispatch_pp` is rejected.
- LM-head row compaction is turned off automatically. `lmhead_drop_ignored_rows` is forced off with a warning.
- No on-the-fly vision training. `train_vision` is not supported with KD (KD needs tokenized shards with sidecars).
- Sidecar logprobs are fp16 only (`logprob_dtype = 0`).

## Troubleshooting

All sidecars are checked before training starts (magic, version, `n_tokens`, `top_k`, file size, and the embedded tokenize hash against `{output_dir}/.tokenize_hash`). Each error tells you what to do:

**Missing sidecar**: `KD sidecar '<shard>.kd' is missing for token shard '<shard>'. Run 'surogate distill-capture <config.yaml>' to capture teacher logprobs.`
You ran `surogate sft` with a `distillation:` block before capturing. Run the capture step. (When `kd_dir` is set, the trainer looks there and symlinks `<shard>.kd` for you. If a *different* real sidecar already sits at `<shard>.kd`, training aborts with `distillation.kd_dir points at <sidecar> but a different sidecar already exists at <shard>.kd; remove one of them.`)

**Tokenize-hash mismatch**: `KD sidecar '<path>' embeds tokenize hash '<old>' but the current token shards have hash '<new>'. The token shards were re-tokenized — re-run 'surogate distill-capture'.`
Anything that changes tokenization (datasets, `sequence_len`, packing, template) re-tokenizes the shards and invalidates the existing sidecars. Teacher rows would no longer line up with tokens, and nothing would warn you, so training refuses to start. Re-run the capture (it recaptures only the invalid sidecars). An `n_tokens` mismatch between sidecar and shard is caught the same way.

**top_k mismatch**: `KD sidecar '<path>' was captured with top_k=<K> but the config requests top_k=<K'>. Re-run 'surogate distill-capture' with the desired distillation.top_k.`
`distillation.top_k` is fixed in the sidecars at capture time. Set the config back to the captured value, or recapture.

**Truncated sidecar**: `KD sidecar '<path>' is truncated or oversized: ... The capture likely did not finish — re-run 'surogate distill-capture'.`
Captures write to a `.tmp` file and rename it atomically when done, so this usually means a stray or hand-copied file. Re-running the capture fixes it.

**Missing `.tokenize_hash`**: `distillation is enabled but no <output_dir>/.tokenize_hash was found...`
The output dir has shards but no tokenization hash (for example, it was only partly copied). Re-run tokenization and the capture.

**Capture: token id out of teacher vocab**: `Token shard '<path>' contains token id <X> but the teacher vocab size is <Y>. Student and teacher must share a tokenizer. For cross-tokenizer distillation, first transplant the teacher's tokenizer onto the student ... then re-tokenize and re-capture against the transplanted model.`
Your teacher does not share the student's tokenizer. Pick a teacher from the same family, or follow the error's advice (see [Cross-tokenizer distillation](#cross-tokenizer-distillation)).

**Capture (API): server rejects or omits `prompt_logprobs`**: see [Remote teacher](#remote-teacher-vllm-api). The endpoint must be a vLLM-compatible server started with `--max-logprobs >= top_k`; aggregators such as OpenRouter cannot be used.

## Example

A complete runnable config lives at [`examples/distillation/qwen3-kd.yaml`](https://github.com/invergent-ai/surogate/blob/main/examples/distillation/qwen3-kd.yaml) (Qwen3-1.7B teacher → Qwen3-0.6B student).

## See also

- [Configuration](/engine/guides/configuration/): how a config file is laid out
- [Datasets](/engine/guides/datasets/): preparing the data that both capture and training tokenize
- [Metrics](/engine/guides/metrics/): reading `kd_loss` next to the other step metrics
- [Config reference](/engine/reference/config/): every `distillation:` option
- [Back to docs index](/engine/)
