Skip to content

Fix dtype mismatch for non-quantized layers when autocast is disabled#478

Merged
danielhanchen merged 2 commits into
mainfrom
fix/fp16-base-layer-dtype
Feb 9, 2026
Merged

Fix dtype mismatch for non-quantized layers when autocast is disabled#478
danielhanchen merged 2 commits into
mainfrom
fix/fp16-base-layer-dtype

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

  • Fix dtype mismatch error in compiled LoRA forward pass for non-quantized base layers (e.g. SiGLIP vision encoder in Gemma3) when autocast is disabled.

Details

Models on the FORCE_FLOAT32 list (like Gemma3) have autocast disabled (fp16=False, bf16=False). When such models contain non-quantized nn.Linear layers with float32 weights (e.g. SiGLIP vision encoder), passing float16 activations to F.linear causes:

RuntimeError: expected mat1 and mat2 to have the same dtype, but got Float and Half

The compiled LoRA forward calls self.base_layer(x, *args, **kwargs) without any dtype guard. The fix adds a check before this call: when autocast is not enabled and the base layer has a weight tensor with a different dtype than the input, cast the input to match.

This only affects non-quantized layers. For 8-bit quantized layers, the base_layer call is already replaced by _call_8bit_base_layer(...) earlier in the compilation pipeline, so the source.replace() is naturally a no-op for those layers.

Companion PR: unslothai/unsloth#4005

Test plan

  • bf16 + 4-bit training with Llama-3.2-1B-Instruct -- no regression (loss 1.5377)
  • fp16 + 4-bit training with Llama-3.2-1B-Instruct -- passes (loss 1.5313)
  • Gemma3 4B vision model with SiGLIP encoder (requires both this PR and companion unsloth PR)

When autocast is disabled (e.g. models on the FORCE_FLOAT32 list like
Gemma3) and a non-quantized base layer has float32 weights (e.g. SiGLIP
vision encoder), passing float16 activations to F.linear causes a dtype
mismatch error.

Add a dtype guard before the base_layer call in the compiled LoRA
forward path: when autocast is not enabled, cast the input to match the
base layer weight dtype. This only affects non-quantized layers since
the 8-bit code path already replaces the base_layer call above this
point.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @danielhanchen, 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 dtype mismatch issue that occurs in specific model configurations (e.g., Gemma3 with SiGLIP) when autocast is disabled. The core of the fix involves adding a dtype check and input casting to ensure compatibility between input tensors and layer weights, preventing RuntimeError exceptions. This change specifically targets non-quantized layers, leaving the handling of quantized layers unaffected.

Highlights

  • Fixes dtype mismatch: Addresses a RuntimeError caused by dtype mismatch in non-quantized layers when autocast is disabled, specifically affecting models like Gemma3 with SiGLIP vision encoders.
  • Input Type Casting: Implements a check to cast input tensors to the correct dtype before passing them to the base layer when autocast is disabled and a dtype mismatch is detected.
  • Targeted Application: The fix is applied only to non-quantized layers, as 8-bit quantized layers are already handled by a different mechanism.

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

Changelog
  • unsloth_zoo/compiler.py
    • Added a conditional dtype check and input casting to handle dtype mismatches in non-quantized layers when autocast is disabled.
Activity
  • The PR includes a fix for a dtype mismatch error.
  • The fix involves checking and casting input tensors to match the weight dtype of the base layer when autocast is disabled.
  • The changes are limited to non-quantized layers.
  • Test plan includes bf16 and fp16 training with Llama-3.2-1B-Instruct, and testing with Gemma3 4B vision model.
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 aims to fix a dtype mismatch error for non-quantized layers when autocast is disabled. The logic of the fix is sound, but the implementation introduces an indentation error in the generated code string, which would cause a syntax error at runtime. I've provided a critical comment with a suggested fix to correct the indentation.

Comment thread unsloth_zoo/compiler.py Outdated
Comment on lines +2398 to +2405
source = source.replace(
"result = self.base_layer(x, *args, **kwargs)",
"if not torch.is_autocast_enabled() and hasattr(self.base_layer, 'weight') "
"and self.base_layer.weight is not None "
"and x.dtype != self.base_layer.weight.dtype:\n"
" x = x.to(self.base_layer.weight.dtype)\n"
" result = self.base_layer(x, *args, **kwargs)",
)

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.

critical

The indentation in the replacement string is incorrect and will cause an IndentationError when the generated code is executed. The result = ... line is indented less than the if block's body but is not aligned with the if statement itself.

To fix this, the result = self.base_layer(x, *args, **kwargs) line should be at the same indentation level as the if statement (i.e., unindented within the replacement string), and the body of the if statement should be indented relative to it (e.g., by 4 spaces).

Suggested change
source = source.replace(
"result = self.base_layer(x, *args, **kwargs)",
"if not torch.is_autocast_enabled() and hasattr(self.base_layer, 'weight') "
"and self.base_layer.weight is not None "
"and x.dtype != self.base_layer.weight.dtype:\n"
" x = x.to(self.base_layer.weight.dtype)\n"
" result = self.base_layer(x, *args, **kwargs)",
)
source = source.replace(
"result = self.base_layer(x, *args, **kwargs)",
"if not torch.is_autocast_enabled() and hasattr(self.base_layer, 'weight') "
"and self.base_layer.weight is not None "
"and x.dtype != self.base_layer.weight.dtype:\n"
" x = x.to(self.base_layer.weight.dtype)\n"
"result = self.base_layer(x, *args, **kwargs)",
)

The replacement string previously hardcoded space counts (12, 8) that
assumed the dedented source had `result = self.base_layer(...)` at
exactly 8-space indent. Use re.search to detect the actual indentation
so the fix adapts if peft changes its nesting depth.
@danielhanchen danielhanchen merged commit 608ddd0 into main Feb 9, 2026
3 checks passed
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.

1 participant