A Blazing Fast LM-Head Replacement

A language model writes text one token at a time. A token is a word or a piece of a word, and the fixed list of all the tokens a model knows is its vocabulary. At each step the model boils the text so far down to one list of numbers called the hidden state. The last layer, which people call the head, then compares the hidden state against a stored vector for every token in the vocabulary, and the token whose vector matches best is the one that gets written.

Each comparison is a dot product, which multiplies the two vectors entry by entry and adds the results up. With a vocabulary of 262,144 tokens that is 262,144 dot products on every token the model writes. On a phone CPU, which is where models under a billion parameters actually run, that one step is often at least a tenth of the whole time spent per token. It is paid in full however obvious the next token is. Almost all of it goes on tokens that were never going to be chosen, because the model nearly always puts its confidence on a handful of candidates.

namewhat it is
Gemma 3 270M-ITA small open language model from Google with 270 million parameters and a vocabulary of 262,144 tokens. IT means the instruction-tuned version, the one trained to follow requests.
WildChatA public dataset of a million real conversations between people and ChatGPT. We use its prompts and the model's completions on them.
FineWeb-EDUA dataset of educational web pages. We use it as text the router never saw during training.
AdamWThe standard optimiser for training transformers. It adapts the step size for each weight and pulls the weights gently toward zero.

The work here is on Gemma 3 270M, the small model with that 262,144 token vocabulary, using WildChat conversations as the text. HiDRA replaces the dense head, dense because it scores every token, with a binary tree of yes-or-no questions over the vocabulary. The hidden state answers up to eighteen of them, each one a single dot product, and lands at a leaf of the tree. The dense head then scores only the tokens under that leaf. The base model is frozen and only the tree is trained.

Top-1 accuracy is how often the single most likely token under the head is the true next token. On WildChat completions the output stage runs 8.04 times faster and gives up 4.2 points of top-1 accuracy. The depth of the tree is chosen at inference time, after training is done, so the same tree gives a whole curve of speed against quality.

The cost of the head

A little maths follows, though I have kept it to dot products where I could. The score the head gives each token is called a logit. Decoding computes the logits zk=h⊤ekz_k = h^{\top} e_k for every token kk. Here h∈Rdh \in \mathbb{R}^{d} is the hidden state, a vector of dd numbers, and ek∈Rde_k \in \mathbb{R}^{d} is the stored vector for token kk, which is called its embedding. The embeddings stacked on top of each other form a matrix with VV rows and dd columns, where VV is the vocabulary size.

An embedding needs a picture. Every token has a stored list of d numbers that the model learned during training, and tokens that are used in similar ways end up with similar lists, so cat sits near dog and far from therefore. That list is the token's embedding. The head's matrix is all 262,144 of those lists stacked on top of each other, and scoring a token means comparing the hidden state with one of them.

Physically the head is one pass over that matrix. Every row is read from memory and multiplied against the same hidden state, so the cost per step is O(Vd)O(Vd), which means it grows in proportion to the vocabulary size times the width. The transformer body does not grow when the vocabulary grows, but this layer does, and vocabularies have been growing.

The logits are turned into probabilities by the softmax, which exponentiates each logit and divides by the total so that the VV numbers add up to one. That distribution is nearly always concentrated on a small fraction of the vocabulary. So most rows are read only to confirm they are irrelevant.

The way out is to decide roughly where the probability is before scoring anything. HiDRA gives every token a binary path of LL bits. The vocabulary is split in half, each half is split in half again, and so on until each leaf holds one token. With V=262,144=218V = 262{,}144 = 2^{18} that takes L=18L = 18 levels.

Routing the hidden state down the tree costs one dot product per level. After l≤Ll \le L levels only the V/2lV/2^{l} tokens under the reached node still need scoring. The cost becomes

O ⁣(Ld+V2l d). O\!\left(Ld + \frac{V}{2^{l}}\,d\right).

At l=0l = 0 nothing has been decided and this is the dense head. Each extra level costs one more dot product of width dd and halves the second term. At l=Ll = L the whole output stage is eighteen dot products and one row.

The depth ll is not fixed when the tree is built. It is a number whoever deploys the model picks for their hardware, so the same tree can run shallow on a fast machine and deep on a slow one.

