Skip to content

Disable gradient checkpointing when explicitly off for vision - #3879

Merged
danielhanchen merged 1 commit into
unslothai:mainfrom
ducviet00:fix-gc
Jan 14, 2026
Merged

danielhanchen merged 1 commit into
unslothai:mainfrom
ducviet00:fix-gc

Conversation

@ducviet00

@ducviet00 ducviet00 commented Jan 12, 2026 •

Copy link
Copy Markdown
Contributor

When training Qwen3-VL with gradient_checkpointing=False, the process fails with an AttributeError. The error originates from Qwen3VLVisionBlock expecting a _gradient_checkpointing_func attribute that is not present when checkpointing is disabled.

AttributeError: 'Qwen3VLVisionBlock' object has no attribute '_gradient_checkpointing_func'. Did you mean: 'gradient_checkpointing'?

The issue appears to be located in unsloth_compiled_cache/UnslothSFTTrainer.py, generated by rl.py.

While FastVisionModel.for_training is called, it re-enable/configure gradient checkpointing do not properly in vision.py:

        m = model
        while hasattr(m, "model"):
            _for_training(m)
            m = m.model
        _for_training(m)
        model.train()  # to turn on training on modules deeper in

        # Since transformers 4.53, must turn on explicitly
        for module in model.modules():
            if hasattr(module, "gradient_checkpointing"):
                module.gradient_checkpointing = True # should be use_gradient_checkpointing

Version:

unsloth			2026.1.2
unsloth-zoo		2026.1.2
transformers	4.57.3
trl				0.24.0
Training Script ```python USE_GRAD_CHECKPOINTING = False model, tokenizer = FastVisionModel.from_pretrained( MODEL_PATH, max_seq_length=MAX_LEN, load_in_4bit=False, load_in_8bit=False, load_in_16bit=True, use_gradient_checkpointing=USE_GRAD_CHECKPOINTING, device_map=device_map, ) ... model = FastVisionModel.get_peft_model( model, finetune_vision_layers=False, finetune_language_layers=True, finetune_attention_modules=True, finetune_mlp_modules=True, use_gradient_checkpointing=USE_GRAD_CHECKPOINTING, r=LORA_RANK, lora_alpha=LORA_RANK, lora_dropout=0, bias="none", random_state=3407, use_rslora=False, loftq_config=None, max_seq_length=MAX_LEN, )
FastVisionModel.for_training(model, use_gradient_checkpointing=USE_GRAD_CHECKPOINTING)  # Enable for training!
data_collator = UnslothVisionDataCollator(
    model,
    tokenizer,
)
trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    data_collator=data_collator,
    train_dataset=train_conversation_dataset,
    eval_dataset=eval_conversation_dataset,
    args=SFTConfig(
        per_device_train_batch_size=4,
        per_device_eval_batch_size=32,
        gradient_checkpointing=USE_GRAD_CHECKPOINTING,
        gradient_accumulation_steps=1,
        ...
    ),
)
</details>

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @ducviet00, 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 implements a comprehensive solution to fully control and disable gradient checkpointing for vision models within the framework. By integrating the gradient_checkpointing setting from training arguments directly into the model's training preparation logic, it provides the flexibility to conditionally activate or deactivate this memory optimization technique, addressing scenarios where it might not be desired or beneficial for vision-specific tasks.

Highlights

  • Dynamic Gradient Checkpointing Control: Introduced a mechanism to dynamically retrieve the gradient_checkpointing setting from training arguments within unsloth/models/rl.py.
  • Conditional Gradient Checkpointing for Vision Models: Modified the _for_training function in unsloth/models/vision.py to accept and utilize a use_gradient_checkpointing parameter, allowing for explicit enabling or disabling of gradient checkpointing for vision modules.
  • Complete Disablement Capability: Ensured that the gradient_checkpointing status is consistently passed to the model's training preparation methods, enabling complete control over its activation, specifically allowing for its full disablement for vision models as per the PR title's intent.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

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. ↩

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

Copy link
Copy Markdown
Contributor

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 correctly implements the ability to disable gradient checkpointing by propagating the gradient_checkpointing setting from training arguments down to the model's modules. The changes in unsloth/models/rl.py and unsloth/models/vision.py work together to achieve this. I've added one comment in unsloth/models/vision.py regarding a minor code redundancy that could be refactored for better clarity and maintainability. Overall, the changes are logical and address the intended goal.

Comment thread unsloth/models/vision.py
Comment on lines 1274 to +1276
for module in model.modules():
if hasattr(module, "gradient_checkpointing"):
module.gradient_checkpointing = True
module.gradient_checkpointing = use_gradient_checkpointing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

While this change is correct and necessary to propagate the use_gradient_checkpointing setting, there appears to be a redundancy in how gradient_checkpointing is being set.

The _for_training function (defined at line 1250) also sets m.gradient_checkpointing = use_gradient_checkpointing inside a while loop that iterates through the model hierarchy (lines 1266-1270). This for loop here does the same, but for all modules recursively.

To improve code clarity and avoid setting the attribute twice on some modules, consider consolidating this logic. Relying only on this for loop would be sufficient and clearer, as model.modules() is more comprehensive. You could then remove the gradient_checkpointing logic from the _for_training helper function.

@ducviet00 ducviet00 changed the title Complete disable gradient_checkpointing for vision Disable gradient checkpointing when explicitly off for vision Jan 12, 2026

@Datta0 Datta0 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yeah this does make sense to me

@danielhanchen
danielhanchen merged commit 33b0343 into unslothai:main Jan 14, 2026
@davedgd

davedgd commented Feb 11, 2026

Copy link
Copy Markdown
Contributor

It may be worth mentioning that this patch in rl.py broke gradient checkpointing when using TrainingArguments inside SFTTrainer since version 2026.1.3 (due to TrainingArguments implicitly defaulting it to False). Thankfully this is quickly fixed by swapping TrainingArguments with SFTConfig. I bring it up because this took some time to discover when OOM issues arose with code based on older notebooks that still used TrainingArguments.

abiswas-realadvice pushed a commit to abiswas-realadvice/unsloth that referenced this pull request May 14, 2026
Disable gradient checkpointing when explicitly off for vision
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants