Overview
Qwen models are fully compatible with the Hugging Face Transformers library, providing a standardized interface for loading and running inference. This guide covers all aspects of using Qwen with Transformers.Installation
Install the required packages:Transformers 4.32.0 or above is required for Qwen models. For best performance, use PyTorch 2.0 or above.
Loading Models from Hugging Face
Qwen models are available on Hugging Face Hub with various configurations:1
Initialize Tokenizer
Load the tokenizer with
trust_remote_code=True:2
Load Model
Load the model with automatic device mapping:
3
Run Inference
Use the chat interface for conversational models:
Precision Options
Qwen supports multiple precision formats to balance performance and memory usage:- Auto (Recommended)
- BF16
- FP16
- CPU
Automatically selects the best precision based on your device:
Chat Interface
The.chat() method provides a convenient interface for conversational models:
History Format
The history is a list of tuples containing (query, response) pairs:Generation Parameters
Customize text generation withGenerationConfig:
Common Parameters
Base Model Usage
For non-chat models, use the standard.generate() method:
Quantized Models
Load pre-quantized models for reduced memory usage:Quantized models provide significant memory savings with minimal performance degradation. See the quantization guide for more details.
KV Cache Quantization
Enable KV cache quantization for higher throughput:Device Mapping
Control which devices the model uses:Performance Tips
Enable Flash Attention
Enable Flash Attention
Install flash-attention for 30-40% speedup:No code changes needed - Qwen automatically detects and uses flash attention.
Use BF16 Precision
Use BF16 Precision
On supported hardware, BF16 provides the best balance:
Optimize Generation Config
Optimize Generation Config
Adjust generation parameters for your use case:
Next Steps
ModelScope Integration
Use Qwen with ModelScope platform
Batch Inference
Process multiple requests efficiently
Streaming
Stream tokens as they’re generated
Multi-GPU
Scale across multiple GPUs