routing one hidden state down the token treeeach level is one dot product with a decision vector · the leaf keeps V / 2^l tokensdepth 0 · candidates left 262,144bit = 1[ h·d + b > 0 ] at each node · after depth l the dense head scores only the leafdepth 1 · candidates left 131,072bit = 1[ h·d + b > 0 ] at each node · after depth l the dense head scores only the leafdepth 2 · candidates left 65,536bit = 1[ h·d + b > 0 ] at each node · after depth l the dense head scores only the leafdepth 3 · candidates left 32,768bit = 1[ h·d + b > 0 ] at each node · after depth l the dense head scores only the leafdepth 4 · candidates left 16,384bit = 1[ h·d + b > 0 ] at each node · after depth l the dense head scores only the leafdepth 5 · candidates left 8,192bit = 1[ h·d + b > 0 ] at each node · after depth l the dense head scores only the leaf
Each internal node of the tree holds one decision vector and a bias. The hidden state takes the left or right branch depending on the sign of one dot product, so reaching depth l costs l dot products instead of V. The dense head then scores only the tokens under the reached node, which is V over 2 to the l of them. The tree is drawn 16 wide at the bottom, the real one is 262,144 wide.

The hyperplane at each node

Each internal node ℓ\ell holds a decision vector dℓ∈Rdd_\ell \in \mathbb{R}^{d} and a bias bℓb_\ell, which is a single number added on. It sends the hidden state left or right by the sign of one weighted sum plus a constant,

bitℓ=1 ⁣[h⊤dℓ+bℓ>0]. \mathrm{bit}_\ell = \mathbb{1}\!\left[h^{\top} d_\ell + b_\ell > 0\right].

Geometrically that is a hyperplane in the hidden space. A hyperplane is a flat surface that cuts the space into two halves, the way a line cuts a sheet of paper in two. The vector dℓd_\ell is its normal, the direction pointing straight out of the surface, and the bias slides the surface along that normal. The two half-spaces are the two children of the node.

The question is which hyperplane each node should hold. Every token kk has an embedding eke_k, and the tree needs the embeddings of the left child's tokens on one side and the right child's on the other. But the thing being routed at inference is not an embedding, it is a hidden state. When the tree is built there is no hidden state to look at.

So we model it. When the true next token is tt, take the hidden state to be the embedding of tt plus noise,

h=et+ρ,ρ∼N(0,Σ). h = e_t + \rho, \qquad \rho \sim \mathcal{N}(0, \Sigma).

The symbol N(0,Σ)\mathcal{N}(0, \Sigma) means Gaussian noise, the bell-curve kind, centred on zero. Its covariance Σ\Sigma is a matrix that says how wide the noise is in every direction and which directions it stretches along. So this says a hidden state that is about to produce token tt lies in a cloud around ete_t, and Σ\Sigma is the shape of that cloud.

Drop the node subscript and write the margin mt=d⊤et+bm_t = d^{\top} e_t + b. That is the signed distance of ete_t from the hyperplane in units of ∥d∥\|d\|, the length of the normal. Its sign says which side the embedding is on and its size says how far from the surface it sits.

The routing decision for hh is the sign of

d⊤h+b=mt+d⊤ρ, d^{\top} h + b = m_t + d^{\top}\rho,

and it goes wrong when the noise term is large enough, and in the wrong direction, to flip that sign.

Now the geometry pays off. The noise ρ\rho lives in dd dimensions, but the only part of it that matters is its projection onto the normal, the shadow it casts along that one direction, which is the single number d⊤ρd^{\top}\rho. A linear function of a Gaussian is Gaussian, so d⊤ρ∼N(0,d⊤Σd)d^{\top}\rho \sim \mathcal{N}(0, d^{\top}\Sigma d). The quantity d⊤Σdd^{\top}\Sigma d is the variance of the cloud measured along dd, so it is how wide the cloud is in the one direction that can flip the decision.

The tails of a Gaussian are the far ends of the bell, and a standard bound on how little probability sits out there gives

P(error)≤2exp⁡ ⁣(−mt22 d⊤Σd). P(\text{error}) \le 2 \exp\!\left(-\frac{m_t^{2}}{2\, d^{\top} \Sigma d}\right).

Everything about the choice of dd is in the exponent. The error falls with the margin squared and rises with the spread of the noise along the normal. So the direction to pick is the one that maximises mt2/d⊤Σdm_t^{2} / d^{\top}\Sigma d.

