QAT INT4 google/gemma-3-12b-it model
Developed by: pytorch
License: apache-2.0
Quantized from Model : google/gemma-3-12b-it
Quantization Method : QAT INT4
Terms of Use : Terms
gemma-3-12b-it 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 66% VRAM reduction (8.34 GB needed) and 1.73x speedup on H100 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:
1 # Server
2 export MODEL=pytorch/gemma-3-12b-it-QAT-INT4
3 VLLM_DISABLE_COMPILE_CACHE=1 vllm serve $MODEL --tokenizer $MODEL -O3
1 # Client
2 curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{
3 "model": "pytorch/gemma-3-12b-it-QAT-INT4",
4 "messages": [
5 {"role": "user", "content": "Give me a short introduction to large language models."}
6 ],
7 "temperature": 0.6,
8 "top_p": 0.95,
9 "top_k": 20,
10 "max_tokens": 32768
11 }'
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:
1 pip install git+https://github.com/huggingface/transformers@main
2 pip install torchao
3 pip install torch
4 pip install accelerate
Example:
1 import torch
2 from transformers import AutoModelForCausalLM, AutoTokenizer
3
4 model_name = "pytorch/gemma-3-12b-it-QAT-INT4"
5
6 # load the tokenizer and the model
7 tokenizer = AutoTokenizer.from_pretrained(model_name)
8 model = AutoModelForCausalLM.from_pretrained(
9 model_name,
10 torch_dtype="auto",
11 device_map="auto"
12 )
13
14 # prepare the model input
15 prompt = "Give me a short introduction to large language model."
16 messages = [
17 {"role": "user", "content": prompt}
18 ]
19 text = tokenizer.apply_chat_template(
20 messages,
21 tokenize=False,
22 add_generation_prompt=True,
23 enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
24 )
25 model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
26
27 # conduct text completion
28 generated_ids = model.generate(
29 **model_inputs,
30 max_new_tokens=32768
31 )
32 output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
33
34 # parsing thinking content
35 try:
36 # rindex finding 151668 (</think>)
37 index = len(output_ids) - output_ids[::-1].index(151668)
38 except ValueError:
39 index = 0
40
41 thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
42 content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
43
44 print("thinking content:", thinking_content)
45 print("content:", content)
Fine-tuning Recipe
Install the required packages:
1 pip install torch
2 pip install git+https://github.com/huggingface/transformers@main
3 pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu128
4 pip install unsloth
5 pip install accelerate
Use the following code to fine-tune the model
1 # Modeled after https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_(14B)-Reasoning-Conversational.ipynb
2
3 from unsloth import FastModel
4 from unsloth.chat_templates import (
5 get_chat_template,
6 standardize_data_formats,
7 standardize_sharegpt,
8 train_on_responses_only,
9 )
10 from datasets import load_dataset
11 from trl import SFTConfig, SFTTrainer
12 import torch
13
14
15 max_seq_length = 2048
16 dtype = torch.bfloat16
17
18
19 # ==============
20 # Model setup |
21 # ==============
22
23 model, tokenizer = FastModel.from_pretrained(
24 model_name = "unsloth/gemma-3-12b-it",
25 max_seq_length = max_seq_length,
26 dtype = dtype,
27 load_in_4bit = False,
28 full_finetuning = False,
29 )
30
31 model = FastModel.get_peft_model(
32 model,
33 finetune_vision_layers = False,
34 r = 8,
35 lora_alpha = 8,
36 lora_dropout = 0,
37 qat_scheme = "int4",
38 )
39
40 tokenizer = get_chat_template(tokenizer, chat_template="gemma3")
41
42
43 # =============
44 # Data setup |
45 # =============
46
47 def format_into_conversation(example):
48 choices = ["A", "B", "C", "D"]
49 correct_choice = choices[example["answer"]]
50 question = "Choose the correct answer for the following question: "
51 question += f"{example['question']}\n\n"
52 question += "Choices:\n"
53 question += f"A. {example['choices'][0]}\n"
54 question += f"B. {example['choices'][1]}\n"
55 question += f"C. {example['choices'][2]}\n"
56 question += f"D. {example['choices'][3]}"
57 answer = f"The correct answer is {correct_choice}."
58 return {"conversations": [
59 {"from": "human", "value": question},
60 {"from": "gpt", "value": answer},
61 ]}
62
63 def formatting_prompts_func(examples):
64 convos = examples["conversations"]
65 texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False).removeprefix('<bos>') for convo in convos]
66 return { "text" : texts, }
67
68 dataset = load_dataset("cais/mmlu", "all", split="auxiliary_train")
69 dataset = dataset.map(format_into_conversation)
70 dataset = dataset.remove_columns(["question", "subject", "choices", "answer"])
71 dataset = standardize_data_formats(dataset)
72 dataset = dataset.map(formatting_prompts_func, batched = True,)
73
74
75 # ========
76 # Train |
77 # ========
78
79 trainer = SFTTrainer(
80 model = model,
81 tokenizer = tokenizer,
82 train_dataset = dataset,
83 dataset_text_field = "text",
84 max_seq_length = max_seq_length,
85 packing = False,
86 args = SFTConfig(
87 per_device_train_batch_size = 32,
88 gradient_accumulation_steps = 1,
89 warmup_steps = 5,
90 num_train_epochs = 1,
91 max_steps = 100,
92 learning_rate = 2e-5,
93 logging_steps = 1,
94 optim = "adamw_8bit",
95 weight_decay = 0.01,
96 lr_scheduler_type = "linear",
97 seed = 3407,
98 output_dir = "outputs",
99 report_to = "none",
100 ),
101 )
102
103 trainer = train_on_responses_only(
104 trainer,
105 instruction_part = "<start_of_turn>user\n",
106 response_part = "<start_of_turn>model\n",
107 )
108
109 trainer_stats = trainer.train()
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.
Benchmark mmlu accuracy Normalized accuracy degradation google/gemma-3-12b-it bf16 71.51 -0% int4 69.48 -100% Fine-tuned without QAT bf16 71.55 +2% int4 69.58 -95% Fine-tuned with QAT int4 70.18 -65.5%
Reproduce Model Quality Results
language eval
1 export MODEL=google/gemma-3-12b-it # or pytorch/gemma-3-12b-it-QAT-INT4
2 lm_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
1 NUM_PROCESSES=8
2 MAIN_PORT=12345
3 MODEL_ID=google/gemma-3-12b-it # or pytorch/gemma-3-12b-it-QAT-INT4
4 TASKS=chartqa # or tasks from https://github.com/EvolvingLMMs-Lab/lmms-eval/tree/main/lmms_eval/models/simple
5 BATCH_SIZE=32
6 OUTPUT_PATH=./logs/
7
8 accelerate launch --num_processes "${NUM_PROCESSES}" --main_process_port "${MAIN_PORT}" -m lmms_eval \
9 --model gemma3 \
10 --model_args "pretrained=${MODEL_ID}" \
11 --tasks "${TASKS}" \
12 --batch_size "${BATCH_SIZE}" --output_path "${OUTPUT_PATH}"
Peak Memory Usage
Results
Benchmark google/gemma-3-12b-it pytorch/gemma-3-12b-it-QAT-INT4 Peak Memory (GB) 24.50 8.34 (66% reduction)
Reproduce Peak Memory Usage Results
We can use the following code to get a sense of peak memory usage during inference:
1 import torch
2 from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
3
4 # use "google/gemma-3-12b-it" or "pytorch/gemma-3-12b-it-QAT-INT4"
5 model_id = "pytorch/gemma-3-12b-it-QAT-INT4"
6 quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16)
7 tokenizer = AutoTokenizer.from_pretrained(model_id)
8
9 torch.cuda.reset_peak_memory_stats()
10
11 prompt = "Hey, are you conscious? Can you talk to me?"
12 messages = [
13 {
14 "role": "system",
15 "content": "",
16 },
17 {"role": "user", "content": prompt},
18 ]
19 templated_prompt = tokenizer.apply_chat_template(
20 messages,
21 tokenize=False,
22 add_generation_prompt=True,
23 )
24 print("Prompt:", prompt)
25 print("Templated prompt:", templated_prompt)
26 inputs = tokenizer(
27 templated_prompt,
28 return_tensors="pt",
29 ).to("cuda")
30 generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
31 output_text = tokenizer.batch_decode(
32 generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
33 )
34 print("Response:", output_text[0][len(prompt):])
35
36 mem = torch.cuda.max_memory_reserved() / 1e9
37 print(f"Peak Memory Usage: {mem:.02f} GB")
Model Performance
Results (H100 machine)
Benchmark (Latency) google/gemma-3-12b-it pytorch/gemma-3-12b-it-QAT-INT4 latency (batch_size=1) 3.73s 2.16s (1.73x speedup)
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 google/gemma-3-12b-it --batch-size 1
INT4
VLLM_DISABLE_COMPILE_CACHE=1 vllm bench latency --input-len 256 --output-len 256 --model pytorch/gemma-3-12b-it-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
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.