Skip to content

[Bug] Gradient explosion (NaN) when training Qwen 3 Reranker with Unsloth backend on A100 #3705

Closed

Description

@MosRat
  1. Did you update?
    Yes, I am using the latest version from git:
    unsloth = { git = "https://github.com/unslothai/unsloth.git" }

  2. Colab or Kaggle or local / cloud
    Local Server (Linux)

  3. Number GPUs used, use nvidia-smi
    1x NVIDIA A100 (40GB)

  4. Which notebook? Please link!
    I am running a script via ms-swift CLI, not a notebook.

  5. Which Unsloth version, TRL version, transformers version, PyTorch version?

    • Unsloth: Latest (git main)
    • PyTorch: 2.9.0 (installed via index cu128 compatible)
    • CUDA: System CUDA is 12.8
    • Transformers: <=4.56.2
    • Accelerate: 1.11
  6. Which trainer?
    SFTTrainer (wrapped by ms-swift) with loss_type="listwise_generative_reranker".

# Description of the bug:
# When training Qwen/Qwen3-Reranker-8B with task_type="generative_reranker" and tuner_backend="unsloth", 
# I encounter immediate gradient explosion resulting in NaNs.
# 
# Observations:
# 1. Normal run: Logs show `grad_norm = nan`. Loss fluctuates but gradients are broken.
# 2. Debug run: Using `torch.autograd.set_detect_anomaly(True)`, it crashes at `MmBackward0`.
# 3. I added a hook to SDPA. The gradients flowing BACK into SDPA (from MLP/Next layers) explode exponentially 
#    from 1e-6 to 1e+36 in a single step before hitting NaN.
# 4. This happens with both `attn_impl="sdpa"` and `flash_attn`.

# ------------------------------------------------------------------
# Reproduction Script (Bash via ms-swift)
# ------------------------------------------------------------------
# export CUDA_VISIBLE_DEVICES=1
# export PYTORCH_ALLOC_CONF=expandable_segments:True
# export UNSLOTH_COMPILE_DISABLE=1

# uv --preview-features extra-build-dependencies run swift sft \
#    --model Qwen/Qwen3-Reranker-8B \
#    --task_type generative_reranker \
#    --loss_type listwise_generative_reranker \
#    --train_type lora \
#    --tuner_backend unsloth \
#    --torch_dtype bfloat16 \
#    --gradient_accumulation_steps 16 \
#    --learning_rate 2e-4 \
#    --lora_rank 64 \
#    --lora_alpha 128 \
#    --dataset 'MTEB/scidocs-reranking' \
#    ... (other args standard)

