Overview
Batch inference allows you to process multiple prompts simultaneously, significantly improving throughput. With flash attention enabled, Qwen can achieve up to 40% speedup with batch inference compared to sequential processing.Prerequisites
1
Install Flash Attention
For optimal batch inference performance, install flash-attention:
2
Install Dependencies
Ensure you have the required packages:
Flash attention 2 is now supported and provides the best performance for batch inference.
Basic Batch Inference
Here’s a complete example of batch inference with Qwen:Key Configuration Details
Tokenizer Configuration
Tokenizer Configuration
For batch inference, you must configure the tokenizer with distinct pad and eos tokens:Why left padding? Causal language models generate from left to right. Left padding ensures that the actual content is right-aligned, which is crucial for proper attention mask generation.
Model Configuration
Model Configuration
Pass the pad_token_id to the model and generation config:
Context Preparation
Context Preparation
Use
make_context to format each query properly:Performance Optimization
Batch Size Selection
Choose batch size based on your GPU memory and sequence length:Dynamic Batching
Process queries in batches dynamically:Comparing Single vs Batch
Let’s compare single and batch inference:Advanced: Mixed-Length Batching
Handle queries of very different lengths efficiently:Memory Management
Monitor and optimize memory usage:Performance Benchmarks
Typical speedups with batch inference (with flash attention):Maximum speedup of ~40% is typically achieved with batch sizes of 8-16. Larger batches may not provide additional speedup due to GPU saturation.
Troubleshooting
Out of Memory Error
Out of Memory Error
Reduce batch size or sequence length:
Incorrect Outputs
Incorrect Outputs
Ensure you’re using left padding:
No Speed Improvement
No Speed Improvement
Check that flash attention is installed:
Next Steps
Streaming Responses
Stream tokens as they’re generated
Multi-GPU Inference
Scale across multiple GPUs
vLLM Integration
Production-grade serving with vLLM
Quantization
Reduce memory with quantization