/ Модель

Характеристики

Размер весов
8,6 ГБ
Лицензия
Apache 2.0
Архитектура
gemma3 · dense
Базовая модель
gemma-3-12b-it
Опубликована
25 сен 2025

gemma-3-12b-it-AWQ-INT4

Изображение и текст → текст13 профессий

pytorch/gemma-3-12b-it-AWQ-INT4 — это квантизированная версия instruction-tuned языковой модели google/gemma-3-12b-it, разработанная pytorch.

820скачиваний за 30 дней1лайквеса обновлены11 окт 2025

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Изображение → текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Модель предназначена для диалогового взаимодействия, генерации и обработки текста, включая ответы на вопросы, краткие объяснения и другие сценарии использования через chat completions или библиотеку Transformers. В README явно указан английский язык; сведения о поддерживаемых модальностях и размере контекстного окна отсутствуют.

Модель содержит 12 миллиардов параметров и использует квантизацию AWQ-INT4 с группой размера 128 для весов линейных слоёв. Квантизация снижает требования к памяти по сравнению с исходной версией bfloat16 и рассчитана на запуск с PyTorch, torchao, Transformers и vLLM. В примере генерации поддерживается режим рассуждений, который можно включать или отключать через chat template. Для работы с vLLM требуется nightly-версия vLLM и torchao; из-за известных проблем совместимости рекомендуется отключать compile cache.

По данным README, на ограниченной калибровке из 30 примеров задачи mmlu_philosophy модель показала точность 76,85% против 75,56% у gemma-3-12b-it-INT4 и 79,10% у базовой версии bfloat16. Эти результаты нельзя считать полноценной оценкой общих возможностей модели. В рецепте квантизации указано, что AWQ на данный момент работает только на H100 INT4, поэтому аппаратная совместимость может быть ограничена. Модель распространяется по лицензии Apache-2.0.

Для каких профессий подходит13

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Также подходит для

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

AWQ-INT4 google/gemma-3-12b-it model

  • Developed by: pytorch
  • License: apache-2.0
  • Quantized from Model : google/gemma-3-12b-it
  • Quantization Method : AWQ-INT4
  • Terms of Use: Terms

Calibrated with 30 samples of mmlu_philosophy, got eval accuracy of 76.85, while gemma-3-12b-it-INT4 is 75.56, and bfloat16 baseline is 79.10

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/gemma-3-12b-it-AWQ-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/gemma-3-12b-it-AWQ-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 torchao
pip install torch
pip install accelerate

Example:

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "pytorch/gemma-3-12b-it-AWQ-INT4"

# load the tokenizer and the model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype="auto",
    device_map="cuda:0"
)

# 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("
")
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 torch
pip install git+https://github.com/huggingface/transformers@main
pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126
pip install accelerate

Use the following code to get the quantized model:

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig

model_id = "google/gemma-3-12b-it"
model_to_quantize = "google/gemma-3-12b-it"
from torchao.quantization import Int4WeightOnlyConfig, quantize_, ModuleFqnToConfig
from torchao.prototype.awq import (
    AWQConfig,
)
from torchao._models._eval import TransformerEvalWrapper
model = AutoModelForCausalLM.from_pretrained(
    model_to_quantize,
    device_map="cuda:0",
    torch_dtype=torch.bfloat16,
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
def get_quant_config(linear_config):
    return ModuleFqnToConfig({
        r"re:language_model\.model\.layers\..+\.mlp\..+_proj": linear_config,
        r"re:language_model\.model\.layers\..+\.self_attn\..+_proj": linear_config,
        r"re:model\.language_model\.layers\..+\.mlp\..+_proj": linear_config,
        r"re:model\.language_model\.layers\..+\.self_attn\..+_proj": linear_config,
    })
# AWQ only works for H100 INT4 so far
base_config = Int4WeightOnlyConfig(group_size=128)
linear_config = AWQConfig(base_config, step="prepare")
quant_config = get_quant_config(linear_config)
quantize_(
    model,
    quant_config,
)
tasks = ["mmlu_philosophy"]
calibration_limit=30
max_seq_length=2048
TransformerEvalWrapper(
    model=model,
    tokenizer=tokenizer,
    max_seq_length=max_seq_length,
).run_eval(
    tasks=tasks,
    limit=calibration_limit,
)
linear_config = AWQConfig(base_config, step="convert")
quant_config = get_quant_config(linear_config)
quantize_(model, quant_config)
quantized_model = model
linear_config = AWQConfig(base_config, step="prepare_for_loading")
quant_config = get_quant_config(linear_config)
quantized_model.config.quantization_config = TorchAoConfig(quant_config)

# Push to hub
USER_ID = "YOUR_USER_ID"
MODEL_NAME = model_id.split("/")[-1]
save_to = f"{USER_ID}/{MODEL_NAME}-AWQ-INT4"
quantized_model.push_to_hub(save_to, safe_serialization=False)
tokenizer.push_to_hub(save_to)

# Manual Testing
quantized_model = AutoModelForCausalLM.from_pretrained(
    save_to,
    device_map="cuda:0",
    torch_dtype=torch.bfloat16,
)
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. Here we only run on mmlu for sanity check.

Benchmark
google/gemma-3-12b-itjerryzh168/gemma-3-12b-it-INT4pytorch/gemma-3-12b-it-AWQ-INT4
philosophy79.1075.5676.85

Note: jerryzh168/gemma-3-12b-it-INT4 is the H100 optimized checkpoint for INT4

Need to install lm-eval from source: https://github.com/EleutherAI/lm-evaluation-harness#install

baseline

lm_eval --model hf --model_args pretrained=google/gemma-3-12b-it --tasks mmlu --device cuda:0 --batch_size 8

AWQ-INT4

export MODEL=pytorch/gemma-3-12b-it-AWQ-INT4
lm_eval --model hf --model_args pretrained=$MODEL --tasks mmlu --device cuda:0 --batch_size 8

Peak Memory Usage

Results

Benchmark
google/gemma-3-12b-itjerryzh168/gemma-3-12b-it-INT4pytorch/gemma-3-12b-it-AWQ-INT4
Peak Memory (GB)24.5110.37 (58% reduction)12.60 (49% reduction)

Note: jerryzh168/gemma-3-12b-it-INT4 is the H100 optimized checkpoint for INT4

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 "google/gemma-3-12b-it" or "pytorch/gemma-3-12b-it-AWQ-INT4"
model_id = "pytorch/gemma-3-12b-it-AWQ-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

Results (H100 machine)

Benchmark (Latency)
google/gemma-3-12b-itjerryzh168/gemma-3-12b-it-INT4pytorch/gemma-3-12b-it-AWQ-INT4
latency (batch_size=1)3.73s2.73 (1.37x speedup)2.76s (1.35x speedup)
latency (batch_size=256)14.07s13.81 (1.02x speedup)13.93s (1.01x speedup)

Note: jerryzh168/gemma-3-12b-it-INT4 is the H100 optimized checkpoint for INT4

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-it
python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model $MODEL --batch-size 1

AWQ-INT4

export MODEL=pytorch/gemma-3-12b-it-AWQ-INT4
VLLM_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.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Можно запустить

Подбираем GPU…

Класс архитектуры
Gemma3ForConditionalGeneration
Ревизия весов
4f826e6

0 моделей