--- library_name: transformers pipeline_tag: text-generation license: apache-2.0 tags: - llm - speculative-decoding - long-context - acceleration - qwen2 ---
*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](https://huggingface.co/TokenSwift/TokenSwift-QwQ-32B) with 3 Γ acceleration. Check out [inference guide](#inference) for deployment.
- **2025.2.28**: π₯π₯Relase model for finetuned [DeepSeek-R1-Distill-Qwen-32B](https://huggingface.co/TokenSwift/TokenSwift-DeepSeek-R1-Distill-Qwen-32B) with 3 Γ acceleration. Check out [inference guide](#inference) 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
```bash
pip install tokenswift
```
#### Method 2: From the source (recommended)
```bash
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](https://huggingface.co/TokenSwift/TokenSwift-Yarn-Llama-2-7b-128k) |
| TokenSwift-Llama-3.1-8B | [HuggingFace](https://huggingface.co/TokenSwift/TokenSwift-Llama-3.1-8B) |
| TokenSwift-Qwen2.5-1.5B | [HuggingFace](https://huggingface.co/TokenSwift/TokenSwift-Qwen2.5-1.5B) |
| TokenSwift-Qwen2.5-7B | [HuggingFace](https://huggingface.co/TokenSwift/TokenSwift-Qwen2.5-7B) |
| TokenSwift-Qwen2.5-14B | [HuggingFace](https://huggingface.co/TokenSwift/TokenSwift-Qwen2.5-14B) |
| TokenSwift-DeepSeek-R1-Distill-Qwen-32B | [HuggingFace](https://huggingface.co/TokenSwift/TokenSwift-DeepSeek-R1-Distill-Qwen-32B) |
| TokenSwift-QwQ-32B | [HuggingFace](https://huggingface.co/TokenSwift/TokenSwift-QwQ-32B) |
### 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.
```python
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:
```bash
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