Skip to content

Bug Report: ValueError: Attempting to unscale FP16 gradients during training with `fp16=False (ModernBERT-large) #2902

Closed

Description

@bx0-0

Bug Report: ValueError: Attempting to unscale FP16 gradients during training with fp16=False

📌 Summary

I'm experiencing a runtime crash when fine-tuning answerdotai/ModernBERT-large using unsloth.FastModel with fp16=False. The error indicates that FP16 gradients are being used and attempted to be unscaled, even though automatic mixed precision (AMP) is explicitly disabled.


Reproduction Steps

Here is the minimal code to reproduce:

from unsloth import FastModel
from transformers import Trainer, TrainingArguments
from transformers.trainer_utils import OptimizerNames
import torch

model, tokenizer = FastModel.from_pretrained(
    model_name = "answerdotai/ModernBERT-large",
    load_in_4bit = False,
    max_seq_length = 2048,
    auto_model = None,  # Default model
    dtype = None,
)

# Just for safety (still leads to error)
model = model.to(torch.float32)

trainer = Trainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
    args=TrainingArguments(
        output_dir="outputs",
        num_train_epochs=3,
        per_device_train_batch_size=8,
        gradient_accumulation_steps=1,
        fp16=False,
        bf16=False,
        optim=OptimizerNames.ADAMW_TORCH,
        learning_rate=5e-5,
        save_strategy="epoch",
        evaluation_strategy="epoch",
        logging_strategy="epoch",
        report_to="none",
    ),
)

trainer.train()

💥 Error Traceback

ValueError: Attempting to unscale FP16 gradients.

❓Expected Behavior

The training should proceed normally with full precision (fp32) since both fp16 and bf16 are explicitly set to False. No gradient unscaling or AMP logic should be triggered in this configuration.


💡 Suspected Cause

It seems like FastModel.from_pretrained() might still initialize some parts of the model or layers in float16 or c10::Half, regardless of fp16=False in training args.


🧪 Environment

  • unsloth version: latest
  • transformers: 4.41.x
  • torch: 2.3.x
  • GPU: T4
  • Python: 3.11

✅ Workaround Attempted

I’ve tried forcing the model to float32 with:

model = model.to(torch.float32)
for param in model.parameters():
    param.data = param.data.to(torch.float32)

But the error still persists.


🙏 Request

Please verify if FastModel or ModernBERT initializes with float16 layers by default. If so, consider providing a flag to fully opt-out of any low-precision mode during model loading.

Thanks a lot for the great work on unsloth! It's incredibly fast and well-documented ❤️

Activity

  1. bx0-0 commented on Jul 8, 2025

    @bx0-0
    Author

    Also, just to confirm it's not an issue on my end:
    Even when I run your official notebook [here](https://colab.research.google.com/github/timothelaborie/text_classification_scripts/blob/main/bert_classification.ipynb) without any modifications, I still get the exact same error:

    ValueError: Attempting to unscale FP16 gradients.
    

    So it seems like the issue is reproducible even in your own default setup.

  2. Etherll commented on Aug 5, 2025

    @Etherll
    Collaborator

    Hi, if you want to use full param training please set full_finetuning=True, in FastModel.from_pretrained
    instead of

    # make all parameters trainable
    for param in model.parameters():
        param.requires_grad = True
  3. danielhanchen commented on Sep 15, 2026

    @danielhanchen
    Member

    Fixed! ModernBERT-large loaded in fp16, cast to fp32 and trained with a plain Trainer completes without the unscale error. Two things for the current release: pass auto_model set to AutoModelForSequenceClassification for a classifier, and use full_finetuning=True rather than flipping requires_grad by hand.

    Please update Unsloth: uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir (if it's not in the current release yet it'll be in the next one). Reopen if it still happens!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions