{"slug": "fine-tuning-gemma-4-12b-on-gpu-produces-nan-grads", "title": "Fine-tuning Gemma 4 12B on GPU produces nan grads", "summary": "A developer reports that fine-tuning Google's Gemma 4 12B on GPU with a single example produces NaN gradients in the lm_head weights, while identical code on CPU returns finite gradients. The minimal reproduction, run with Python v3.14.10, Transformers v5.24.1 and PyTorch v2.15.0, calls backward() on a one-sentence loss in bfloat16 and shows torch.isnan on model.lm_head.weight.grad returning True on cuda:0 and False on CPU, contradicting the usual fp16 or oversized-gradient explanations.", "body_md": "I’m trying to fine-tune Gemma 4 12B, but I’m running into an issue where fine-tuning it on sometimes even a single example produces nan grads on GPU. I’ve been able to find a very simple example that shows this and seems to be reproducible (at least, for me):\n\n``` python\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained('google/gemma-4-12B')\ntokenizer = AutoTokenizer.from_pretrained('google/gemma-4-12B')\n\nmodel = model.to('cuda')\n\ninputs = tokenizer('This is a test.', return_tensors='pt')\ninputs = {k: v.to(model.device) for k, v in inputs.items()}\ninputs['labels'] = inputs['input_ids'].detach().clone()\n\nprint(model.lm_head.weight.grad) # prints \"None\"\nprint(torch.any(torch.isnan(model.lm_head.weight))) # prints \"tensor(False)\"\n\noutputs = model(**inputs)\noutputs.loss.backward()\n\nprint(torch.any(torch.isnan(model.lm_head.weight.grad))) # prints \"tensor(True, device='cuda:0')\"\n```\n\nMost of the advice I’ve found about this elsewhere assumes that nans come in when updating the weights because the grads are too large/too small, or that it has to do with using fp16. But the source of the nans in my case in the grads themselves; and Gemma 4 uses bfloat16 by default, which is supposed to be a fix for nans (though clearly it doesn’t seem to be working in this case).\n\nOddly enough, running the same code as above with the model on the CPU works fine:\n\n``` python\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained('google/gemma-4-12B')\ntokenizer = AutoTokenizer.from_pretrained('google/gemma-4-12B')\n\ninputs = tokenizer('This is a test.', return_tensors='pt')\ninputs['labels'] = inputs['input_ids'].detach().clone()\n\nprint(model.lm_head.weight.grad) # prints \"None\"\nprint(torch.any(torch.isnan(model.lm_head.weight))) # prints \"tensor(False)\"\n\noutputs = model(**inputs)\noutputs.loss.backward()\n\nprint(torch.any(torch.isnan(model.lm_head.weight.grad))) # prints \"tensor(False)\"\n```\n\nThough of course, this isn’t feasible at scale since it’d take too long to fine-tune the model this way.\n\nAny idea how to fix this? It’s baffling me since it seems to be a problem that others attribute to using float16 instead of bfloat16, or which is an issue with gradients being too large or small, but that’s not what’s happening in my case since I’m already using bfloat16 and it’s the gradients themselves that start as nans rather than something that starts when the weights are updated.\n\nFor reference, I’m running Python v3.14.10, Transformers v5.24.1, and PyTorch v2.15.0. Happy to provide more info if needed.", "url": "https://wpnews.pro/news/fine-tuning-gemma-4-12b-on-gpu-produces-nan-grads", "canonical_source": "https://discuss.huggingface.co/t/fine-tuning-gemma-4-12b-on-gpu-produces-nan-grads/193226#post_1", "published_at": "2026-12-06 17:57:50+00:00", "updated_at": "2026-12-06 18:16:28.804216+00:00", "lang": "en", "topics": ["large-language-models", "machine-learning", "ai-research"], "entities": ["Gemma 4 12B", "Google", "PyTorch", "Transformers", "Python"], "also_reported_by": [], "takeaway": "A single-example backward pass on Gemma 4 12B in bfloat16 yields NaN lm_head gradients on CUDA but finite ones on CPU under PyTorch v2.15.0 and Transformers v5.24.1, so verify gradients on GPU before starting a fine-tune.", "recommendation": {"advice": "Before launching a Gemma 4 12B fine-tune, run one example's backward pass on GPU and check torch.isnan on lm_head.weight.grad; the reported setup produced NaNs on CUDA but not CPU.", "playbook": "training-data", "playbook_url": "https://wpnews.pro/playbooks/training-data"}, "alternates": {"html": "https://wpnews.pro/news/fine-tuning-gemma-4-12b-on-gpu-produces-nan-grads", "markdown": "https://wpnews.pro/news/fine-tuning-gemma-4-12b-on-gpu-produces-nan-grads.md", "text": "https://wpnews.pro/news/fine-tuning-gemma-4-12b-on-gpu-produces-nan-grads.txt", "jsonld": "https://wpnews.pro/news/fine-tuning-gemma-4-12b-on-gpu-produces-nan-grads.jsonld"}}