Skip to main content

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:

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 with GenerationConfig:

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:
KV cache quantization and flash attention cannot be enabled simultaneously. If both are set to True, flash attention will be automatically disabled.

Device Mapping

Control which devices the model uses:

Performance Tips

Install flash-attention for 30-40% speedup:
No code changes needed - Qwen automatically detects and uses flash attention.
On supported hardware, BF16 provides the best balance:
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