X-Token: Cross-Tokenizer Knowledge Distillation from Scratch
Building cross-tokenizer distillation from the ground up — why per-position KL breaks across tokenizers, DP span alignment, the chain-rule chunk merge, the projection matrix W, and two complementary losses (P-KL and H-KL) — with a full proof of GOLD's suppressive gradient and one running 2+3 example derived step by step.
We want to teach a small Llama-3.2-1B student using a strong Qwen3-4B teacher. There is one problem, and it sounds trivial until you try it: the two models do not agree on what a token is. Qwen splits the number 201 into three tokens 2, 0, 1. Llama packs it into a single token 201. The standard distillation loss compares the student’s probability of token against the teacher’s probability of token — but token does not mean the same thing on both sides. The comparison is undefined.
This post builds the solution from NVIDIA’s X-Token paper (Turuvekere Sreenivas et al., 2026) from scratch. We will derive every piece: why naive distillation fails, how to align two token streams with dynamic programming, how to merge per-token probabilities into per-chunk probabilities, how to build a projection matrix that maps one vocabulary into another, and the two complementary losses — P-KL and H-KL — that fix two distinct failure modes of the prior state of the art. We will also prove, in full, the suppressive-gradient pathology that motivates the whole design.
We use one running example throughout. The teacher and student both process the string "2+3=6". The student tokenizes the answer 6 and the prompt naturally; the teacher uses a different tokenizer that, on the number 201 appearing elsewhere, splits digits. We will lean hardest on the single chunk where the text is the multi-digit number 201, because that one chunk exposes every failure and every fix.
1. Mathematical setup
This post is self-contained, but it leans on a few tools that earlier posts in this series already derived from scratch. Rather than re-derive them, we link out and recall only what we need:
- KL divergence and entropy — the definition , that it is zero iff (Gibbs’ inequality), and the entropy — are built in Mathematical Prerequisites for Foundation Prior.
- The softmax function and the logarithm rules are built in Mathematical Prerequisites for Mixture of Experts.
- The chain rule of calculus and derivatives are built in Mathematical Prerequisites for Reinforcement Learning; argmax and the indicator function in Mathematical Prerequisites for Mixture of Experts (Part 2).
There is exactly one identity we will need that those posts do not state outright, and the suppressive-gradient proof in Section 9 depends on it entirely, so we derive it here once: the softmax log-derivative identity.
We want , the sensitivity of one log-probability to one logit, where with the normalizer . Take the log first:
Differentiate with respect to term by term. The first term: , the indicator function (1 if , else 0), since distinct logits are independent variables. The second term, by the chain rule of calculus, is
where because every other term of the sum is constant in . Subtracting:
Numerical check. Suppose three logits give . Then (raising logit 1 raises its own log-prob, but less than one-for-one because the normalizer also grows), while (raising a different logit lowers , purely through the normalizer). That second case — the cross term being with no indicator — is the engine of the suppressive gradient we prove in Section 9. We restate this boxed identity there at the point of use.
2. The setup: standard knowledge distillation
Knowledge distillation (KD) is training a small student model to imitate the full output distribution of a large teacher model, not just its top answer (Hinton, Vinyals, Dean, 2015). The teacher’s full distribution carries dark knowledge — the relative probabilities it assigns to wrong answers, which encode similarity structure the hard label throws away.
Concretely, at one position the teacher produces a probability distribution over its vocabulary , and the student produces over its vocabulary . The standard loss is the Kullback–Leibler divergence of the student from the teacher:
Let us name what we just used. The KL divergence measures how many extra nats you pay to encode samples from using a code optimized for . It is zero exactly when and positive otherwise — this is Gibbs’ inequality, with equality iff . Minimizing it drives the student toward the teacher.
This loss has a hidden assumption baked into the sum : index must mean the same token in both distributions. When — same tokenizer, same vocabulary — that holds, and KD is a clean drop-in. The moment the tokenizers differ, the sum is comparing apples to oranges. That is the entire problem.
3. Why per-position KL is ill-defined across tokenizers
Take our running text 201. Two tokenizers, two token streams:
- Student (Llama-style): one token,
[201]. One position. - Teacher (Qwen-style): three tokens,
[2, 0, 1]. Three positions.
The student emits one distribution; the teacher emits three. There is no position shared between them. Even the lengths of the two sequences disagree. You cannot write because there is no single and aligned at a common position.
This is the part that trips people up: it is not merely that the vocabularies are different sets of symbols. It is that the segmentation of the same underlying text is different, so the sequences have different lengths and no positional correspondence. We need two things, in order:
- A way to group tokens on each side into chunks that cover the same underlying text, so we have aligned units to compare. (Section 4 and 5.)
- A way to compare a student chunk-distribution to a teacher chunk-distribution when the two are still over different vocabularies. (Section 7 onward.)
Let us solve them one at a time.
4. Span alignment with dynamic programming
We need to partition both token streams into aligned chunks , where chunk on the student side (, a run of student tokens) and chunk on the teacher side (, a run of teacher tokens) decode to the same substring of text. For 201, the aligned chunk is
because 201 (one student token) and 2,0,1 (three teacher tokens) both decode to the string "201".
How do we find these chunks automatically for an arbitrary sentence? X-Token uses dynamic programming (DP). Let be the first student tokens and the first teacher tokens. Define as the maximum alignment score achievable over those two prefixes. The recurrence is
with boundary conditions and . Here denotes canonicalized string equality between a single token and the concatenation of a span — two strings are equal after normalizing surface differences like space-prefix markers (we make this precise in Section 6). The scoring constants used throughout the paper are
where if the two canonicalized tokens are string-equal and otherwise. After filling the table, a backtrace from recovers the chosen chunk boundaries; transitions selected as gaps mark token positions as unaligned, and those positions are excluded from the loss.
Why soft scoring, not hard alignment
A hard alignment — align-or-fail — has two failure modes on real text. First, a single local oddity (a byte-fallback token, an unusual whitespace glyph) can make the entire sequence misalign or propagate the error to neighbors. Second, two locally-plausible alignments can tie, and an arbitrary tie-break produces inconsistent alignments across training runs. The soft scoring resolves both. Gaps cost , so the DP prefers to insert one gap rather than distort a long stretch. And a -token combination scores , which competes favorably with individual exact matches () only when no exact match exists — so exact 1-to-1 matches are preferred when available, and span combinations are the fallback. The inequality (i.e. ) is what rewards walking through an alignment over walking around it.
Numerical check on the running example
Suppose at the relevant region the student has the single token 201 and the teacher has 2,0,1. The DP can either (a) take three gaps to skip them apart, scoring , or (b) take one 1-to- combination with , since 201 2+0+1 after concatenation, scoring . Since , the DP chooses the combination and emits the aligned chunk . The numbers come out exactly as the design intends.
5. The chain-rule chunk merge
Span alignment gives us which tokens form a chunk. But the teacher chunk [2, 0, 1] is still three separate per-token distributions, while the student chunk [201] is one. To compare them we need one distribution per chunk on each side. We build it with the chain rule of probability.
A chunk-level distribution is the probability the model assigns to producing the entire chunk’s text, decomposed autoregressively over its tokens. For the teacher chunk , the probability of that specific three-token string is
This is the chain rule of probability: . Each factor is exactly the per-position softmax the teacher already computed during its forward pass, so the merge is free — no extra model calls.
Numerical check
Suppose the teacher is confident: , , . Then
The student, packing 201 as one token, directly reads off from its single softmax — say . Now both sides express the same event (“the model produces the text 201”) as a single number, and we finally have aligned, comparable units: and . This chunk-level view is what every loss below operates on.
6. Canonicalization: making “the same text” actually the same
Before we can declare two tokens string-equal in the DP or in the projection matrix below, we must normalize away cosmetic differences between tokenizer families. The canonicalization function maps a token’s decoded string to a normal form so functionally identical tokens compare equal. The rules, applied in order:
- Space-prefix unification: the GPT-2/Llama space marker
Ġ, the SentencePiece marker▁, and a literal Unicode space all map to a single literal space at the start of a token. - Newline unification:
Ċ, the escaped\n, and a literal newline all map to\n. - Byte-fallback tokens: SentencePiece byte tokens of the form
<0xHH>are replaced by the literal character with that byte value. - Leading whitespace + punctuation pairs: combinations like
Ġ,are normalized to the punctuation alone when the whitespace interpretation is ambiguous. - Special tokens: BOS, EOS, PAD, and chat-template tokens are handled by an explicit role-to-role mapping across families.
Canonicalization is idempotent (applying it twice changes nothing) and involves no learned parameters. It is applied at both projection-matrix construction time and inside the DP’s string-equality check, so the two stages agree on what “the same text” means.
This matters more than it looks. The paper documents a concrete failure of an alternative surface-substring aligner (used in TRL’s GOLD trainer) caused by exactly this: the Llama tokenizer auto-prepends a <bos> token (its config default add_bos_token=True) while Qwen and Phi-4-mini default to False. On the input "Hello world." the decoded streams differ on byte 0. The surface aligner extends per-side decoded buffers piece by piece and only flushes when the buffers compare equal as raw strings, but after the first piece, the student buffer is "<|begin_of_text|>" (16 chars) versus the teacher’s "Hello" (5 chars). They never re-sync, and the end-of-sequence force-flush dumps everything into one mis-grouped super-group bundling all tokens together. The DP, by contrast, marks the spurious <bos> as a one-sided gap of unit cost and aligns the three content tokens diagonally as 1-to-1 matches. The disagreement is localized to one gap regardless of sentence length.
7. The projection matrix
We have aligned chunks and chunk-level distributions, but lives over and lives over . They are still distributions over different vocabularies. The final bridge is a projection matrix that maps a student-vocabulary distribution into teacher-vocabulary space. Entry is the weight with which student token ‘s probability mass should be routed to teacher token .
is built deterministically in two passes.
Pass 1 — canonicalized exact match. For every pair whose canonicalized decoded strings are equal, set . This handles tokens that exist verbatim in both vocabularies (e.g. _the, _cat).
Pass 2 — multi-token decoding rule. For each remaining student token with no exact match, decode its text and re-tokenize it under the teacher tokenizer, yielding a sequence of teacher sub-tokens. Assign exponentially decaying weights along that sequence:
with . Then each row is truncated to its top- entries () and row-normalized.
The decay concentrates mass on the leading sub-token, which typically carries the most informative probability mass for cross-tokenizer distillation (e.g. _20 in ["_20", "24"], or the prefix in ["_inter", "national"]), while trailing sub-tokens matter less given the prefix.
Numerical check on the decay
For our 201 example, the student token 201 re-tokenizes under the teacher as , length . Before normalization:
The sum is . Row-normalizing (dividing each by ):
These are exactly the length-3 weights the paper reports. Almost all of 201’s mass routes to the teacher’s leading sub-token 2.
is a probability-preserving operator
Here is the property that makes safe to use. Each row of is non-negative and sums to 1 (after normalization), so left-multiplication by is a convex combination of rows — and a convex combination of probability vectors is a probability vector. Let us prove the projected student distribution is still a valid distribution. Writing for the student chunk distribution,
The middle step swaps the order of summation (Fubini’s theorem for finite sums — interchanging two finite sums is always valid), then uses row-normalization , then total probability . So is a genuine distribution over with no extra normalization tricks. We will use this in P-KL.
is constructed once before training. It can optionally be fine-tuned during KD for additional gains — we will see the ablation.
8. The baseline and its two failures: GOLD’s hybrid loss
To appreciate X-Token’s two losses we must first see precisely how the prior state of the art, GOLD (Patiño et al., 2025), fails. GOLD partitions the two vocabularies into a 1-to-1 string-matched common set and uncommon remainders with . It applies direct KL on the common set and a rank-sorted match (a Universal Logit Distillation, ULD, term Boizard et al., 2024) on the uncommon remainder:
Now the two failures.
Failure 1 — the uncommon-token failure
A critical token is a token whose correct prediction directly determines task accuracy — the multi-digit numerals in a math benchmark like GSM8k are the canonical example. Under the Qwen3-4B teacher, all 1,100 of Llama’s two- and three-digit numerals fall into the uncommon set , because Qwen digit-splits and Llama does not, so there is no 1-to-1 match (Table 8 in the paper: 0/100 two-digit and 0/1000 three-digit Llama numerals survive into ).
These critical tokens are then handled only by the rank-sorted ULD term, which pairs the student’s numeral with whatever teacher token happens to sit at the same rank — an unrelated special character, perhaps. This is identity-agnostic noise: it misaligns critical tokens with semantically unrelated teacher tokens. The supervision signal on exactly the tokens that matter most is garbage.
Failure 2 — the suppressive gradient (proven below)
Worse, even though the uncommon tokens do not appear in , the common-KL term still pushes their probabilities down, because it is computed through the full-vocabulary softmax. We will prove this in Section 9.
The empirical cost is dramatic: on the Qwen pair, GSM8k drops to 2.56 under GOLD, versus 12.89 for same-tokenizer KD from a weaker Llama-3B teacher. Cross-tokenizer KD from a stronger teacher does worse than same-tokenizer KD from a weaker one. Something is actively harmful.
Failure 3 — over-conservative matching
A third, subtler issue: GOLD’s common set requires exact string equality. A pair like (Hundreds, Hund) — where the student token corresponds to the teacher’s leading sub-token — is near-equivalent but not string-equal, so it is exiled to and its clean alignment signal is wasted. Strict equality is too conservative even when the partition is otherwise sound.
X-Token attacks Failures 1–2 with P-KL and Failure 3 with H-KL.
9. Proof: the common-KL term suppresses every uncommon token
This is the formal heart of the motivation. We prove Proposition 1: GOLD’s common-KL term induces a non-negative gradient on every uncommon student logit, pushing all uncommon-token probabilities down, even though those tokens never appear in the loss.
Setup. Fix one chunk. Let be the student logits, , and let be the fixed teacher distribution. Let and be the two sides of the common set (a bijection: each appears in exactly one pair ), and the uncommon set. The full-vocabulary softmax is
The common-KL term, dropping the constant teacher-entropy part, is
Two preliminary identities. Treating each logit as an independent variable, for any :
The first is immediate. The second follows from by the chain rule of calculus: differentiating gives , and differentiating the sum picks out only the -th term , leaving .
Combining with :
This is the standard softmax log-derivative identity.
The proof. Fix an uncommon logit . Since and are disjoint, every satisfies , so and the identity above collapses to for every . The teacher factor does not depend on . Differentiating with respect to (using linearity of differentiation to move the derivative inside the finite sum):
Writing (the teacher’s total mass on the common set — a sub-sum of a probability distribution, hence between 0 and 1):
The gradient is non-negative because both factors are non-negative ( and ), and it vanishes only when one of them is zero.
Interpretation. Gradient descent with step updates . So every uncommon logit is driven down at every step. Because the softmax is monotonically increasing in each logit, shrinking shrinks relative to all other probabilities. The probability mass of every uncommon token is suppressed — even though no uncommon token appears in , and the gradient depends only on , making it independent of the ground-truth token at the position. When your critical numerals live in (the Qwen case), GOLD is actively training the student to stop predicting them. This is why GSM8k collapses to 2.56.
Numerical check
Say at a chunk and the teacher places of its mass on common tokens. Then , and with the logit moves by — downward, every step, regardless of whether 201 is the correct answer.
10. P-KL: remove the partition entirely
The fix for Failures 1 and 2 follows directly from the proof: the partition is the problem, so delete the partition. P-KL (“projection KL”) projects the student’s full chunk distribution into teacher-vocabulary space using and applies a single KL against the teacher’s full distribution — no common set, no ULD term, nothing for an uncommon token to fall out of.
Define the projected student distribution over :
The first equation is exactly the operator , which Section 7 proved is a valid distribution over . The second is plain KL between two distributions over the same teacher vocabulary — now well-defined. Because there is no partition, the critical token 201 is no longer exiled to ; its mass is routed through onto the teacher’s decomposition and compared directly. Both sources of error from Section 8–9 are replaced by teacher-aware supervision over all tokens.
Numerical check
From Section 7, routes student 201 as onto teacher . If the student chunk distribution puts (and we ignore other student tokens for illustration), the projected mass on teacher token 2 is , on 0 it is , and on 1 it is . These now sit in the same teacher vocabulary as , and KL compares them directly — no rank-matching, no suppression.
When P-KL wins
P-KL is the right loss when critical tokens fall outside the common set — the Qwen3-4B regime where all multi-digit numerals are uncommon. Empirically P-KL improves over GOLD by +3.82 average points, and on GSM8k specifically from 2.56 to 15.54 — a jump that even surpasses same-tokenizer KD from Llama-3B (12.89). Notably, plain ULD (no partition, just rank-sort) already beats GOLD (36.77 vs 35.03 avg), confirming the partition is the primary source of failure; P-KL’s identity-aware projection then adds another +2.08 over ULD.
11. H-KL: keep the partition, relax the matching
P-KL throws away the partition entirely. But sometimes the partition is good — when critical tokens already live in the common set, direct identity-aligned KL gives sharper supervision than projecting student mass through ‘s multi-token rows. This is the Phi-4-mini regime: Phi-4-mini keeps all of Llama’s multi-digit numerals in (Table 8: 100/100 two-digit, 1000/1000 three-digit). Here the partition is structurally sound, and discarding it (using P-KL) would sacrifice identity-aligned signal — the paper measures this as a regression.
So the second loss, H-KL (“hybrid KL”), keeps GOLD’s hybrid structure but fixes Failure 3 — the over-conservative exact-match requirement. Instead of requiring string equality to enter , H-KL admits each student token’s top-ranked teacher token under . For each student token , select
and extend the common set with the pair . Exact matches are preserved (they receive the highest weight, 1, in ), and additional near-equivalent pairs like (Hundreds, Hund) are now admitted — they get the same direct-KL signal as a native exact match. H-KL then applies the hybrid loss (the GOLD formula of Section 8) over this expanded common set.
When H-KL wins
H-KL is the right loss when token alignment is reliable — the partition is sound and we want the sharper identity-aligned KL. On the Phi-4-mini teacher, H-KL improves over GOLD by +0.5 average and beats P-KL by +1.68 on that teacher. The reversal is exactly symmetric to P-KL’s: each loss exhibits a sharp drop when applied to the wrong teacher (Table 2 flips the per-teacher winner). Neither mode dominates; the loss must match the regime.
12. The unified view: P-KL and H-KL are two points on one axis
It is tempting to see P-KL and H-KL as two unrelated tricks. They are not. They are the two settings of a single design decision: what to do with the partition.
Both share the same machinery: the same DP alignment, the same chunk merge, and the same projection matrix . P-KL uses as a full projection ( then KL). H-KL uses only for its top-1 entry per row ( to expand ). The conceptual difference between the two methods is therefore completely transparent: how much of you use, and whether you keep the partition. This is what makes the selection rule simple.
The selection rule: a coverage audit
We choose between them with a coverage analysis. Group tokens into character classes (digits by length, alphabetic, punctuation, multi-byte / non-ASCII) and measure each class’s retention in the common set . The rule:
- If critical tokens fall outside → use P-KL (Qwen3-4B: all multi-digit numerals are uncommon).
- If critical tokens remain inside → use H-KL (Phi-4-mini: numerals stay common, punctuation fully covered).
This is a one-time, deterministic audit per teacher — no tuning loop.
13. Plugging the chunk loss into training
The per-chunk loss feeds the standard KD objective, averaged over the aligned chunks of a sequence (top- teacher logits with for the KL itself):
Two practical details complete the recipe.
Dynamic KD/CE scaling. Distillation is combined with ordinary next-token cross-entropy on the student. These two terms can differ wildly in magnitude and drift during training, so a fixed weight makes optimization unstable. X-Token rescales the KD term at every step to match the scale of :
where is the stop-gradient operator: the ratio is treated as a constant for differentiation, so it only rescales the magnitude and does not contribute its own gradient. The effect is that the KD contribution always carries roughly the same weight as CE, regardless of their raw scales. The ablation (Table 4) shows dynamic scaling reaching 36.39 avg vs 35.92–36.27 for the best fixed weights.
Multi-teacher distillation. With teachers, each with its own projection matrix and its own selected loss, aggregate per-teacher losses with static weights:
The surprising finding: static weighting beats adaptive weighting. The paper tried confidence-adaptive from cross-entropy, entropy, and max-probability scores, and a simple static ratio won every time (Table 5: static (0.2, 0.8) reaches 40.48 avg vs 40.16–40.21 for adaptive variants). Adaptive schemes add tuning complexity without consistent gains.
The deeper lesson is about which teachers to combine, not how to weight them. Teacher complementarity drives the gains: pairing Phi-4-mini (math/reasoning) with Llama-3B (commonsense) reaches 40.48 avg, beating the best single cross-tokenizer teacher by +1.3 — while pairing two reasoning teachers (Phi-4-mini + Qwen3-4B) gives only 38.49, where overlapping strengths interfere rather than add.
14. The full algorithm, end to end
Putting every piece in order, one X-Token training step is:
- Preprocess (cached across epochs): tokenize input on both sides → , . Run the DP alignment (Section 4) to get aligned chunks . Alignment is per-sequence and adds no per-step training overhead.
- Forward: run the student with gradient, the frozen teacher without.
- Per chunk : merge per-token probabilities into chunk distributions via the chain-rule merge (Section 5).
- Apply the selected loss: if P-KL, project and take ; if H-KL, apply the hybrid common-KL + ULD over the expanded .
- Aggregate (temperature ), compute , apply the stop-gradient rescaling , and update via .
is initialized rule-based (Section 7), then jointly learned with the student under P-KL (learning rate , no gradient clipping) and kept fixed under H-KL (which only reads , a discrete operation that receives no gradient). The ablation (Table 3) confirms learning helps modestly: 38.85 vs 38.37 avg on the Qwen pair, winning 5/6 benchmark columns — so the rule-based construction is already a strong initialization that fine-tuning refines.
15. What the numbers say
Training a Llama-3.2-1B student on the Nemotron-ClimbMix dataset for 30,000 steps, evaluated 3-shot across MMLU, GSM8k, MATH, Winogrande, and HellaSwag:
- Frozen baseline: 33.96 avg. Continued pre-training (no teacher): 36.63 — modest, confirming the gains come from distillation, not extra compute.
- Same-tokenizer KD (Llama-3B → 1B): 38.40 avg — the same-family ceiling.
- Qwen3-4B teacher: GOLD 35.03 (below even no-teacher pre-training!) → P-KL 38.85 (+3.82), with GSM8k 2.56 → 15.54.
- Phi-4-mini teacher: GOLD 38.66 → H-KL 39.18 (+0.5).
- Two teachers (Phi-4-mini + Llama-3B): 40.48 avg, beating the best single cross-tokenizer run by +1.3 and the same-family reference by +2.1.
The headline: cross-tokenizer KD, done right, exceeds same-tokenizer KD — you are no longer locked to teachers that share your tokenizer, and combining complementary teachers from different families adds gains a single teacher cannot.
16. Summary
Standard distillation breaks across tokenizers because per-position KL assumes a shared segmentation that does not exist; X-Token restores it with DP span alignment (grouping tokens into chunks that decode to the same text), a chain-rule merge (collapsing each chunk’s per-token softmaxes into one chunk-level distribution), and a projection matrix (a probability-preserving operator mapping student-vocabulary mass into teacher space, built from canonicalized exact matches plus exponentially-decayed re-tokenization rules). On top of this shared machinery sit two complementary losses chosen by a one-time coverage audit: P-KL deletes GOLD’s partition and projects the full student distribution through — the cure for the suppressive gradient we proved drives every uncommon (and often critical) token’s probability to zero — while H-KL keeps the partition but expands the common set via ‘s top-1 mapping, recovering sharper identity-aligned KL whenever the partition is already sound. Together with dynamic KD/CE rescaling and complementary-teacher multi-distillation, these let a 1B student learn from any-family teachers and beat same-tokenizer distillation outright.
Previous: DeepSeek-V4 Hybrid Attention: CSA and HCA from Scratch
Enjoyed this post?
Subscribe to get notified when I publish new posts. No spam, unsubscribe anytime.