Skip to main content

Overview

Qwen models support extended context lengths up to 32K tokens, enabling processing of long documents, extensive conversations, and large codebases. Different model sizes support different context lengths:

Context Extension Techniques

Qwen employs several advanced techniques to extend context length effectively:

NTK-Aware Interpolation

NTK (Neural Tangent Kernel) aware interpolation adapts the positional encoding to longer sequences without degrading performance on shorter sequences.

Window Attention

Window attention mechanisms allow the model to efficiently process longer sequences by focusing on relevant segments.

LogN Attention Scaling

Logarithmic scaling of attention scores helps maintain stable training and inference across different context lengths.

RoPE with Extended Base

For Qwen-72B, we adapt Rotary Position Embeddings (RoPE) with a larger rotary base to support 32K tokens:

Perplexity Performance

We evaluated Qwen models on the arXiv dataset with different context lengths:
Qwen-7B maintains strong performance up to 32K tokens with minimal perplexity increase.

Long Context Understanding Evaluation

Qwen-72B-Chat was evaluated on L-Eval benchmark for long text understanding:
Qwen-72B-Chat demonstrates excellent information retrieval across all positions within its 32K context window, proving its robust long context capabilities.

Using Long Context in Practice

Processing Long Documents

Multi-Document Analysis

Extended Conversations

Code Analysis

Memory Optimization for Long Context

KV Cache Quantization

Reduce memory usage when processing long contexts:
Memory Savings with KV Cache Quantization:

Batch Size Optimization

Best Practices for Long Context

Chunk Strategically

For extremely long documents, chunk logically and process with overlap

Use Summarization

Summarize earlier parts of long conversations to manage context

Monitor Token Count

Track token usage to avoid hitting context limits

Enable KV Quantization

Use KV cache quantization for longer sequences

Token Management

Performance Considerations

Important Notes:
  • Memory: Long contexts require significant GPU memory. Consider using multiple GPUs or KV cache quantization
  • Speed: Generation speed decreases with longer contexts due to attention computation
  • Quality: While Qwen maintains strong performance at long contexts, accuracy may vary by task
  • Flash Attention: Using Flash Attention can significantly improve speed and memory efficiency

Supported Models

Long context support by model:
  • Qwen-1.8B: 32K tokens
  • Qwen-7B: 32K tokens (extended from 8K)
  • ⚠️ Qwen-14B: 8K tokens
  • Qwen-72B: 32K tokens

Next Steps

System Prompts

Use system prompts to guide long context processing

Agent Building

Build agents that leverage long context