A large margin on its own is not enough. A hyperplane whose normal points along a direction where the cloud is wide has a large d⊤Σdd^{\top}\Sigma d. It will misroute even with a comfortable margin.

Fisher's discriminant

For a node splitting its tokens into a left set and a right set with means μL\mu_L and μR\mu_R, the expected margin scales with d⊤(μR−μL)d^{\top}(\mu_R - \mu_L). That is the separation of the two groups measured along dd.

The true noise covariance Σ\Sigma is unknown. We stand in for it with the within-class covariance Σw\Sigma_w of the embeddings. That is the spread of each group's embeddings around its own mean, pooled over the two groups, and in practice that spread lines up well with the shape of the embedding space. The objective becomes

max⁡d(d⊤(μR−μL))2d⊤Σwd. \max_d \frac{\left(d^{\top}(\mu_R - \mu_L)\right)^{2}}{d^{\top} \Sigma_w d}.

This is Fisher's linear discriminant from 1936, usually called LDA for linear discriminant analysis, and the answer has a simple shape. The ratio is a separation squared over a spread, both measured along one direction. It does not change if dd is rescaled, so only the direction matters.

Change coordinates so that the within-class cloud becomes round. Writing d=Σw−1/2ud = \Sigma_w^{-1/2} u turns the denominator into u⊤uu^{\top} u and the numerator into (u⊤Σw−1/2(μR−μL))2\left(u^{\top} \Sigma_w^{-1/2}(\mu_R - \mu_L)\right)^{2}. In those coordinates the problem is to pick a unit vector uu with the largest dot product against a fixed vector. The answer is the fixed vector itself, u∝Σw−1/2(μR−μL)u \propto \Sigma_w^{-1/2}(\mu_R - \mu_L). Mapping back gives

d⋆∝Σw−1(μR−μL). d^{\star} \propto \Sigma_w^{-1}(\mu_R - \mu_L).

So the Fisher direction is the mean difference after whitening, where whitening means stretching the space until the cloud is round. If the noise were the same width in every direction, Σw\Sigma_w would be a multiple of the identity and the plain mean difference would already be the right normal.

It is not the same width in every direction here. Token embedding spaces in trained models are strongly anisotropic, which means the cloud of embeddings is stretched far along a few directions and thin along the rest. Most of the variance sits in a few shared directions that carry no information about which token is which. Embeddings in context also sit in a narrow cone where similarity is dominated by what all tokens share rather than by meaning.

That is also why centroid methods like k-means are a poor fit for grouping tokens. k-means groups points by their distance to a centre, so it assumes round clusters, and those clusters are not there.

A mean-difference hyperplane has some component along those few long directions, so its d⊤Σwdd^{\top}\Sigma_w d is large and the bound is loose. Multiplying by Σw−1\Sigma_w^{-1} shrinks the components of dd along the long axes. That tilts the hyperplane until it cuts the clouds across their thin direction. The margin shrinks a little, the noise along the normal shrinks a lot, and the ratio grows.

The tree is built from the embedding matrix alone by recursive median splits along the LDA direction. We use the median rather than the mean so that the two children hold equal numbers of tokens and the tree stays balanced. That balance is what makes the leaf at depth ll hold V/2lV/2^{l} tokens rather than some unlucky larger set. Each node's LDA vector becomes the initial value of its decision vector.

the direction that minimises routing errorthe noise is stretched along one axis · the Fisher split d ∝ Σw⁻¹(μR − μL) misroutes fewer pointsmean differenced = μR − μLerrors on these 80 points 16P(error) ≤ 2 exp(− m² / 2 dᵀΣd)so maximise m² / dᵀΣdrotatingd = …errors on these 80 points 12P(error) ≤ 2 exp(− m² / 2 dᵀΣd)so maximise m² / dᵀΣdrotatingd = …errors on these 80 points 7P(error) ≤ 2 exp(− m² / 2 dᵀΣd)so maximise m² / dᵀΣdrotatingd = …errors on these 80 points 7P(error) ≤ 2 exp(− m² / 2 dᵀΣd)so maximise m² / dᵀΣdrotatingd = …errors on these 80 points 5P(error) ≤ 2 exp(− m² / 2 dᵀΣd)so maximise m² / dᵀΣdrotatingd = …errors on these 80 points 4P(error) ≤ 2 exp(− m² / 2 dᵀΣd)so maximise m² / dᵀΣdrotatingd = …errors on these 80 points 2P(error) ≤ 2 exp(− m² / 2 dᵀΣd)so maximise m² / dᵀΣdFisher LDAd = Σw⁻¹(μR − μL)errors on these 80 points 0P(error) ≤ 2 exp(− m² / 2 dᵀΣd)so maximise m² / dᵀΣd
Two clouds of points, stretched along one axis, split by one hyperplane. The first frame uses the mean difference as the normal and misroutes 16 of the 80 points. The later frames tilt the normal toward the Fisher direction and the count falls to zero. The margin shrinks a little while the noise along the normal shrinks a lot. The points are made up.

