Skip to content

Conversation

@mmathew23
Copy link
Collaborator

Qwen3 VL and other models declare accepts_loss_kwargs which can influence whether or not the final loss is loss / gradient_accumulation_steps. Qwen3VL, Gemma3 set this to False in transformers 4.57 which means the loss is double scaled down. Unsloth has already scaled the loss by this point, so this PR changes the behavior to not let accepts_loss_kwargs take priority.

qwen 3 vl notebook now show eval and train loss in line:
https://colab.research.google.com/drive/1pd2Boa3p-aY1u-plHSMegsQ-7CfPv0Rw?usp=sharing

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @mmathew23, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves a critical bug affecting gradient accumulation for specific models, such as Qwen3 VL, when used with transformers version 4.57. By strategically patching the Trainer class, it prevents an unintended double scaling of the loss, ensuring accurate training and evaluation metrics. The change guarantees that Unsloth's intended loss handling takes precedence, leading to correct model behavior during training.

Highlights

  • Corrected Loss Scaling: Fixed an issue where models like Qwen3 VL and Gemma3 in transformers 4.57 caused double scaling of loss during gradient accumulation due to their accepts_loss_kwargs declaration.
  • Trainer Patching Enhancement: The patch_gradient_accumulation_fix function was modified to specifically patch both Trainer.training_step and Trainer.__init__.
  • Training Step Logic Update: The Trainer.training_step patch now conditionally applies loss scaling based on num_items_in_batch and explicitly forces self.model_accepts_loss_kwargs to False to prevent conflicts.
  • Initializer Override: A new patch for Trainer.__init__ was introduced to force the accepts_loss_kwargs check to False, ensuring Unsloth's loss handling takes precedence.
  • Validation: A Colab notebook is linked to demonstrate the correct eval and train loss in line after the fix has been applied.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request addresses a double-scaling issue with gradient accumulation for models like Qwen3 VL and Gemma3. The fix involves patching Trainer.__init__ to prevent transformers from applying its own loss scaling when Unsloth has already done so. The implementation correctly identifies and modifies the hasattr(..., 'accepts_loss_kwargs') check using source code manipulation, which is consistent with the existing patching style in this file.

My review includes a couple of suggestions to improve code maintainability by reducing duplication. Overall, the changes look good and effectively solve the described problem.

Comment on lines +1702 to +1713
# Import all variables that need importing
import transformers.trainer

items_in_trainer = dir(transformers.trainer)
good_items = []
for item in items_in_trainer:
if item in function:
good_items.append(item)
exec(
"from transformers.trainer import ("
+ ", ".join(x for x in good_items)
+ ")",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This block of code for dynamically importing dependencies is duplicated in the new patch for Trainer.__init__ (lines 1758-1771). To improve maintainability and reduce code duplication, consider extracting this logic into a helper function.

You could define a helper function like this:

def _import_dependencies_from_source(source_code: str, global_namespace: dict):
    """Dynamically imports dependencies found in source_code from transformers.trainer."""
    import transformers.trainer
    items_in_trainer = dir(transformers.trainer)
    good_items = [item for item in items_in_trainer if item in source_code]
    if good_items:
        exec(
            f"from transformers.trainer import ({', '.join(good_items)})",
            global_namespace,
        )

Then you could replace this block and the one at lines 1758-1771 with a call to this helper, for instance:
_import_dependencies_from_source(function, globals())

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@danielhanchen danielhanchen merged commit 38bdbed into unslothai:main Nov 15, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants