Open-weight models are useful precisely because you can adapt them to your domain. A general-purpose 12B-parameter model knows a lot about everything and not enough about your specific task — your internal taxonomy, your error categories, your domain jargon. Fine-tuning bridges that gap.
Gemma 3 (Gemma Team, Google DeepMind, 2024; arXiv:2403.08295) is Google's open-weight model family derived from Gemini research, shipping in 1B, 4B, 12B, and 27B parameter variants. The instruction-tuned versions (gemma-3-*-it) are already aligned via SFT + RLHF, which means fine-tuning is about narrowing the model's capability to your domain, not teaching it to follow instructions from scratch.
This post covers the full workflow: preparing a dataset, fine-tuning Gemma 3 12B with QLoRA on Vertex AI, evaluating the results, and avoiding the failure modes that waste GPU hours.
Why Gemma 3, and why fine-tune at all
Three reasons to fine-tune rather than prompt-engineer:
- Consistency. A fine-tuned model produces outputs in your format every time, without multi-page system prompts that eat context and cost tokens.
- Latency. Shorter prompts (no few-shot examples needed) mean faster inference.
- Quality ceiling. For classification, extraction, and structured tasks, fine-tuning reliably outperforms prompting once you have 500+ high-quality examples (Hu et al., 2022; arXiv:2106.09685).
Why Gemma 3 specifically: the 12B model hits a practical sweet spot. It's large enough to retain strong general capabilities after fine-tuning, small enough to serve on a single A100, and multimodal (SigLIP vision encoder at 4B+) if you need image understanding. Google's open license permits commercial use.
QLoRA: the pragmatic default
Full fine-tuning a 12B model requires ~96 GB of GPU memory and updates all 12 billion parameters. For most domain-adaptation tasks, this is overkill.
LoRA (Low-Rank Adaptation; Hu, Shen, Wallis et al., ICLR 2022; arXiv:2106.09685) freezes the pretrained weights and injects small trainable low-rank matrices at each attention layer. This cuts trainable parameters by 10,000x while preserving 95-99% of full fine-tuning quality.
QLoRA (Dettmers, Pagnoni et al., NeurIPS 2023; arXiv:2305.14314) goes further: it loads the base model in 4-bit NormalFloat (NF4) quantization, then trains LoRA adapters in bf16 on top. The result is a 12B model fine-tunable on a single GPU with ~12 GB of VRAM.
┌──────────────────────────────────────────────────────┐
│ Base Model (frozen, 4-bit NF4 quantized) │
│ │
│ ┌─────────┐ ┌─────────┐ │
│ │ q_proj │ ──▶ │ LoRA A │──▶ LoRA B ──▶ + ──▶ │
│ │ (frozen) │ │ (r=32) │ (r=32) merge │
│ └─────────┘ └─────────┘ │
│ │
│ Same pattern for v_proj, k_proj, o_proj │
└──────────────────────────────────────────────────────┘The key hyperparameters:
| Parameter | Recommended | Why |
|---|---|---|
LoRA rank (r) | 16–64 | Higher = more capacity, more memory. 32 is the sweet spot for most tasks. |
| LoRA alpha | 2 × rank | Scaling factor. Convention is alpha = 2r. |
| Target modules | q_proj, v_proj minimum | Add k_proj, o_proj, gate_proj, up_proj for more capacity if rank alone isn't enough. |
| Learning rate | 1e-4 | For LoRA specifically. Full fine-tuning uses 2e-5. |
| Epochs | 2–4 | More epochs on small datasets = overfitting. |
| Batch size | 4–8 (with gradient accumulation) | Effective batch of 32 via accumulation is standard. |
Dataset preparation
Gemma 3 uses a specific chat template. Your training data must match it exactly:
<start_of_turn>user
Classify this customer message into one of: [billing, technical, account, other].
Message: "I can't log in and the reset email never arrives"
<end_of_turn>
<start_of_turn>model
technical
<end_of_turn>Format your dataset as JSONL with a messages array:
import json
def format_example(input_text: str, label: str, task_prompt: str) -> dict:
return {
"messages": [
{"role": "user", "content": f"{task_prompt}\nMessage: \"{input_text}\""},
{"role": "model", "content": label},
]
}
# Generate training file
with open("train.jsonl", "w") as f:
for example in training_data:
record = format_example(example["text"], example["label"], TASK_PROMPT)
f.write(json.dumps(record) + "\n")Dataset sizing guidelines:
| Examples | Expected outcome |
|---|---|
| 100–500 | Marginal improvement. Better than zero-shot, worse than few-shot for many tasks. |
| 500–2,000 | Reliable improvement for classification and extraction. The minimum for production. |
| 2,000–10,000 | Strong domain adaptation. Diminishing returns above this for most structured tasks. |
| 10,000+ | Full domain specialization. Worth it for high-stakes production systems. |
Quality matters more than quantity. 500 carefully curated examples outperform 5,000 noisy ones. Curate aggressively: remove ambiguous labels, deduplicate near-identical examples, balance class distribution.
Training with Hugging Face + PEFT
The most portable approach — works on any GPU (local, cloud, Colab):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model
from trl import SFTTrainer, SFTConfig
MODEL_ID = "google/gemma-3-12b-it"
# 4-bit quantization config
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
quantization_config=bnb_config,
device_map="auto",
)
# LoRA configuration
lora_config = LoraConfig(
r=32,
lora_alpha=64,
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
lora_dropout=0.05,
task_type="CAUSAL_LM",
)
# Training
trainer = SFTTrainer(
model=model,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
peft_config=lora_config,
args=SFTConfig(
output_dir="./gemma-finetuned",
num_train_epochs=3,
per_device_train_batch_size=4,
gradient_accumulation_steps=8,
learning_rate=1e-4,
lr_scheduler_type="cosine",
warmup_ratio=0.1,
bf16=True,
logging_steps=10,
eval_strategy="steps",
eval_steps=50,
save_steps=100,
max_seq_length=4096,
),
)
trainer.train()
trainer.save_model("./gemma-finetuned")Memory footprint: ~12 GB VRAM for 12B with QLoRA. Fits on a T4 (16 GB), comfortably on an A100 (40/80 GB).
Training on Vertex AI
For teams on Google Cloud, Vertex AI offers managed fine-tuning that abstracts GPU provisioning:
Option 1: Managed Tuning (simplest)
Upload your JSONL to GCS, select gemma-3-12b-it from the Model Garden, configure adapter size and epochs, and launch. Vertex handles infrastructure, checkpointing, and artifact management. Limited hyperparameter control.
Option 2: Custom Training Job (full control)
Package your training script in a Docker container and submit via gcloud ai custom-jobs create. You specify the GPU type (A100 recommended), instance count, and training code. This gives you full access to the training loop — learning rate schedules, custom evaluation, early stopping.
gcloud ai custom-jobs create \
--region=us-central1 \
--display-name=gemma-finetune \
--worker-pool-spec=machine-type=a2-highgpu-1g,replica-count=1,container-image-uri=gcr.io/your-project/gemma-trainer:latestOption 3: KerasNLP (Google's recommended path)
import keras_nlp
model = keras_nlp.models.GemmaCausalLM.from_preset("gemma3_instruct_12b")
model.backbone.enable_lora(rank=16)
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy")
model.fit(train_ds, epochs=3, validation_data=val_ds)KerasNLP works across JAX, TensorFlow, and PyTorch backends. JAX on TPUs is the highest-throughput option for large-scale fine-tuning.
Evaluation
Fine-tuning without evaluation is guesswork. Measure three things:
1. Task-specific metrics. For classification: accuracy, F1, precision, recall per class. For extraction: exact match, token-level F1. For generation: ROUGE, BERTScore.
from sklearn.metrics import classification_report
preds = [generate(model, tokenizer, x) for x in test_inputs]
print(classification_report(test_labels, preds))2. LLM-as-judge quality. For subjective tasks, use a stronger model (Gemini 2.5 Pro) to evaluate output quality on a rubric. This technique is well-established — Zheng et al. (NeurIPS 2023; arXiv:2306.05685) showed that strong LLM judges achieve 80%+ agreement with human evaluators.
3. Regression detection. Fine-tuning can cause catastrophic forgetting (McCloskey & Cohen, 1989) — the model gets better at your task but worse at general capabilities. Track perplexity on a general benchmark (MMLU subset, HellaSwag) before and after. If general performance drops more than 5%, you're overfitting.
Common failure modes
Overfitting on small datasets. Symptom: training loss drops to near-zero while eval loss rises after epoch 1. Fix: reduce epochs to 2, increase LoRA dropout to 0.1, add data augmentation (paraphrase examples via Gemini).
Learning rate too high. Symptom: loss spikes or oscillates, model outputs become incoherent. For LoRA, start at 1e-4 and reduce if unstable. Full fine-tuning needs 2e-5 or lower.
Template mismatch. Symptom: fine-tuned model ignores instructions or produces malformed output. Fix: ensure training data uses the exact Gemma chat template including <start_of_turn> and <end_of_turn> tokens.
Context length mismatch. Symptom: degraded quality on long inputs at inference despite good training metrics. Fix: train at the sequence length you'll serve. If your production inputs are 2K tokens, don't train at 512.
When not to fine-tune
Fine-tuning is the wrong tool when:
- Prompt engineering suffices. If few-shot examples in the prompt achieve your quality bar, save the engineering effort. Fine-tuning is an optimization, not a first resort.
- Your data changes frequently. Fine-tuned models are frozen in time. If your categories, labels, or domain knowledge shift monthly, RAG (which updates the knowledge base without retraining) is more maintainable.
- You need citations or attribution. Fine-tuned models internalize knowledge without source tracking. RAG preserves provenance.
Conclusion
Fine-tuning Gemma 3 is a well-understood workflow with production-grade tooling. QLoRA makes it accessible on consumer GPUs; Vertex AI makes it manageable at scale. The hard parts aren't the framework — they're the dataset curation, the evaluation rigor, and knowing when fine-tuning is the right tool versus prompt engineering or RAG.
Start with 500 curated examples and QLoRA on the 4B model. Validate the approach works for your task. Then scale to 12B with more data if needed. Measure everything.
Further reading:
- Hu et al., "LoRA: Low-Rank Adaptation of Large Language Models" (arXiv:2106.09685)
- Dettmers et al., "QLoRA: Efficient Finetuning of Quantized LLMs" (arXiv:2305.14314)
- Gemma Team, "Gemma: Open Models Based on Gemini Research" (arXiv:2403.08295)
- Vertex AI Model Garden — Gemma
- Hugging Face Gemma 3 collection