The Mamba in the Llama: Distilling and Accelerating Hybrid Models

Junxiong Wang, Daniele Paliotta, Avner May, Alexander M. Rush, Tri Dao

TL;DR

Training linear RNNs like Mamba from scratch to match Transformer performance is incredibly expensive, requiring trillions of tokens. This paper introduces a breakthrough distillation method that directly initializes Mamba layers using pretrained Transformer attention weights, creating high-performing hybrid models with minimal compute. Combined with a novel hardware-aware speculative decoding algorithm, these hybrid models achieve up to a 2.6x inference speedup while maintaining the generation quality of the original Transformer.

What Problem Does This Paper Address?

While Transformers dominate the large language model (LLM) landscape, they suffer from a massive bottleneck during inference: the Key-Value (KV) cache. As sequence lengths grow, the memory required to store this cache scales quadratically, making long-context generation prohibitively slow and resource-intensive.

Linear State Space Models (SSMs) and linear RNNs, like Mamba, offer a promising alternative with $O(1)$ inference throughput and no KV cache requirements. However, scaling them up from scratch requires massive computational power and trillions of tokens. The authors of this paper ask a compelling question: Can we take an existing, highly optimized Transformer (like Llama-3) and cheaply convert it into an efficient Mamba-based hybrid model?

Methods

The authors propose a recipe to transform a pretrained Transformer into a hybrid Mamba model using limited academic GPU resources:

  1. Attention-to-Mamba Initialization: By exploiting the mathematical relationship between linearized attention and linear RNNs, the authors directly map the Transformer's $Q, K, V$ projection weights to Mamba’s input and output parameters ($C, B, x$). The original, knowledge-rich MLP layers are kept frozen during the initial phase.
  2. Stepwise Hybrid Distillation: Instead of completely removing all attention mechanisms, the authors create hybrid models by progressively replacing attention layers with Mamba blocks (e.g., keeping 50% or 25% of the attention layers).
  3. Multistage Alignment Distillation: To recover performance, the student model undergoes a three-stage post-training pipeline: progressive distillation using teacher pseudo-labels, Supervised Fine-Tuning (SFT), and Direct Preference Optimization (DPO) to align the student's outputs with the teacher's preferences.
Figure 1: Transferring Transformer to Mamba. Weights, in orange, are initialized from the Transformer (Linear projections for Q, K, and V are initialized using linear projection for C, B, and X respectively). We replace individual attention heads with Mamba heads, and then finetune Mamba blocks while freezing the MLP blocks. Shapes are kept mainly the same. Weights in green are added. New parameters are introduced for the learned A and ∆parameters.

Additionally, speculative decoding for RNNs is notoriously difficult because caching hidden states ($h_t$) introduces massive memory overhead. The authors design a hardware-aware multi-step speculative decoding algorithm with a custom GPU kernel that verifies multiple tokens in parallel and rewinds states lazily without materializing intermediate states off fast GPU memory.

Figure 2: Multi-Step RNN Speculative Decoding. Left (top): The draft model generates the set of blue draft tokens sequentially. The draft tokens are then verified. Right (top): Verification uses the multistep kernel, without materializing the intermediate states. The last token is rejected and replaced with the true best token. Note, that even though more tokens are generated we cannot advance the hidden state cache. Left (bottom) The draft model can now generate more blue draft tokens from the current tokens, resulting in six total. Right (bottom) When the new draft is verified, the multi-step kernel returns both the hidden state after the yellow token and the final hidden state, since verification will fall between those positions.

Datasets

The models were distilled and evaluated using several open-source datasets:

  • Distillation & Fine-Tuning: UltraChat, UltraFeedback, GenQA, InfinityInstruct, OpenHermes 2.5, and SimPO.
  • Evaluation Benchmarks: MT-Bench, AlpacaEval 2, GSM8K, CRUX, and the LM Evaluation Harness (including MMLU, HellaSwag, ARC, and TruthfulQA).
  • Long-Context Evaluation: Needle-in-a-Haystack.

Key Insights and Ideas

  • Weight Reuse is Highly Effective: Pretrained Transformer attention weights contain structural priors that can directly seed a linear RNN. This eliminates the need for expensive pretraining, requiring only 20 billion tokens of distillation compared to the trillions needed from scratch.
  • Hybrids Offer the Best of Both Worlds: Retaining a fraction of attention layers (e.g., 25% to 50%) preserves the complex context-matching capabilities of Transformers while significantly reducing the memory footprint of the KV cache.
  • Natural Length Extrapolation: Surprisingly, even though the distillation process only utilized a 2k sequence length, the resulting hybrid models naturally extrapolated to show near-perfect accuracy on Needle-in-a-Haystack tests up to 38k tokens—20x the training length.
  • DPO as a Distillation Objective: This work represents one of the first successful applications of Direct Preference Optimization (DPO) specifically used to close the alignment gap between a student model and its teacher.

Key Results

  • State-of-the-Art Hybrid Performance: The top-performing model, distilled from Llama3-8B-Instruct (retaining 50% attention), achieved a 29.61% length-controlled win rate on AlpacaEval 2 against GPT-4 and a 7.35 on MT-Bench, outperforming open-source Mamba models trained from scratch on trillions of tokens.
  • Substantial Inference Speedups: The hardware-aware speculative decoding algorithm delivered a 2.1x to 2.6x speedup for pure Mamba models on NVIDIA 3090 and H100 GPUs, and over a 1.8x speedup when applied to hybrid architectures.

Limitations and Future Work

  • The Pure Mamba Gap: While hybrid models perform exceptionally well, completely removing all attention layers (0% attention / pure Mamba) still results in a significant drop in downstream task accuracy. Completely closing this gap remains an open challenge.
  • Draft Model Bottlenecks: In speculative decoding, the draft models inherit the massive embedding tables of their parent models (like Llama 3), making them relatively large. The authors note that developing smaller, more compact draft models is a critical next step to unlocking even higher throughput.

Summary updated

Abstract

Linear RNN architectures, like Mamba, can be competitive with Transformer models in language modeling while having advantageous deployment characteristics. Given the focus on training large-scale Transformer models, we consider the challenge of converting these pretrained models for deployment. We demonstrate that it is feasible to distill large Transformers into linear RNNs by reusing the linear projection weights from attention layers with academic GPU resources. The resulting hybrid model, which incorporates a quarter of the attention layers, achieves performance comparable to the original Transformer in chat benchmarks and outperforms open-source hybrid Mamba models trained from scratch with trillions of tokens in both chat benchmarks and general benchmarks. Moreover, we introduce a hardware-aware speculative decoding algorithm that accelerates the inference speed of Mamba and hybrid models. Overall we show how, with limited computation resources, we can remove many of the original attention layers and generate from the resulting model more efficiently. Our top-performing model, distilled from Llama3-8B-Instruct, achieves a 29.61 length-controlled win rate on AlpacaEval 2 against GPT-4 and 7.35 on MT-Bench, surpassing the best 8B scale instruction-tuned linear RNN model. We also find that the distilled model has natural length extrapolation, showing almost perfect accuracy in the needle-in-a-haystack test at 20x the distillation length. Code and pre-trained checkpoints are open-sourced at https://github.com/jxiw/MambaInLlama and https://github.com/itsdaniele/speculative_mamba.
BibTeX
@inproceedings{wang2024mamba,
  author = {Junxiong Wang and Daniele Paliotta and Avner May and Alexander M. Rush and Tri Dao},
  title = {{The Mamba in the Llama: Distilling and Accelerating Hybrid Models}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2024},
  url = {https://openreview.net/forum?id=uAzhODjALU},
}
Figure