QAT INT4 Qwen/Qwen3-8B
- Developed by: pytorch
- License: apache-2.0
- Quantized from Model : Qwen/Qwen3-8B
- Quantization Method : QAT INT4
Qwen3-8B fine-tuned with unsloth using quantization-aware training (QAT) from torchao, and quantized with int4 weight only quantization, by PyTorch team. Use it directly or serve using vLLM for 62% VRAM reduction (6.24 GB needed) and 1.45x speedup on H100 GPUs.
Inference with vLLM
Install vllm nightly and torchao nightly to get some recent changes:
pip install --pre vllm --extra-index-url https://wheels.vllm.ai/nightly
pip install --pre torchao torch --index-url https://download.pytorch.org/whl/nightly/cu128
Serving
Then we can serve with the following command:
# Server
export MODEL=pytorch/Qwen3-8B-QAT-INT4
VLLM_DISABLE_COMPILE_CACHE=1 vllm serve $MODEL --tokenizer $MODEL -O3
# Client
curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "pytorch/Qwen3-8B-QAT-INT4",
"messages": [
{"role": "user", "content": "Give me a short introduction to large language models."}
],
"temperature": 0.6,
"top_p": 0.95,
"top_k": 20,
"max_tokens": 32768
}'
Note: please use VLLM_DISABLE_COMPILE_CACHE=1 to disable compile cache when running this code, e.g. VLLM_DISABLE_COMPILE_CACHE=1 python example.py, since there are some issues with the composability of compile in vLLM and torchao,
this is expected be resolved in pytorch 2.8.
Inference with Transformers
Install the required packages:
pip install git+https://github.com/huggingface/transformers@main
pip install --pre torchao torch --index-url https://download.pytorch.org/whl/nightly/cu128
pip install accelerate
Example:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "pytorch/Qwen3-8B-QAT-INT4"
# load the tokenizer and the model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto"
)
# prepare the model input
prompt = "Give me a short introduction to large language model."
messages = [
{"role": "user", "content": prompt}
]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
)
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
# conduct text completion
generated_ids = model.generate(
**model_inputs,
max_new_tokens=32768
)
output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
# parsing thinking content
try:
# rindex finding 151668 (</think>)
index = len(output_ids) - output_ids[::-1].index(151668)
except ValueError:
index = 0
thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
print("thinking content:", thinking_content)
print("content:", content)
Fine-tuning Recipe
Install the required packages:
pip install git+https://github.com/huggingface/transformers@main
pip install --pre torchao torch --index-url https://download.pytorch.org/whl/nightly/cu128
pip install unsloth
pip install accelerate
Use the following code to fine-tune the model:
# Modeled after https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_(14B)-Reasoning-Conversational.ipynb
from unsloth import FastLanguageModel
from unsloth.chat_templates import (
get_chat_template,
standardize_data_formats,
standardize_sharegpt,
train_on_responses_only,
)
from datasets import load_dataset
from trl import SFTConfig, SFTTrainer
import torch
max_seq_length = 2048
dtype = torch.bfloat16
# ==============
# Model setup |
# ==============
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Qwen3-8B",
max_seq_length = max_seq_length,
dtype = dtype,
load_in_4bit = False,
full_finetuning = False,
)
model = FastLanguageModel.get_peft_model(
model,
r = 16,
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",],
lora_alpha = 16,
lora_dropout = 0,
qat_scheme = "int4",
)
tokenizer = get_chat_template(tokenizer, chat_template="qwen3")
# =============
# Data setup |
# =============
def format_into_conversation(example):
choices = ["A", "B", "C", "D"]
correct_choice = choices[example["answer"]]
question = "Choose the correct answer for the following question: "
question += f"{example['question']}\n\n"
question += "Choices:\n"
question += f"A. {example['choices'][0]}\n"
question += f"B. {example['choices'][1]}\n"
question += f"C. {example['choices'][2]}\n"
question += f"D. {example['choices'][3]}"
answer = f"The correct answer is {correct_choice}."
return {"conversations": [
{"from": "human", "value": question},
{"from": "gpt", "value": answer},
]}
def formatting_prompts_func(examples):
convos = examples["conversations"]
texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]
return { "text" : texts, }
dataset = load_dataset("cais/mmlu", "all", split="auxiliary_train")
dataset = dataset.map(format_into_conversation)
dataset = dataset.remove_columns(["question", "subject", "choices", "answer"])
dataset = standardize_data_formats(dataset)
dataset = dataset.map(formatting_prompts_func, batched = True,)
# ========
# Train |
# ========
trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
train_dataset = dataset,
dataset_text_field = "text",
max_seq_length = max_seq_length,
packing = False,
args = SFTConfig(
per_device_train_batch_size = 32,
gradient_accumulation_steps = 1,
warmup_steps = 5,
num_train_epochs = 1,
max_steps = 300,
learning_rate = 2e-5,
logging_steps = 1,
optim = "adamw_8bit",
weight_decay = 0.01,
lr_scheduler_type = "linear",
seed = 3407,
output_dir = "outputs",
report_to = "none",
),
)
trainer = train_on_responses_only(
trainer,
instruction_part = "<|im_start|>user\n",
response_part = "<|im_start|>assistant\n",
)
trainer_stats = trainer.train()
model.save_pretrained_torchao("/tmp/finetuned_qat_model")
Model Quality
We rely on lm-evaluation-harness to evaluate the quality of the quantized model.
| Benchmark | ||
|---|---|---|
| mmlu accuracy | Normalized accuracy degradation | |
| Qwen3/Qwen3-8B | ||
| bf16 | 73.02 | -0% |
| int4 | 69.91 | -100% |
| Fine-tuned without QAT | ||
| bf16 | 74.16 | +137% |
| int4 | 69.50 | -113% |
| Fine-tuned with QAT | ||
| int4 | 71.12 | -61.1% |
Reproduce Model Quality Results
Need to install lm-eval from source: https://github.com/EleutherAI/lm-evaluation-harness#install
baseline
lm_eval --model hf --model_args pretrained=Qwen/Qwen3-8B --tasks mmlu --device cuda:0 --batch_size auto
int4 weight only quantization with quantization-aware training (QAT-INT4)
export MODEL=pytorch/Qwen3-8B-QAT-INT4
# or
# export MODEL=Qwen/Qwen3-8B
lm_eval --model hf --model_args pretrained=$MODEL --tasks mmlu --device cuda:0 --batch_size auto
Peak Memory Usage
Results
| Benchmark | ||
|---|---|---|
| Qwen3-8B | Qwen3-8B-QAT-INT4 | |
| Peak Memory (GB) | 16.47 | 6.24 (62% reduction) |
Reproduce Peak Memory Usage Results
We can use the following code to get a sense of peak memory usage during inference:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
# use "Qwen/Qwen3-8B" or "pytorch/Qwen3-8B-QAT-INT4"
model_id = "pytorch/Qwen3-8B-QAT-INT4"
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda:0", torch_dtype=torch.bfloat16)
tokenizer = AutoTokenizer.from_pretrained(model_id)
torch.cuda.reset_peak_memory_stats()
prompt = "Hey, are you conscious? Can you talk to me?"
messages = [
{
"role": "system",
"content": "",
},
{"role": "user", "content": prompt},
]
templated_prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
print("Prompt:", prompt)
print("Templated prompt:", templated_prompt)
inputs = tokenizer(
templated_prompt,
return_tensors="pt",
).to("cuda")
generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
output_text = tokenizer.batch_decode(
generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print("Response:", output_text[0][len(prompt):])
mem = torch.cuda.max_memory_reserved() / 1e9
print(f"Peak Memory Usage: {mem:.02f} GB")
Model Performance
Our INT4 model is only optimized for batch size 1, so expect some slowdown with larger batch sizes, we expect this to be used in local server deployment for single or a few users where the decode tokens per second will matters more than the time to first token.
Results
| Benchmark (Latency) | ||
|---|---|---|
| Qwen3-8B | Qwen3-8B-QAT-INT4 | |
| latency (batch_size=1) | 2.50s | 1.72s (1.45x speedup) |
Int4 weight only is optimized for batch size 1 and short input and output token length, please stay tuned for models optimized for larger batch sizes or longer token length.
Reproduce Model Performance Results
Setup
Get vllm source code:
git clone git@github.com:vllm-project/vllm.git
Install vllm
VLLM_USE_PRECOMPILED=1 pip install --editable .
Run the benchmarks under vllm root folder:
benchmark_latency
baseline
vllm bench latency --input-len 256 --output-len 256 --model Qwen/Qwen3-8B --batch-size 1
QAT INT4
VLLM_DISABLE_COMPILE_CACHE=1 vllm bench latency --input-len 256 --output-len 256 --model pytorch/Qwen3-8B-QAT-INT4 --batch-size 1
Paper: TorchAO: PyTorch-Native Training-to-Serving Model Optimization
The model's quantization is powered by TorchAO, a framework presented in the paper TorchAO: PyTorch-Native Training-to-Serving Model Optimization.
Abstract: We present TorchAO, a PyTorch-native model optimization framework leveraging quantization and sparsity to provide an end-to-end, training-to-serving workflow for AI models. TorchAO supports a variety of popular model optimization techniques, including FP8 quantized training, quantization-aware training (QAT), post-training quantization (PTQ), and 2:4 sparsity, and leverages a novel tensor subclass abstraction to represent a variety of widely-used, backend agnostic low precision data types, including INT4, INT8, FP8, MXFP4, MXFP6, and MXFP8. TorchAO integrates closely with the broader ecosystem at each step of the model optimization pipeline, from pre-training (TorchTitan) to fine-tuning (TorchTune, Axolotl) to serving (HuggingFace, vLLM, SGLang, ExecuTorch), connecting an otherwise fragmented space in a single, unified workflow. TorchAO has enabled recent launches of the quantized Llama 3.2 1B/3B and LlamaGuard3-8B models and is open-source at this https URL .
Resources
- Official TorchAO GitHub Repository: https://github.com/pytorch/ao
- TorchAO Documentation: https://docs.pytorch.org/ao/stable/index.html
Disclaimer
PyTorch has not performed safety evaluations or red teamed the quantized models. Performance characteristics, outputs, and behaviors may differ from the original models. Users are solely responsible for selecting appropriate use cases, evaluating and mitigating for accuracy, safety, and fairness, ensuring security, and complying with all applicable laws and regulations.
Nothing contained in this Model Card should be interpreted as or deemed a restriction or modification to the licenses the models are released under, including any limitations of liability or disclaimers of warranties provided therein.
- Downloads last month
- 404