Serving
Then we can serve with the following command:
# Serverexport MODEL=pytorch/gemma-3-12b-it-INT4VLLM_DISABLE_COMPILE_CACHE=1 vllm serve $MODEL --tokenizer $MODEL -O3
# Clientcurl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{ "model": "pytorch/gemma-3-12b-it-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.
Install the required packages:
pip install git+https://github.com/huggingface/transformers@mainpip install torchaopip install torchpip install accelerate
Example:
import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer model_name = "pytorch/gemma-3-12b-it-INT4" # load the tokenizer and the modeltokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype="auto", device_map="auto") # prepare the model inputprompt = "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 completiongenerated_ids = model.generate( **model_inputs, max_new_tokens=32768)output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist() # parsing thinking contenttry: # 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("")content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("") print("thinking content:", thinking_content)print("content:", content)
Quantization Recipe
Install the required packages:
pip install torchpip install git+https://github.com/huggingface/transformers@mainpip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126pip install accelerate
Use the following code to get the quantized model:
import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig model_id = "google/gemma-3-12b-it"model_to_quantize = "google/gemma-3-12b-it" from torchao.quantization import Int4WeightOnlyConfigquant_config = Int4WeightOnlyConfig(group_size=128, int4_packing_format="tile_packed_to_4d", int4_choose_qparams_algorithm="hqq")quantization_config = TorchAoConfig(quant_type=quant_config)quantized_model = AutoModelForCausalLM.from_pretrained(model_to_quantize, device_map="auto", torch_dtype=torch.bfloat16, quantization_config=quantization_config)tokenizer = AutoTokenizer.from_pretrained(model_id) # Push to hubUSER_ID = "YOUR_USER_ID"MODEL_NAME = model_id.split("/")[-1]save_to = f"{USER_ID}/{MODEL_NAME}-INT4"quantized_model.push_to_hub(save_to, safe_serialization=False)tokenizer.push_to_hub(save_to) # Manual Testingprompt = "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. Here we only run on mmlu for sanity check.
Table with columns: Benchmark| Benchmark | | |
|---|
| google/gemma-3-12b-it | pytorch/gemma-3-12b-it-INT4 |
| mmlu | 71.51 | 68.96 |
| chartqa (multimodal) | 55.80 | 56.28 |
language eval
Need to install lm-eval from source:
https://github.com/EleutherAI/lm-evaluation-harness#install
export MODEL=google/gemma-3-12b-it # or pytorch/gemma-3-12b-it-INT4lm_eval --model hf --model_args pretrained=$MODEL --tasks mmlu --device cuda:0 --batch_size 8
multi-modal eval
Need to install lmms-eval from source:
pip install git+https://github.com/EvolvingLMMs-Lab/lmms-eval.git
NUM_PROCESSES=8MAIN_PORT=12345MODEL_ID=google/gemma-3-12b-it # or pytorch/gemma-3-12b-it-INT4TASKS=chartqa # or tasks from https://github.com/EvolvingLMMs-Lab/lmms-eval/tree/main/lmms_eval/models/simpleBATCH_SIZE=32OUTPUT_PATH=./logs/ accelerate launch --num_processes "${NUM_PROCESSES}" --main_process_port "${MAIN_PORT}" -m lmms_eval \ --model gemma3 \ --model_args "pretrained=${MODEL_ID}" \ --tasks "${TASKS}" \ --batch_size "${BATCH_SIZE}" --output_path "${OUTPUT_PATH}"
Peak Memory Usage
Results
Table with columns: Benchmark| Benchmark | | |
|---|
| google/gemma-3-12b-it | pytorch/gemma-3-12b-it-INT4 |
| Peak Memory (GB) | 24.50 | 8.68 (65% reduction) |
We can use the following code to get a sense of peak memory usage during inference:
import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig # use "google/gemma-3-12b-it" or "pytorch/gemma-3-12b-it-INT4"model_id = "pytorch/gemma-3-12b-it-INT4"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() / 1e9print(f"Peak Memory Usage: {mem:.02f} GB")
Results (A100 machine)
Table with columns: Benchmark (Latency)| Benchmark (Latency) | | |
|---|
| google/gemma-3-12b-it | pytorch/gemma-3-12b-it-INT4 |
| latency (batch_size=1) | 3.73s | 2.16s (1.73x speedup) |
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
export MODEL=google/gemma-3-12b-itpython benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model $MODEL --batch-size 1
INT4
export MODEL=pytorch/gemma-3-12b-it-INT4VLLM_DISABLE_COMPILE_CACHE=1 python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model $MODEL --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
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.