Training the nodes

LDA sees the embeddings and nothing else. It does not know that some tokens are far more frequent than others. It also does not know what real hidden states look like, since the Gaussian cloud was a model rather than a measurement.

So after initialisation every node is fine-tuned as a yes-or-no classifier on real data. We run the frozen model on WildChat completions with teacher forcing, which means the model is fed the true text at every position rather than its own guesses. Each position then gives a true hidden state hh and a true next token tt. The path bits of tt say which way hh should go at every node on its path.

Each node outputs a routing probability through a sigmoid, a squashing function that takes any number to a value between zero and one. It is trained with binary cross-entropy against the correct bit. That is the standard loss for a yes-or-no prediction, and it penalises confident wrong answers the most,

pℓ=σ ⁣(h⊤dℓ+bℓ),Lℓ=BCE ⁣(b^ℓ,bℓtrue). p_\ell = \sigma\!\left(h^{\top} d_\ell + b_\ell\right), \qquad \mathcal{L}_\ell = \mathrm{BCE}\!\left(\hat b_\ell, b_\ell^{\text{true}}\right).

Only the decision vectors move. The embeddings and the transformer stay as they were. The effect is to take hyperplanes that are right for Gaussian noise around embeddings and nudge them to where the real hidden states fall, weighted by how often each token actually occurs.

The sigmoids also give the tree a probability distribution. For a token kk with path bits (b1,…,bL)(b_1, \dots, b_L),

p(k)=∏ℓ=1Lpℓ bℓ (1−pℓ)1−bℓ, p(k) = \prod_{\ell=1}^{L} p_\ell^{\,b_\ell}\,(1 - p_\ell)^{1 - b_\ell},

the product along the path of the probability of each turn taken. At every node the two children's probabilities sum to one, so summing p(k)p(k) over all leaves gives one. This is a valid distribution over the vocabulary. It is what hierarchical softmax has always done, hierarchical softmax being the older idea of replacing one big softmax with a tree of small decisions.

Stopping early at depth l<Ll < L and handing the leaf to the original head is different. The original head's softmax over the leaf's tokens is normalised over the leaf, not over the vocabulary. So the result is a truncated distribution, and it is not the base model's softmax.

Perplexity is the standard measure of how surprised a model is by the true text, and lower is better. Perplexities computed from the truncated distribution rise with depth because truncation removes probability mass. They say something about routing quality, but they are not comparable to the base model's perplexity and we do not use them that way.

Beams

Greedy routing follows one branch at every node. The failure that produces is geometric. A hidden state that sits close to one of the hyperplanes on its path has a small margin there, so a small perturbation puts it on the wrong side. After that every later decision is made in the wrong subtree and the correct token cannot be recovered.

The tokens most at risk are the ones near a partition boundary, and the dense head would have had no trouble with them. Beam routing keeps the top kk paths by cumulative routing probability at every level instead of one. It then scores the union of the tokens under all kk reached nodes. A token one partition over is now in the candidate set as long as its path stayed among the kk most probable.

The cost is kk times the candidates. A beam of kk at depth ll scores about kV/2lkV/2^{l} tokens, which is why doubling the beam and going one level deeper leaves the projection cost roughly where it was.

The sweep over depths 0 to 17 and beams 1 to 16 shows three things. Perplexity rises steadily with depth and hardly depends on beam width, so it is the truncation that costs probability mass, not the greedy choice. The speedup of the projection grows roughly exponentially with depth, as the formula says it should, and wider beams pull it down in proportion to the candidates they add. And beam routing recovers most of the top-1 accuracy that depth alone gives up, at a fixed speed.