# ------------------------------------------------------------------
# Stack Trace (with set_detect_anomaly=True)
# ------------------------------------------------------------------
#  output.register_hook(sdpa_check) for output of F.sdpa
# [SDPA Backward] Grad Max: 8.046e-06
# ...
# [SDPA Backward] Grad Max: 2.648e+36  <-- Explosion happens here
#
Traceback (most recent call last):
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/swift/cli/sft.py", line 121, in <module>
    sft_main()
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/swift/llm/train/sft.py", line 352, in sft_main
    return SwiftSft(args).main()
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/swift/llm/base.py", line 49, in main
    result = self.run()
             ^^^^^^^^^^
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/swift/ray/base.py", line 170, in wrapper
    return func(self, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/swift/llm/train/sft.py", line 206, in run
    return self.train(trainer)
           ^^^^^^^^^^^^^^^^^^^
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/swift/llm/train/sft.py", line 254, in train
    trainer.train(trainer.args.resume_from_checkpoint)
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/swift/trainers/trainers.py", line 57, in train
    return super().train(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/swift/trainers/mixin.py", line 815, in train
    res = super().train(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/transformers/trainer.py", line 2333, in train
    return inner_training_loop(
           ^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 325, in _fast_inner_training_loop
  File "<string>", line 91, in _unsloth_training_step
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/accelerate/accelerator.py", line 2740, in backward
    loss.backward(**kwargs)
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/torch/_tensor.py", line 625, in backward
    torch.autograd.backward(
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/torch/autograd/__init__.py", line 354, in backward
    _engine_run_backward(
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/torch/autograd/graph.py", line 841, in _engine_run_backward
    return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/torch/autograd/function.py", line 315, in apply
    return user_fn(self, *args)
           ^^^^^^^^^^^^^^^^^^^^
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/unsloth_zoo/gradient_checkpointing.py", line 598, in backward
    torch.autograd.backward(outputs_with_grad, args_with_grad)
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/torch/autograd/__init__.py", line 354, in backward
    _engine_run_backward(
  File "/home/user/workspace/ir_train/.venv/lib/python3.12/site-packages/torch/autograd/graph.py", line 841, in _engine_run_backward
    return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Function 'MmBackward0' returned nan values in its 0th output.

Additional Context:

  • not happened when use huggingface peft
  • loss is not nan and it is always changing.
  • Hardware: A100 40GB.
  • The issue seems specific to the combination of Unsloth's gradient checkpointing/Llama implementation and the Listwise Reranker loss flow.
  • Verified that disabling unsloth (using standard HF backend) avoids the immediate NaN, though memory usage is higher.

Activity

  1. danielhanchen commented on Dec 15, 2025

    @danielhanchen
    Member

    Sorry on the issue - did you try disabling gradient checkpointing? Or set use_gradient_checkpointing = True Also can u try using FastModel instead of FastLanguageModel

  2. MosRat commented on Dec 17, 2025

    @MosRat
    Author

    Sorry on the issue - did you try disabling gradient checkpointing? Or set use_gradient_checkpointing = True Also can u try using FastModel instead of FastLanguageModel

    I try to use this config changing to the following ms-swift code but it not works

    https://github.com/modelscope/ms-swift/blob/a5172ae0f1b3c632ab5ff002288841ecda2554d8/swift/llm/train/tuner.py#L250

    And sorry for not mention above, I have to change some code in unsloth-zoo
    https://github.com/unslothai/unsloth-zoo/blob/cc159de5eec55d63805562fb09d346993f6c594a/unsloth_zoo/loss_utils.py#L336

    # change here to fix ShapeError
    labels: torch.Tensor = x["labels"] # shape = (batch_size, ) in reranker tasks, one label for one seq, not token.
    labels = labels.unsqueeze(1).expand_as(x["input_ids"]) # shape = (batch_size, seq_len)
     .......
    # otherwise error raise here
    token_count &= (attention_mask[..., 1:] != 0)

    because it raise an error saying token_count &= (attention_mask[..., 1:] != 0) shape not match.

  3. fourwheels2512 commented on Feb 22, 2026

    @fourwheels2512

    Late comment but potentially useful for anyone landing here with the same NaN explosion issue:

    The Qwen reranker + A100 combination is hitting something similar to what I documented on Mistral-7B: gradient norms that blow up in a way that static max_grad_norm thresholds can't catch, because the threshold is calibrated before training sees its actual norm distribution.

    A few things that helped in my testing:

    1. Adaptive gradient clipping — instead of max_grad_norm=1.0, compute a rolling z-score over recent gradient norms and only clip steps that are statistically anomalous (e.g., >2 standard deviations above the rolling mean). This auto-calibrates as training progresses rather than using a pre-set ceiling.

    2. Check gradient norm logging — add logging_steps=1 temporarily and watch grad_norm in your logs. If you're seeing 10x+ spikes on specific steps before the NaN, it's the same root cause.

    3. For Qwen specifically — the reranker architecture has cross-attention layers that can amplify gradient variance more than decoder-only models. Reducing learning_rate by 50% and increasing warmup_ratio to 0.1 sometimes prevents the initial blowup.

    I built a free tool for testing adaptive clipping without local GPU if useful: https://huggingface.co/spaces/Fourwheels2512/crma-fine-tuner — supports Mistral, TinyLlama, Gemma. Qwen support would be a natural next model to add.

  4. self-assigned this
    on Oct 9, 2026
  5. added a commit that references this issue on Oct 11, 2026
    62354ed
  6. danielhanchen commented on Oct 11, 2026

    @danielhanchen
    Member

    Fixed! Sorry on the delay. Unsloth's training forward dropped the attention mask because it assumed right padding, and when no labels are passed (as ms-swift's generative reranker does) it also zeroes the pad embeddings, so with ms-swift's left padding every real token attended to zeroed pads and the gradients went NaN on the first step. The mask is now kept for left-padded label-less training batches; right-padded and labelled training is unchanged. Fixed in #13154 (verified on Qwen3-Reranker-0.6B and 8B, A100 and B200: NaN on every step before, finite after). The 1-D labels shape error you hit in unsloth-zoo was fixed earlier in unslothai/unsloth-zoo#1217, so the local edit to loss_utils.py is no longer needed.
    To update: 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

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions