How to fine-tune Gemma 4 on one GPU
Choose RAG, QLoRA or full tuning, check VRAM for all five Gemma 4 sizes, and follow Google’s single-GPU example from dataset to serving.
Published

A support bot that invents a return window needs the store’s current policy. A bot that has the policy and still answers in the wrong language has a different problem. As of November 2026, Google’s Gemma 4 tuning guide gives an engineer with one GPU a way to tell which failure calls for retrieval and which is worth a training run.
What would fix a failed answer?
Take a real prompt Gemma gets wrong. Give it the missing source, the desired output format and an example of a good answer. If the corrected prompt works, you have a baseline. If the source changes tomorrow, your application needs to fetch the new version. If the same mistake recurs across different inputs with the right evidence already present, collect examples of the behavior you want to teach.
LoRA and full fine-tuning describe which weights change. Either can implement supervised training. LoRA freezes the base and learns small matrices alongside its layers. QLoRA also stores the frozen base in 4-bit precision. Full fine-tuning updates the entire checkpoint. Google suggests considering it for a large dataset, a substantial shift in output style or a checkpoint destined for further alignment. For a support tool that needs both fresh policy and consistent replies, retrieval and an adapter can work together. Google’s decision table · Full fine-tuning guide
Pick the checkpoint before preparing the data
As of Nov 28, 2026 · Source: Google Gemma fine-tuning overview
Google’s rule of thumb is to start with the instruction-tuned checkpoint for almost everything. For example, google/gemma-4-12B-it already recognizes chat turns, follows instructions and knows when to stop. Most teams can start there and use SFT or reinforcement learning. That advice also applies to tool use, vision and audio tuning on checkpoints that support the task.
Choose the pre-trained checkpoint, such as google/gemma-4-12B, for continued pre-training on a substantial corpus or for building your own chat template. It completes documents. Budget for the work of teaching conversation afterward if the final product is a chat assistant. If a smaller production model is the goal, the teacher’s verified answers can become the student’s training data. Gemma checkpoint guide · Model distillation for production
Which Gemma 4 size fits one GPU?
Google gives the following approximate peak training VRAM at a sequence length of 2,048 tokens. Training needs memory for activations as well as weights. Each trainable weight also needs a gradient and optimizer state, which is why a card that runs a checkpoint can still be too small to update it.
For a rented example, Runpod lists an NVIDIA L4 with 24 GB. The 12B QLoRA estimate leaves room on that card. Even E2B full tuning exceeds its capacity. The 31B QLoRA estimate comes close to the limit, and Google’s larger-model guidance uses gradient checkpointing. For 26B A4B, the inactive experts still occupy memory. Use its dedicated mixture-of-experts recipe, which freezes the router. Google’s memory table · Model-specific settings · MoE recipe · Runpod L4 specifications
Treat these numbers as sizing estimates. Google’s actual E2B QLoRA example reports a peak under 10 GB with a per-device batch of 2. Before paying for a bigger card, check the sequence length and batch size in your own configuration. If the task is coding, compare the unmodified checkpoint on representative prompts first. Google’s QLoRA run · Local models for coding
Run Google’s E2B QLoRA example
Google’s notebook teaches google/gemma-4-E2B-it to reason in a specified language and give the final answer in English. That task has a useful acceptance test. You can check each language separately on a prompt held out of training. The cells below follow the notebook’s settings for one GPU with bfloat16 support. Google’s E2B notebook
Install the libraries and format the examples
Run the install cell in a GPU notebook. The model and dataset downloads need network access. The training configuration saves the adapter locally.
%pip install -q -U "transformers>=5.10.1" "trl>=0.16.0" "peft>=0.19.0" accelerate datasets bitsandbytes torchao
%pip install -q -U evaluate sacrebleu jiwer pillow soundfile librosa matplotlib tensorboardKeep the instructions and user message in prompt. Put the target assistant turn in completion. For this text dataset, TRL then excludes the prompt tokens from the loss while allowing the model to attend to them. Gemma’s chat template supplies the turn boundaries. In Google’s language task, the reasoning trace and final answer belong in separate fields so the template can place them correctly. Dataset formatting and loss masking
from datasets import load_dataset
def create_conversation(sample):
system_message = (
f"reasoning language: {sample['reasoning_language']}\n\n{sample['developer']}"
).strip()
return {
"prompt": [
{"role": "system", "content": system_message},
{"role": "user", "content": sample["user"]},
],
"completion": [
{
"role": "assistant",
"reasoning_content": sample["analysis"],
"content": sample["final"],
},
],
"chat_template_kwargs": {"enable_thinking": True},
}
dataset = load_dataset("HuggingFaceH4/Multilingual-Thinking", split="train")
dataset = dataset.map(create_conversation, remove_columns=dataset.features)
dataset = dataset.train_test_split(test_size=0.1, seed=42)For a ticket classifier, the equivalent completion would contain the approved priority label. Hold out real tickets with the same labeling rules. Decide how to grade them before training so that success means a better classification on an unseen ticket.
Load the frozen base and choose the trainable layers
The base is stored in NF4 and unpacked for bfloat16 computation. The adapter’s rank is 16 and its alpha is 32. The target list covers attention and feed-forward projections in the text decoder. The exclusion keeps the vision and audio towers out of the update.
import torch
from transformers import AutoProcessor, BitsAndBytesConfig
model_id = "google/gemma-4-E2B-it"
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_quant_storage=torch.bfloat16,
)
processor = AutoProcessor.from_pretrained(model_id)
tokenizer = processor.tokenizer
from peft import LoraConfig
peft_config = LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.0,
bias="none",
target_modules=[
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
],
exclude_modules=r"model\.(vision_tower|audio_tower)\..*",
task_type="CAUSAL_LM",
)Record a baseline, then train once
Use the notebook’s held-out example before training. Keeping special tokens during decoding lets the processor separate the thinking channel and the final answer. Release the inference copy before the trainer loads the model.
from transformers import AutoModelForMultimodalLM
torch.manual_seed(42)
base_model = AutoModelForMultimodalLM.from_pretrained(
model_id,
quantization_config=quantization_config,
device_map="auto",
)
test_sample = dataset["test"][5]
prompt = processor.apply_chat_template(
test_sample["prompt"],
tokenize=False,
add_generation_prompt=True,
enable_thinking=True,
)
inputs = processor(text=prompt, return_tensors="pt").to(base_model.device)
input_len = inputs["input_ids"].shape[-1]
outputs = base_model.generate(**inputs, max_new_tokens=1024)
response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)
result = processor.parse_response(response, prefix="")
print(result["thinking"], result["content"], sep="\n")
del base_model, inputs, outputs
torch.cuda.empty_cache()Google uses one epoch, a learning rate of 2e-4 and gradient accumulation over 8 small batches. Evaluation runs at the start and at the epoch boundary. The final save writes adapter weights. Google’s trainer configuration
from trl import SFTConfig, SFTTrainer
args = SFTConfig(
output_dir="gemma-4-multilingual-thinking",
max_length=2048,
num_train_epochs=1,
per_device_train_batch_size=2,
per_device_eval_batch_size=2,
gradient_accumulation_steps=8,
optim="paged_adamw_8bit",
logging_steps=10,
save_strategy="epoch",
eval_strategy="epoch",
eval_on_start=True,
learning_rate=2e-4,
weight_decay=0.01,
warmup_steps=0.05,
lr_scheduler_type="cosine",
max_grad_norm=1.0,
bf16=True,
model_init_kwargs={"dtype": torch.bfloat16},
push_to_hub=False,
report_to="tensorboard",
)
trainer = SFTTrainer(
model=model_id,
args=args,
train_dataset=dataset["train"],
eval_dataset=dataset["test"],
processing_class=tokenizer,
quantization_config=quantization_config,
peft_config=peft_config,
)
trainer.train()
trainer.save_model()For a longer run, watch validation loss. If it starts rising while training loss keeps falling, Google recommends selecting the checkpoint with the lowest validation loss. If you move to full tuning, revise the optimizer and learning rate as well as the memory budget. The full-tuning guide explains why its 8-bit TorchAO AdamW handles the compact models’ large embedding tables differently from the paged optimizer above. Best practices · Full-tuning optimizer guidance
Check what the adapter actually learned
Google’s notebook asks for the return policy in a held-out conversation. Its baseline and merged checkpoint answer the same prompt. The comparison below summarizes Google’s published example.
English reasoning despite the request for French.
Replies in French and asks which product the user means.
The model reasons about the return request in French.
Replies in English and supplies a 30-day return window.
The adapter fixed the language of the reply. Where did the return window come from? The test prompt supplied no store policy. For a support deployment, score language adherence and policy accuracy separately. Retrieve the actual policy, run the same held-out requests through the original and tuned checkpoints, and check each stated term against the retrieved text. Google’s before-and-after example
Choose a training framework or coding agent
Google’s Python example uses Hugging Face Transformers to load Gemma, PEFT to define the adapter and TRL to train it. The overview also names Unsloth for single-GPU tuning and direct GGUF export, Axolotl for YAML-configured jobs on one or more GPUs, Vertex AI for managed tuning, and Google Kubernetes Engine (GKE) for multi-GPU training on Kubernetes. Google’s framework list · Unsloth guide
If you work through a coding agent, Google’s overview gives this global install command for its gemma-trainer skill.
npx skills add google-gemma/gemma-skills --skill gemma-trainer --globalGive the agent the dataset path, the task, the GPU capacity and the criterion for a good answer. For support tickets, specify which field holds the input and which holds the approved label. The skill checks the data and chat template, proposes settings for the available memory, prepares the training script, and compares held-out outputs before export. Review the proposed checkpoint and examples while changes are still cheap. Gemma trainer skill
Export the artifact your serving system expects
The QLoRA run saves adapter_model.safetensors alongside its adapter configuration. For a shared vLLM service, you can keep adapters separate, load their matching base once, enable --enable-lora, register each adapter with --lora-modules, and select its registered name per request.
For a standalone checkpoint, release the trainer and reload the original model in bfloat16. Budget enough memory for that higher-precision copy. Merging directly into quantized weights introduces rounding error. Save the processor with the weights so the deployed model receives the same chat format.
del trainer
torch.cuda.empty_cache()
from peft import PeftModel
base_model = AutoModelForMultimodalLM.from_pretrained(
model_id,
low_cpu_mem_usage=True,
dtype=torch.bfloat16,
device_map="auto",
)
peft_model = PeftModel.from_pretrained(base_model, args.output_dir)
merged_model = peft_model.merge_and_unload()
merged_model.save_pretrained("merged_model", safe_serialization=True, max_shard_size="2GB")
processor.save_pretrained("merged_model")
del base_model, peft_model, merged_model
torch.cuda.empty_cache()Before serving, reload merged_model and its processor, run the same held-out prompt with the same generation settings, and compare the parsed answer with your acceptance criteria. For a merged E2B or E4B on one GPU, Google’s vLLM command starts the server.
vllm serve ./merged_model \
--dtype bfloat16 \
--max-model-len 32768For llama.cpp or Ollama, convert the merged directory to FP16 GGUF, then quantize that file. These commands assume a local llama.cpp checkout with its quantizer built.
python llama.cpp/convert_hf_to_gguf.py ./merged_model \
--outfile model-f16.gguf --outtype f16
./llama.cpp/build/bin/llama-quantize model-f16.gguf model-q4_k_m.gguf Q4_K_MFor E2B or E4B on mobile, Google’s LiteRT-LM exporter creates a .litertlm bundle. Use --externalize_embedder to separate the per-layer embedding table from the active weights. Choose the export that matches the device where the model will answer, then repeat the held-out check there. Google’s export commands · Local serving options
Best local LLMs for your hardware
Compare untuned models for the machine where you plan to serve the finished application.
- Published
- Category
- Build







