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

How to fine-tune Gemma 4 on one GPU

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.

What the application needsWhere to startWhat you supply
Current inventory, customer records or policyRetrieval-augmented generation (RAG)Retrieve the relevant record at request time and put it in the prompt. Model weights stay fixed.
Fluency in a new language or a large specialist corpusContinued pre-trainingRaw domain text teaches vocabulary and phrasing before instruction tuning.
A repeatable output format, persona, tool schema or taskSupervised fine-tuning (SFT) with LoRAPair representative inputs with the exact responses the model should produce.
A compact E2B or E4B model that can perform a larger model’s taskSFT through distillationUse verified examples from Gemma 4 31B, including its reasoning traces, to train the smaller model.
Correctness you can score, such as SQL returning the expected rowsReinforcement learningGrade generated answers with a verifier. For judgments such as style, use preferred and rejected answer pairs.

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

Most teams can start at supervised fine-tuningThe training stages and the evidence each one consumes
How the model learns
Pre-trainingPredict the next token across a broad corpus.
Continued pre-trainingLearn from raw text in a new domain or language.
Supervised fine-tuningLearn the desired response from example conversations.
Reinforcement learningLearn from preferences or scores on generated answers.

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.

Gemma 4 modelParameter countQLoRAFull fine-tuning
E2B2B effective~7 GB~32 GB
E4B4B effective~9 GB~42 GB
12B12B~11 GB~80 GB
26B A4B26B total, 4B active per token~21 GB~160 GB
31B31B~22 GB~200 GB

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.

Python
%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 tensorboard

Keep 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

Python
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.

Python
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.

Python
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

Python
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.

One return-policy question before and after QLoRA
Original E2B-it

English reasoning despite the request for French.

Replies in French and asks which product the user means.

After QLoRA

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.

Bash
npx skills add google-gemma/gemma-skills --skill gemma-trainer --global

Give 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.

Python
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.

Bash
vllm serve ./merged_model \
    --dtype bfloat16 \
    --max-model-len 32768

For 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.

Bash
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_M

For 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

Published
Category
Build
Related Articles
Anthropic Siren: Why Agents Leave Weak Sandboxes, and What Stops Them

Anthropic Siren: Why Agents Leave Weak Sandboxes, and What Stops Them

Siren tests whether Claude leaves a weakened sandbox. Describing the sandbox's rules cut that by 68% to 96%. What to set up, and what still needs a wall.Nov 28, 2026Build
Blender MCP

Blender MCP

Choose the right Blender MCP, connect it to Claude or another client, and try three scene questions before letting an assistant edit your file.Nov 28, 2026Build
Qwen 3.8 27B: Can Your Machine Run It?

Qwen 3.8 27B: Can Your Machine Run It?

Choose a Qwen 3.8 27B download for a 16 GB or 24 GB GPU or a 32 GB Mac, then start a local chat with Ollama or LM Studio.Nov 28, 2026Build
Grok Build: What It Is, What It Costs, and How to Start

Grok Build: What It Is, What It Costs, and How to Start

Install Grok Build, sign in, and ask your first question about a project. See the commands for macOS, Linux, WSL, and Windows and the model it uses.Nov 27, 2026Build
Claude Dreaming: How Dreams Rebuild an Agent's Memory Between Sessions

Claude Dreaming: How Dreams Rebuild an Agent's Memory Between Sessions

Claude dreaming in Managed Agents: what a dream reads, the new memory store it writes, the request line by line, how to review it, and what it costs.Nov 27, 2026Build
Vercel Workflow SDK 5.8: Which Steps Are Safe to Run Early?

Vercel Workflow SDK 5.8: Which Steps Are Safe to Run Early?

Vercel cut step-to-step overhead from 85 ms to 7 ms. See how speculative execution works, which steps need a retry policy, and how to roll out the upgrade.Nov 27, 2026Build
Claude Agent Teams: Setup, Use Cases and Limits

Claude Agent Teams: Setup, Use Cases and Limits

Enable Claude Code agent teams, split a review across sessions, and choose when peer discussion earns the extra usage. Includes setup and recovery steps.Nov 27, 2026Build
Odysseus AI: The Official Repository, What It Does, and How to Start

Odysseus AI: The Official Repository, What It Does, and How to Start

Find PewDiePie’s official Odysseus repository and demo, see how local and external models connect, and start the workspace with its Docker commands.Nov 27, 2026Build
Newsletter

One letter, every Sunday.Working systems, not hot takes.

Weekly. No spam. Unsubscribe anytime.