Qwen3-8B quantized with torchao int4 weight only quantization, using hqq algorithm for improved accuracy, by PyTorch team. Use it directly or serve using vLLM for 62% VRAM reduction and 1.2x speedup on A100 GPUs.
Inference with vLLM
Install vllm nightly and torchao nightly to get some recent changes:
pip install vllm --pre --extra-index-url https://wheels.vllm.ai/nightly
pip install torchao
Serving
Then we can serve with the following command:
# Server
export MODEL=pytorch/Qwen3-8B-int4wo-hqq
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-int4wo-hqq",
"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 torchao
pip install torch
pip install accelerate
Example:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "pytorch/Qwen3-8B-int4wo-hqq"
# 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)
Quantization Recipe
Install the required packages:
pip install git+https://github.com/huggingface/transformers@main
pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126
pip install torch
pip install accelerate
Use the following code to get the quantized model:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
model_id = "microsoft/Phi-4-mini-instruct"
from torchao.quantization import Int4WeightOnlyConfig
quant_config = Int4WeightOnlyConfig(group_size=128, use_hqq=True)
quantization_config = TorchAoConfig(quant_type=quant_config)
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
tokenizer = AutoTokenizer.from_pretrained(model_id)
# Push to hub
USER_ID = "YOUR_USER_ID"
MODEL_NAME = model_id.split("/")[-1]
save_to = f"{USER_ID}/{MODEL_NAME}-int4wo-hqq"
quantized_model.push_to_hub(save_to, safe_serialization=False)
tokenizer.push_to_hub(save_to)
# Manual Testing
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):])
Note: to push_to_hub
you need to run
pip install -U "huggingface_hub[cli]"
huggingface-cli login
and use a token with write access, from https://huggingface.co/settings/tokens
Model Quality
We rely on lm-evaluation-harness to evaluate the quality of the quantized model.
Benchmark | ||
---|---|---|
Qwen3-8B | Qwen3-8B-int4wo | |
General | ||
mmlu | 73.04 | 70.4 |
mmlu_pro | 53.81 | 52.79 |
bbh | 79.33 | 74.92 |
Multilingual | ||
mgsm_en_cot_en | 39.6 | 33.2 |
m_mmlu (avg) | 57.17 | 54.06 |
Math | ||
gpqa_main_zeroshot | 35.71 | 32.14 |
gsm8k | 87.79 | 86.28 |
leaderboard_math_hard (v3) | 53.7 | 46.83 |
Overall | 60.02 | 56.33 |
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=microsoft/Phi-4-mini-instruct --tasks mmlu --device cuda:0 --batch_size 8
int4 weight only quantization with hqq (int4wo-hqq)
export MODEL=pytorch/Qwen3-8B-int4wo-hqq
# or
# export MODEL=Qwen/Qwen3-8B
lm_eval --model hf --model_args pretrained=$MODEL --tasks mmlu --device cuda:0 --batch_size 8
Peak Memory Usage
Results
Benchmark | ||
---|---|---|
Qwen3-8B | Qwen3-8B-int4wo-hqq | |
Peak Memory (GB) | 16.47 | 6.27 (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-int4wo-hqq"
model_id = "pytorch/Qwen3-8B-int4wo-hqq"
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", 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 int4wo 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 (A100 machine)
Benchmark (Latency) | ||
---|---|---|
Qwen3-8B | Qwen3-8B-int4wo-hqq | |
latency (batch_size=1) | 3.52s | 2.84s (1.24x 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 [email protected]:vllm-project/vllm.git
Install vllm
VLLM_USE_PRECOMPILED=1 pip install --editable .
Run the benchmarks under vllm
root folder:
benchmark_latency
baseline
export MODEL=Qwen/Qwen3-8B
python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model $MODEL --batch-size 1
int4wo-hqq
export MODEL=pytorch/Qwen3-8B-int4wo-hqq
VLLM_DISABLE_COMPILE_CACHE=1 python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model $MODEL --batch-size 1
benchmark_serving
We benchmarked the throughput in a serving environment.
Download sharegpt dataset:
wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.json
Other datasets can be found in: https://github.com/vllm-project/vllm/tree/main/benchmarks
Note: you can change the number of prompts to be benchmarked with --num-prompts
argument for benchmark_serving
script.
baseline
Server:
export MODEL=Qwen/Qwen3-8B
vllm serve $MODEL --tokenizer $MODEL -O3
Client:
export MODEL=Qwen/Qwen3-8B
python benchmarks/benchmark_serving.py --backend vllm --dataset-name sharegpt --tokenizer $MODEL --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json --model $MODEL --num-prompts 1
int4wo-hqq
Server:
export MODEL=pytorch/Qwen3-8B-int4wo-hqq
VLLM_DISABLE_COMPILE_CACHE=1 vllm serve $MODEL --tokenizer $MODEL -O3 --pt-load-map-location cuda:0
Client:
export MODEL=pytorch/Qwen3-8B-int4wo-hqq
python benchmarks/benchmark_serving.py --backend vllm --dataset-name sharegpt --tokenizer $MODEL --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json --model $MODEL --num-prompts 1
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
- 22