Instructions to use google/gemma-4-12B-it with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use google/gemma-4-12B-it with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("google/gemma-4-12B-it") model = AutoModelForMultimodalLM.from_pretrained("google/gemma-4-12B-it", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- AMD Developer Cloud
Gradient spikes when LoRA fine-tuning on images: cause and a simple fix
Hi Gemma team and everyone fine-tuning Gemma-4,
I ran into something while LoRA fine-tuning gemma-4-12b-it on CT images and spent a week tracking it down. Sharing it here in case it is useful, and because I would love to hear whether this is known.
What I see
- On long prompts (2,400–3,600 tokens with two or three images), the first-step LoRA gradients computed in bf16 and in fp32 agree in the upper layers (cosine ≥ 0.96) but are nearly orthogonal in the lower third of the language model (median cosine about 0.02).
- Pre-clipping gradient norms during training have a median of 8.5 and spike as high as 23,307. A full fp32 run still spikes (max 39,862), so this is not just bf16 rounding.
- The same lower-layer disagreement shows up on Gemma-4-31B, with CT images and with natural photos, and on text-only prompts of about 2,000 tokens. Qwen3.8-27B is mostly spared on the same prompts. (The cross-model checks used 4-bit weights.)
Where it comes from (12B, image prompts)
- fp32 itself is a fine reference: its gradient is unchanged by relative noise of 1e-6 on the hidden states. But at 1e-4, 7 of 10 measurements already fall below cosine 0.9, and bf16 hidden states differ from fp32 by about 1% per token. So the backward path is ill-conditioned, and bf16 just exposes it.
- Swapping bf16 hidden states into individual layers localizes the sensitivity to the MLPs of layers 19–21 at image-token positions. The backward map from layer 21 to layer 11 amplifies the gradient by 11–206× depending on the prompt.
- On the worst prompt, 54% of the squared gradient norm arriving at layer 11 sits on a single image token: a dark, low-contrast patch near the image border.
Workaround
Detach the MLP output at image-token positions in layers 19–21. The forward pass is bit-for-bit unchanged; only the backward pass differs.
# img_mask: bool tensor [seq_len], True at the image tokens of the current example
DETACH_LAYERS = {19, 20, 21}
def mlp_forward(self, x, _orig=TextMLP.forward):
y = _orig(self, x)
if layer_index[id(self)] in DETACH_LAYERS:
y = torch.where(img_mask[..., None], y.detach(), y)
return y
TextMLP.forward = mlp_forward # Gemma4TextMLP and Gemma4UnifiedTextMLP
On a CT lesion-grounding task (300 steps, batch 8, four seeds per arm):
| Validation loss | Median grad norm | Max grad norm | |
|---|---|---|---|
| Standard bf16 | 0.336 ± 0.019 | 8.5 | 23,307 |
| Standard fp32 (one run) | 0.332 | 7.7 | 39,862 |
| Layers 0–18 frozen | 0.334 ± 0.003 | 0.73 | 100 |
| Detach | 0.296 ± 0.003 | 0.63 | 125 |
Every detach run beat every other run. Step time is unchanged.
Caveats
One task, one model, 300 steps, four seeds, and a single fp32 run. The localization and the fix were tested only on 12B image prompts. Long text prompts break down more gradually, not at layers 19–21, and I have no fix for them. The detached gradient is not the true gradient; I only show that it trains better here.
Questions for the team
- Is this a known property of Gemma-4? Was anything similar visible during pretraining, or would large batches and clipping have hidden it?
- Is there a recommended way to fine-tune on long image prompts that avoids it?
- Any idea why the MLPs of these particular layers are so sensitive at low-information image patches?
Possibly related: transformers issue #45676 (gradient spikes when LoRA fine-tuning 31B on text, attributed there to near-saturated attention).
Write-up with all the details: [arXiv link]
Thanks!
Thank you for sharing this so carefully — the localization is striking, and the re-runnable detail is much appreciated.
What stood out to us is how sharply the effect is localized: near-orthogonal bf16/fp32 gradients in the lower third (median cosine about 0.02) against cosine ≥0.96 higher up, with spikes to 23,307 in bf16 and 39,862 in fp32, so the fp32 comparison makes clear this is not only bf16 rounding. The concentration at the MLPs of layers 19–21 at image-token positions, the 11–206× amplification from layer 21 to layer 11, and 54% of the squared gradient norm at layer 11 sitting on a single dark, low-contrast image token near the border, together make a compelling case for an ill-conditioned backward path rather than a generic precision problem.
The detach workaround is also interesting for the same reason: a forward pass that is bit-for-bit unchanged, yet validation loss of 0.296 ± 0.003 against 0.336 ± 0.019 for standard bf16 on the CT lesion-grounding task, with median gradient norm falling from 8.5 to 0.63 and the maximum from 23,307 to 125, at unchanged step time. We note the caveats as stated — one task, one model, and a detached gradient that is not the true gradient — so we would be cautious about generalizing beyond the reported setting, while still finding the result worth trying for others seeing similar spikes on long image prompts.
Thank you again for the careful measurements and for posting the write-up.