LLM LM Head Optimization: The Real Bottleneck, Common Misconceptions, and How to Choose

    The LM head—also called the language model output head or output projection layer—is frequently misunderstood. This article corrects two popular misconceptions: that it creates an information bottleneck directly tied to hallucination, and that some kind of "latent-space probe head" is the answer. It explains what the LM head actually does, why the softmax bottleneck is mathematically real yet rarely matters in mainstream models, and why the genuine constraint is engineering overhead—a large share of parameters, oversized logits tensors during training, and a full-vocabulary pass on every decode step. You will find a method-selection table, low-risk-first recommendations (weight tying, output-layer quantization, chunked or fused cross-entropy, shared drafter), guidance on measuring memory for chunked cross-entropy, options for vocabulary pruning, sampling approximations, inference-side coordination, and how to validate whether an optimization actually works.

    When it comes to the LM head of large language models, two claims circulate widely. One says it creates an information bottleneck and is even directly responsible for hallucination. The other says the problem can be solved with some kind of “latent-space probe head.”

    Both claims need correcting. First, the mathematical softmax bottleneck does exist, but in mainstream LLMs it rarely becomes a practical constraint, and it should not be equated with hallucination. Second, the “latent-space probe head” idea often mistakes the drafter (draft model) in speculative decoding for an answer probe. The drafter’s job is not to read a probed answer out of the latent space—it generates candidate tokens for the target model. Some approaches (for example, DSpark and similar ones) handle the lm_head precisely by reusing the target model’s output projection and keeping it frozen rather than training it.

    The LM head bottleneck that actually deserves attention is not expressiveness but engineering cost: a high share of parameters, large logits tensors during training, and a full-vocabulary pass on every decode step. Understanding this is what lets you pick the right optimization path.

    What Does the LM Head Actually Do?

    After the Transformer backbone produces the final-layer hidden state h ∈ R^d, the LM head uses a weight matrix W_o ∈ R^{V×d} to project the hidden state into vocab-sized logits, which softmax then turns into the probability distribution over the next token:

    1. logits = W_o @ h # [V]
    2. P(w | h) = softmax(logits)

    This single expression maps to two very different engineering constraints:

    • During training: logits must be computed for all token positions across the batch at once, and gradients must flow back through them.
    • During inference decoding: logits are computed once per generated token, the workload is typically memory-bandwidth bound, and the batch is usually small.

    As a result, the LM head’s optimization goals are not unified. Training cares more about logits-tensor memory and compute efficiency; inference cares more about memory bandwidth, latency, and throughput.

    Does the LM Head Cause Hallucination?

    This is one of the most common questions, and the answer is no—at least it cannot be attributed directly.

    First, the logits distribution can retain multiple candidate peaks internally. The model can hold preferences for several possible answers before and within the output layer, and which token is finally emitted still depends on post-processing such as sampling strategy, temperature, Top-K, Top-P, and repetition penalty. So a low-rank or softmax structure does not necessarily mean “the model can only say one answer.”

    Second, hallucination is more closely tied to the following factors:

    • Training-data quality, knowledge coverage, and domain distribution;
    • The degree of alignment and instruction-following ability;
    • Decoding strategy, such as temperature, repetition penalty, and sampling truncation;
    • How context is organized, the quality of retrieval results, and prompt design;
    • Model size, training objectives, and the post-training pipeline.

    Attributing hallucination to the LM head tends to steer engineering effort toward the wrong optimization target. The safer approach is to first verify whether the LM head is genuinely a bottleneck, and only then decide whether to change the output structure.

    The Softmax Bottleneck: Mathematically Real, Rarely Bites in Practice

    The Rank Limitation

    Classic research around 2017—Breaking the Softmax Bottleneck (Yang et al., 2017; later published at ICLR 2018)—pointed out that the log-probability matrix of a language model’s output can be written as the product of a hidden-state matrix and the transpose of the vocabulary matrix. Its rank is therefore bounded by the hidden-state dimension:

    1. rank(log P) = rank(H @ W_o^T) <= min(N, d, V) = d

    Real language word–context probability matrices are typically high-rank, whereas the model’s output is at most rank d. The more training data and the longer the sequences, the more pronounced this structural gap becomes. This is the so-called softmax bottleneck.

    That study also proposed a fix: add a residual network F(·) after the hidden state, then multiply by the vocabulary matrix, expanding the expressiveness to:

    1. rank(F(H) @ W_o^T) <= d × (L + 1)

    where L is the number of residual-network layers. Later work has re-characterized this bottleneck from angles such as mixed softmax, sigmoid substitution, sparse output, and combinations of high-rank and low-rank structures.

    Why Is the Practical Impact Limited?

    The often-cited claim that “only 13 of 150 open-source models have tokens that can never be selected” commonly appears in follow-up empirical summaries or reproduction materials. Because different papers may differ in model versions, vocabulary sizes, token-frequency thresholds, and evaluation corpora, this article does not recommend treating it as a strict law, but rather as an engineering rule-of-thumb clue.

    A more reliable judgment method is to sample your own model and corpus to check whether there are tokens that the model “never internally assigns the highest probability,” and to observe the word frequency and business importance of those tokens. If the issue is concentrated in long-tail words and has minimal impact on evaluation metrics, prioritize optimizing engineering overhead rather than rushing to change the output structure.

    The Real Bottleneck: Parameters, Memory, and Bandwidth

    The LM head has three real problems.

    1. A High Share of Parameters

    Take a configuration with a vocabulary of roughly 128,000 and a hidden dimension of 4096:

    1. W_o = 128000 × 4096 ≈ 524 million parameters

    In a model on the order of 8 billion parameters, this single layer accounts for over 6%. Stored in half precision, it takes about 1 GB; during mixed-precision training, once gradients, optimizer states, and temporary buffers are counted, the actual footprint is even higher.

    2. Huge Logits Tensors During Training

    During training, logits must be materialized as [batch × seq, vocab]. For a sequence containing 2048 tokens, a single logits tensor in half precision is about:

    1. 2048 × 128000 × 2 B ≈ 0.5 GB

    Run 32 such sequences in parallel, and just the logits exceed 16 GB. In long-context scenarios, a single sequence of 128,000 tokens produces one logits tensor of roughly 30 GB in half precision—possibly larger than the model weights themselves. If forward activations are also retained for backpropagation, the cost grows further.

    3. Heavy Memory Access and Throughput Pressure During Inference

    At decode time, every generated token requires a pass over the hidden state and the full vocabulary. The larger the vocabulary and the smaller the model, the larger the output layer’s share. The output layer is usually a full, dense computation, hard to avoid through conventional sparsification. Quantization can only reduce weight-reading and storage overhead; it cannot eliminate the softmax work of traversing the entire vocabulary.

    How to Choose Output-Layer Optimizations: A Selection Table

    Method Main benefit Main risk Suitable scenario Rollback cost Metrics to validate
    Weight tying Reduces output-layer parameters Conflict when input embeddings are strongly fine-tuned LMs with consistent input/output distributions Low Perplexity, embedding anomalies
    Chunked cross-entropy Lowers peak training memory Poor implementation hurts numerics Long-sequence, large-vocabulary training Very low Peak memory, loss alignment
    Output-layer quantization Reduces bandwidth and storage Precision loss, operator support Inference deployment, memory-constrained Low–medium Perplexity, task accuracy
    Low-rank factorization Reduces parameters and memory access Reduced expressiveness Parameter-constrained, very large vocabulary Medium Perplexity, long-tail word performance
    Vocabulary pruning Linearly reduces memory and compute Missing business/long-tail words Fixed domains with controllable input Medium Coverage, OOV rate
    Sampling approximation Training speedup Introduces bias or variance Very-large-vocabulary training Medium Loss curve, task metrics
    Inference hot vocabulary Reduces decode latency May wrongly drop contextually necessary words Concentrated high-frequency words, online serving Low TTFT, tokens/s
    Shared drafter Reduces extra speculative-decoding parameters Target-model changes require retraining Already using speculative decoding Medium Acceptance rate, latency

    Overall priority: land low-risk, high-reward options first—for example chunked/fused cross-entropy, weight tying, output-layer quantization, and shared drafter in speculative decoding. Then carefully evaluate structural changes such as low-rank factorization, vocabulary pruning, and hierarchical softmax.

    Low Risk First: Weight Tying and Output-Layer Quantization

    Weight Tying

    If input embeddings and the output distribution are highly consistent, you can bind the output projection to the input word embeddings:

    1. self.lm_head.weight = self.embedding.weight

    This reduces output-layer parameters. But note that when input embeddings are fine-tuned heavily, it is advisable to lower their learning rate and track weight decay separately, to avoid optimization conflicts introduced by the tying.

    Output-Layer Quantization

    Quantizing the output layer alone to INT8/FP8 can significantly compress weight bandwidth, which is especially effective at decode time. Two points to watch:

    • Quantization causes precision loss, so compare perplexity and task accuracy;
    • Quantization cannot eliminate the full softmax pass over the entire vocabulary; it mainly reduces weight-reading and storage overhead.

    How to Measure Memory for Chunked Cross-Entropy?

    The most direct training optimization is to change logits from “full materialization” to “chunked materialization.” The core idea: split by tokens and process only a small segment of hidden states at a time; compute logits within a block, immediately compute the loss, then release that block’s tensor.

    Below is a minimal runnable example. Dependencies: PyTorch >= 2.0, CUDA. The shape of hidden is [T, d], labels is [T], and W_o is [V, d]. The example assumes ignore_index = -100.

    1. # Dependencies: PyTorch >= 2.0, CUDA
    2. # hidden: [T, d], labels: [T], W_o: [V, d]
    3. # ignore_index = -100 in labels; if half precision overflows, switch to the framework's fused CE or explicit float32
    4. import torch
    5. def chunked_ce(hidden, labels, W_o, chunk_size=2048, ignore_index=-100):
    6. total_loss = 0.0
    7. valid_tokens = 0
    8. T = hidden.shape[0]
    9. for start in range(0, T, chunk_size):
    10. end = min(start + chunk_size, T)
    11. h = hidden[start:end]
    12. y = labels[start:end]
    13. mask = (y != ignore_index)
    14. if not mask.any():
    15. continue
    16. # Current block logits
    17. logits = h @ W_o.T
    18. # Promote to float32 for numerical stability; if the framework supports fused CE, prefer it
    19. logits = logits.float()
    20. # ignore_index cannot be gathered directly, so use 0 as a placeholder
    21. y_safe = torch.where(mask, y, torch.zeros_like(y))
    22. # log-sum-exp minus the target logit, avoiding the extra large tensor from log_softmax
    23. max_logits = logits.max(dim=-1).values
    24. logsumexp = max_logits + torch.log(
    25. torch.exp(logits - max_logits[:, None]).sum(dim=-1)
    26. )
    27. target_logits = logits.gather(1, y_safe[:, None]).squeeze(1)
    28. block_loss = (logsumexp - target_logits)[mask]
    29. total_loss = total_loss + block_loss.sum()
    30. valid_tokens = valid_tokens + mask.sum()
    31. del logits # Release this block's logits immediately
    32. return total_loss / valid_tokens.clamp_min(1)

    To measure memory, you can observe the peak before and after forward/backward:

    1. torch.cuda.reset_peak_memory_stats()
    2. loss = chunked_ce(hidden, labels, model.lm_head.weight, chunk_size=2048)
    3. loss.backward()
    4. print(torch.cuda.max_memory_allocated() / 1024 ** 3) # GB

    Tuning suggestions:

    • Start trying chunk_size from 1K to 4K;
    • Too small a block causes frequent kernel launches and lower memory-access utilization;
    • Too large a block fails to reduce peak memory;
    • If the framework provides a fused cross-entropy operator, prefer it, as it usually offers higher throughput;
    • The loss values from chunked CE and fused CE should be close or identical, which can be used to cross-check correctness.

    How to Choose Vocabulary Pruning?

    Vocabulary pruning is the most direct linear optimization: memory and compute drop roughly linearly with vocabulary size. But the risk is also clear, since pruned words may appear in evaluation sets or business inputs.

    Static Pruning

    Count word frequencies in the corpus, remove long-tail words, then retrain or continue training. Suitable for scenarios with stable input/output distributions and low-value long-tail words. Before launch, confirm:

    • Whether the evaluation set covers the pruned words;
    • Whether business text contains specialized terms, entity names, or code symbols;
    • Whether there is a fallback mechanism.

    Dynamic or Hot Vocabulary

    During training or inference, keep only the region where probability mass concentrates—for example, words within a Top-K or a cumulative-probability threshold—and sample with normalization over the pruned vocabulary. Suitable for scenarios with concentrated high-frequency words and latency sensitivity.

    Risks and Validation

    Recommended monitoring:

    • Trigger rate of pruned words;
    • Changes in perplexity;
    • Task metrics such as named-entity recognition, code completion, and long-form generation;
    • The share of garbled text, dropped characters, or off-topic answers in user feedback.

    If vocabulary pruning causes a clear drop in task accuracy, roll back first rather than piling on more complex patches.

    Sampling Approximation and Hierarchical Output

    When the cost of a full softmax is too high, sampling approximation is worth considering:

    • Importance sampling: sample negatives from a proposal distribution and use that distribution to correct for unbiasedness;
    • Hash-based approximate retrieval: use locality-sensitive hashing to quickly find similar candidate words;
    • Synthetic negative sampling: approximate the log-partition function with a few synthetic negative samples, with bias correction.

    These methods are more suited to training speedup than to unconditionally powering inference. They introduce bias or variance and require monitoring of the loss curve and downstream task metrics.

    In addition, hierarchical softmax or adaptive softmax can split a single V-way classification into a tree structure, reducing complexity from O(V) to about O(log V). The cost is multi-level lookups and branching at inference, a more complex implementation, and limited support for dynamic vocabularies.

    Sparse softmax variants such as sparsemax and α-entmax make the output itself sparse, which can support pruning-aware training and provide a basis for vocabulary pruning at inference.

    Inference-Side Coordination: Don’t Just Change the lm_head

    At inference, several angles can be optimized in coordination:

    • Dynamic vocabulary pruning: maintain a hot vocabulary based on context and historical hit statistics, and compute softmax only over that subset. This changes the target model the least, but if you use a drafter-type approach, it needs to be adjusted in sync.
    • Shared drafter: if you use speculative decoding, letting the drafter reuse the target model’s lm_head is one of the most direct parameter-saving options.
    • Output-layer quantization: paired with FP8/INT8 weight and activation schemes, it reduces memory-bandwidth pressure.
    • Prompt caching: for identical system prompts or identical prefixes, you can reuse the KV, hidden states, or reusable logits intermediate results produced during prefill. You cannot cache arbitrary sampling results unless the business allows fixed templates, a fixed seed, or deterministic decoding.
    • Post-processing: temperature, Top-K, Top-P, repetition penalty, and so on are all done after the logits, do not change the output layer itself, yet are the most direct means of controlling the output distribution.
    • Engineering implementation: if you use a third-party inference framework, prefer enabling its general capabilities—chunked/fused cross-entropy kernels, FP8/INT8 quantization, speculative decoding—and avoid custom implementations that diverge from upstream behavior.

    It must be emphasized: any change to the LM head ripples downstream. After fine-tuning the output layer, pruning the vocabulary, or quantizing the output layer, the drafter’s predicted distribution may become mismatched with it, requiring retraining of the draft head or recalibration.

    How to Validate Whether an Optimization Is Effective?

    1. First Confirm Whether the Bottleneck Is Real

    Sample and count the share of tokens that “never get the highest probability,” along with their word frequency. If the share is very low and concentrated in long-tail words, prioritize optimizing engineering overhead rather than rushing to change the structure.

    2. Effect Alignment

    On the same evaluation set, compare perplexity, task accuracy, and long-form generation quality before and after the optimization. For low-risk options, use the following as reference:

    • Keep the relative change in perplexity within about 1%;
    • Keep the drop in task accuracy within about 0.5 percentage points;
    • Ensure long-form generation shows no obvious repetition, truncation, or semantic drift;
    • The loss values from chunked cross-entropy and fused cross-entropy should be consistent or close.

    Structural options such as low-rank factorization, vocabulary pruning, and hierarchical softmax require stricter evaluation—for example, perplexity change, task accuracy, OOV rate, and long-tail word coverage.

    3. Resource Metrics

    Recommended to record:

    • tokens/s;
    • Time-to-first-token (TTFT);
    • Per-step decode time;
    • Peak memory via torch.cuda.max_memory_allocated();
    • Behavior at the target context length and batch size.

    Do not look only at “pretty numbers” from short sequences. Long-context scenarios are often where the LM head memory bottleneck is most pronounced.

    4. Rollback Plan

    Vocabulary pruning, low-rank factorization, speculative-decoding sharing, and dynamic hot vocabularies all change the output distribution and are possible changes to it. Before launch, keep a switch that can revert to the original lm_head in one step, and record the model version, vocabulary version, and inference parameters.

    Summary

    1. The mathematical softmax bottleneck is real, but in mainstream models it rarely bites and cannot be simply attributed to hallucination.
    2. The real LM head bottleneck is engineering overhead: a high parameter share, logits tensors during training that may exceed the weights in size, and a full-vocabulary pass for every token at decode time.
    3. Prioritize low-risk, high-reward options first: chunked/fused cross-entropy, weight tying, output-layer quantization, and shared drafter in speculative decoding.
    4. Structural changes require evaluation and rollback: low-rank factorization, vocabulary pruning, and hierarchical softmax change the output space the model can express, so you must let data speak.
    5. Look elsewhere for the cause of hallucination: mainly in data, alignment, decoding strategy, and context organization—do not simply blame the LM head.

    References and Notes

    • Yang et al., Breaking the Softmax Bottleneck, arXiv:1711.02903, 2017; later published at ICLR 2018.
    • Regarding the empirical claim that “only 13 of 150 open-source models have unreachable tokens,” different retellings may vary in model versions, vocabulary sizes, and frequency thresholds. For engineering deployment, it is advisable to re-measure and record the model list, vocabulary size, evaluation corpus, and threshold conditions.
    • This article uses cautious wording when describing speculative-decoding approaches such as DSpark: some approaches do adopt the practice of the drafter reusing the target model’s lm_head and keeping it frozen, but specific implementations may differ.