library_name: transformers
pipeline_tag: text-generation
license: apache-2.0
tags:
- llm
- speculative-decoding
- long-context
- acceleration
- qwen2
TokenSwift: Lossless Acceleration of Ultra Long Sequence Generation
This repository contains a model checkpoint of the TokenSwift framework, specifically TokenSwift-QwQ-32B, designed for accelerating Large Language Models (LLMs).
TokenSwift is a novel framework designed to substantially accelerate the generation process of ultra-long sequences, up to 100K tokens, while maintaining the target model's inherent quality.
Model Details
Model Description
Generating ultra-long sequences with large language models (LLMs) has become increasingly crucial but remains a highly time-intensive task, particularly for sequences up to 100K tokens. While traditional speculative decoding methods exist, simply extending their generation limits fails to accelerate the process and can be detrimental. Through an in-depth analysis, we identify three major challenges hindering efficient generation: frequent model reloading, dynamic key-value (KV) management and repetitive generation.
To address these issues, we introduce TOKENSWIFT, a novel framework designed to substantially accelerate the generation process of ultra-long sequences while maintaining the target model's inherent quality. Experimental results demonstrate that TOKENSWIFT achieves over 3 times speedup across models of varying scales (1.5B, 7B, 8B, 14B) and architectures (MHA, GQA). This acceleration translates to hours of time savings for ultra-long sequence generation, establishing TOKENSWIFT as a scalable and effective solution at unprecedented lengths.
✨ Key Highlights
| Highlights | Description | Emoji |
|---|---|---|
| ⚡ Speed | 3× faster than vanilla Transformers | ⏩ |
| 🎯 Lossless | Matches original model's output quality | ✅ |
| 📈 Scalability | Linear time complexity for 100K+ sequences | 📏 |
| 🛠️ Plug & Play | Works with most HuggingFace models | 🤗 |
Framework Illustration
Illustration of TOKENSWIFT Framework. First, target model (LLM) with partial KV cache and three linear layers outputs 4 logits in a single forward pass. Tree-based attention is then applied to construct candidate tokens. Secondly, top-k candidate 4-grams are retrieved accordingly. These candidates compose draft tokens, which are fed into the LLM with full KV cache to generate target tokens. The verification is performed by checking if draft tokens match exactly with target tokens. Finally, we randomly select one of the longest valid draft tokens, and update n-gram table and KV cache accordingly.
This repository contains:
- ✅ 100% reproducibility for all experiments
- 📊 Benchmark scripts for sequence lengths: 20K/40K/60K/80K/100K
- 🤖 Pre-trained model adapters for Any Structure
Visualization of our acceleration performance vs. baseline methods
✨ News
- 2025.5.2: 🔥🔥 Our Paper is accepted by ICML 2025!
- 2025.3.19: 🔥🔥Relase model for finetuned QwQ-32B with 3 × acceleration. Check out inference guide for deployment.
- 2025.2.28: 🔥🔥Relase model for finetuned DeepSeek-R1-Distill-Qwen-32B with 3 × acceleration. Check out inference guide for deployment.
- 2025.2.27: Paper Release on Arxiv.
How to Get Started with the Model
Installation
You can install the tokenswift library via pip or from source.
Method 1: With pip
pip install tokenswift
Method 2: From the source (recommended)
git clone https://github.com/bigai-nlco/TokenSwift.git
cd TokenSwift
conda create -n tokenswift python=3.11
conda activate tokenswift
conda install nvidia::cuda-nvcc
pip install -r requirements.txt
pip install https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.4cxx11abiFALSE-cp311-cp311-linux_x86_64.whl
Models Download
| Model Name | Download Link |
|---|---|
| TokenSwift-Yarn-Llama-2-7b-128k | HuggingFace |
| TokenSwift-Llama-3.1-8B | HuggingFace |
| TokenSwift-Qwen2.5-1.5B | HuggingFace |
| TokenSwift-Qwen2.5-7B | HuggingFace |
| TokenSwift-Qwen2.5-14B | HuggingFace |
| TokenSwift-DeepSeek-R1-Distill-Qwen-32B | HuggingFace |
| TokenSwift-QwQ-32B | HuggingFace |
Inference / Sample Usage
Python via transformers
You can easily use this model with the Hugging Face transformers library. Ensure you have transformers and torch installed.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "TokenSwift/TokenSwift-QwQ-32B" # This model
# The base model may vary depending on the specific TokenSwift checkpoint.
# For TokenSwift-QwQ-32B, the base model is Qwen/QwQ-32B.
# You might need to adjust the base model name for other TokenSwift variants.
# Load tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, device_map="auto")
# Example prompt for long sequence generation
prompt = "In a realm far away, where magic intertwined with technology, a young apprentice named Elara discovered an ancient artifact. It pulsed with an ethereal glow, hinting at powers beyond her wildest dreams. As she touched its surface, a surge of energy coursed through her, revealing forgotten prophecies and a destiny she never imagined. The artifact hummed, a low vibration echoing through the silent chamber, drawing her deeper into its mysteries. Outside, the world continued oblivious, but within the confines of that room, Elara's life was irrevocably changed. She knew then that her journey had just begun, a path fraught with peril and untold wonders. This ancient power, once dormant, was now awakening within her, demanding to be understood and mastered. The weight of this new knowledge settled upon her shoulders, a burden and a blessing. She was no longer just an apprentice; she was a vessel for something ancient and powerful, a key to unlocking secrets long buried. The air crackled with anticipation, reflecting the storm brewing within her soul. Her fingers traced the intricate carvings on the artifact, each line telling a story of a forgotten era. She closed her eyes, trying to absorb every detail, every whisper of its past. The chamber itself seemed to breathe with her, a silent witness to her transformation. It was a moment of profound realization, a turning point that would shape the very fabric of her existence. The hum intensified, a symphony of awakened power. She felt the pull of a greater purpose, a call to adventure that she could not ignore. The journey ahead would be long and arduous, but she was ready. She would embrace her destiny, whatever it held. The last rays of sunlight pierced through a narrow slit in the ceiling, illuminating the dust motes dancing in the air, oblivious to the momentous change that had just occurred. The dust danced, each speck a tiny universe, unburdened by destiny or ancient prophecies. Elara, however, was keenly aware of the weight of her newfound path. She looked at the artifact, then back at the chamber, a new resolve hardening her gaze. The ancient magic flowed through her veins, a thrilling, terrifying current. She took a deep breath, and began to walk towards the exit, her steps firm and purposeful. Her journey was indeed just beginning, and the world was about to feel the ripple effect of her awakening. Her mind raced with possibilities and dangers, each step a testament to her courage. The artifact, now a part of her, guided her silently. She emerged from the chamber, transformed, into a world that would soon reckon with her power. The wind whispered secrets through the trees outside, and a single leaf detached itself, spiraling down to the forest floor, foretelling a storm."
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device)
# Generate text
outputs = model.generate(input_ids, max_new_tokens=100)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
Command Line Interface
Take LLaMA3.1-8B as an example:
torchrun --master-port 1111 --nproc_per_node=1 main.py \
--model_type llama3_1 \
--ckpt_path your_checkpoint_path \
--prefill_len 4096 \
--retrival_max_budget 4096 \
--gen_len 102400 \
--gamma 4 \
--min_p 0.1 \
--temperature 1.0 \
--tree_decoding \
--ngram_topk 20 \
--penalty 1.2 \
--penalty_length 1024 \
--prompt_id 0
<NOTE: Modify the data and model path>
For other models, you can run the scripts in infer_scripts/ folder. For example:
bash infer_scripts/r1_qwen_32b.sh
Training Guide (Optional)
Datasets Download
From the PG-19 training set, data larger than 8K are filtered out according to different tokenizer.
Or download processed training datasets from llama2-pg19, llama3.1-pg19, qwen2.5-pg19.
How to Train
Take LLaMA3.1-8B as an example:
torchrun --master-port 1111 --nproc_per_node=4 train/train_legacy.py \
--model_name_or_path /your_model_path/Meta-Llama-3.1-8B \
--llama_type llama3_1 \
--data_path /your_data_path/llama3_1_pg19_8k_data \
--output_dir /your_checkpoint_path/adapter_ckpts_llama3_1 \
--max_steps 200 \
--per_device_train_batch_size 3 \
--gradient_accumulation_steps 10 \
--save_steps 200 \
--learning_rate 5e-3 \
--weight_decay 0.1 \
--warmup_steps 50 \
--lr_scheduler_type cosine \
--logging_steps 5 \
--report_to tensorboard \
--bf16 True \
--medusa_heads 3 \
--remove-unused-columns false
<NOTE: Modify the data and model path>
For other models, you can run the scripts in train/scripts/ folder. For example:
cd train
bash scripts/train_R1_qwen2_5_32b.sh
Citation
If you are interested in our work or use our library, please cite:
@misc{tokenswift,
title={From Hours to Minutes: Lossless Acceleration of Ultra Long Sequence Generation up to 100K Tokens},
author={Tong Wu and Junzhe Shen and Zixia Jia and Yuxuan Wang and Zilong Zheng},
year={2025},
eprint={2502.18890},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2502.18890},
}
Acknowledgment
This codebase is influenced by remarkable projects from the LLM community, including Medusa and TriForce.