Results

Everything is on Gemma 3 270M-IT with a depth-18 tree over its 262,144 tokens. The decision vectors train with next-token supervision on WildChat, meaning the correct bit at each node comes from the true next token. Sequence length is 512, batch size 16, 5 epochs, with AdamW at a learning rate of 3×10−43 \times 10^{-4}. The data is a 90k/5k train and validation split, evaluated every 1,000 steps.

Those settings need unpacking. Sequence length is how many tokens each training example holds. Batch size is how many examples are averaged into one update of the decision vectors, and an epoch is one pass through the whole training set. The learning rate is the size of each update step. The split means 90,000 conversations to train on and 5,000 held back to check progress.

Timings are on CPU with 100 warm-up and 1,000 timed iterations per setting. Top-1 is next-token accuracy, how often the most likely token is the true one, and the dense head itself scores 78.75%.

settingdepthtop-1projection ms/tokenrouting ms/token
beam 120.6241.160.030
beam 230.7191.140.031
beam 440.7461.320.033
beam 850.7621.160.035
beam 1660.7681.150.048
dense head–0.78810.95–

Each row doubles the beam and goes one level deeper, so the candidate count is about the same across rows. The projection column barely moves while top-1 climbs from 62.4% to 76.8%. That is the cleanest view of what beams buy.

At depth 4 with beam 4 on four CPU threads the whole output stage, routing included, drops from 15.33 to 1.91 ms per token, which is the 8.04 times. The routing runs in one fused kernel, a single piece of code that does all the levels in one pass, and it stays under 0.1 ms at every depth and beam. So routing is never the bottleneck.

Teacher-forced decoding of the full model goes from 61.08 to 49.11 ms per token, which is 1.24 times. The transformer forward pass is 51.29 ms of that on its own and nothing here touches it. On eight threads the same operating point gives 1.26 times.

A router trained on WildChat keeps 95.8% of the dense head's top-1 at depth 4 on held-out WildChat. On FineWeb-EDU, educational web pages that look nothing like chat logs, it keeps the same 95.8%, even though the dense model's own top-1 there is 31.3% instead of 74.0%. At depth 17 the retained fractions are 78.8% and 79.5%. The fraction retained travels across domains even when absolute difficulty does not, which is what you would hope for from hyperplanes fitted to the shape of the embedding space rather than to a corpus.

projection cost against top-1 accuracy, Gemma 3 270M on WildChateach curve is one beam width · points are depths 0 to 17 · the dense head sits at 10.9 ms and 78.75%0.40.50.60.70.80.01 ms0.1110beam 1beam 4beam 16dense headprojection-only ms per token on CPU, log scale · routing itself stays under 0.1 ms at every depth
Moving down a curve is going deeper in the tree. Each level cuts the projection cost roughly in half and gives up a little accuracy. Wider beams keep more of the accuracy at the same depth and pay for it in candidates scored. Depth 4 with beam 4 is the point we quote, 1.32 ms against 10.9 and 74.6% against 78.75%.

What it does not say

The result means that the head of a language model can be replaced after training, without touching the model, by a sequence of hyperplane decisions. The directions of those hyperplanes follow from a tail bound and a change of coordinates, and the depth of the sequence can be left to whoever deploys it. The 8.04 times is on the isolated output stage. On the whole decode step for this model it is 1.24 times, because for a 270M model on CPU the transformer body is still most of the step.

What stands is that the dense head can be swapped for eighteen hyperplane decisions after training, with the depth left as a dial for whoever deploys it.

References

  1. Morin and Bengio, Hierarchical probabilistic neural network language model, AISTATS, 2005.
  2. Mnih and Hinton, A scalable hierarchical distributed language model, NeurIPS, 2008.
  3. Grave et al., Efficient softmax approximation for GPUs, 2017.
  4. Fisher, The use of multiple measurements in taxonomic problems, Annals of Human Genetics, 1936.
  5. Ethayarajh, How contextual are contextualized word representations?, 2019.
  6. Mu, Bhat and Viswanath, All-but-the-top: simple and effective postprocessing for word representations, 2017.
  7. Rudman and Eickhoff, Stable anisotropic regularization, 2024.
  8. Gemma Team, Gemma 3 technical report, 2025.
  9. Zhao et al., WildChat: 1M ChatGPT interaction logs in the wild, 2024.