Skip to content

Fix self.temp_O buffer shape for batched inference - #4099

Closed
danielhanchen wants to merge 1 commit into
mainfrom
fix/temp-O-shape-batched-inference
Closed

danielhanchen wants to merge 1 commit into
mainfrom
fix/temp-O-shape-batched-inference

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Feb 24, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Fix self.temp_O allocation shape from (1, bsz, hidden_size) to (bsz, 1, hidden_size) in 6 model files
  • The wrong shape caused torch.matmul to silently resize the output tensor when bsz > 1, producing UserWarning: An output with one or more elements was resized
  • This will become a hard error in a future PyTorch release

Details

The Pattern A allocation path (triggered when attention_size != hidden_size, e.g. Mistral Nemo 12b) allocated self.temp_O as (1, bsz, hidden_size). However, fast_linear_forward calls torch.matmul(X, W.t(), out=self.temp_O) where X has shape (bsz, 1, in_features), so the output should be (bsz, 1, hidden_size).

The Pattern B alias path (self.temp_O = self.temp_QA[1][:, :, :hidden_size]) already produces the correct (bsz, 1, hidden_size) shape. When bsz == 1, both shapes are identical (1, 1, hidden_size), so this only manifests with batched inference.

Files changed

File Function
unsloth/models/llama.py LlamaAttention_fast_forward_inference
unsloth/models/gemma2.py Gemma2Attention_fast_forward_inference
unsloth/models/granite.py GraniteAttention_fast_forward_inference
unsloth/models/cohere.py CohereAttention_fast_forward_inference
unsloth/models/qwen3.py Qwen3Attention_fast_forward_inference
unsloth/models/falcon_h1.py FalconH1Attention_fast_forward_inference

Test plan

  • Batched left-padded generation tested on 20 models across 6 architectures -- all produce coherent output, zero resize warnings
  • Single-sequence (bsz=1) generation still works for all models
  • SFT training sanity check (5 steps on Llama-3.2-1B) passes with no regressions
  • Baseline confirmed: old (1, bsz, hidden_size) produces 26 resize warnings on gemma-2-2b-it (bsz=3)

Test results: 20 models, batched generation (bsz=3), zero resize warnings

# Model Architecture bsz=1 warnings bsz=3 warnings Status
1 HuggingFaceTB/SmolLM-135M-Instruct Llama 0 0 PASS
2 HuggingFaceTB/SmolLM-360M-Instruct Llama 0 0 PASS
3 HuggingFaceTB/SmolLM-1.7B-Instruct Llama 0 0 PASS
4 TinyLlama/TinyLlama-1.1B-Chat-v1.0 Llama 0 0 PASS
5 unsloth/Llama-3.2-1B-Instruct Llama 0 0 PASS
6 meta-llama/Llama-3.2-3B-Instruct Llama 0 0 PASS
7 Qwen/Qwen2-0.5B-Instruct Qwen2 0 0 PASS
8 Qwen/Qwen2.5-0.5B-Instruct Qwen2 0 0 PASS
9 Qwen/Qwen2.5-Coder-0.5B-Instruct Qwen2 0 0 PASS
10 Qwen/Qwen2.5-1.5B-Instruct Qwen2 0 0 PASS
11 Qwen/Qwen2.5-Math-1.5B-Instruct Qwen2 0 0 PASS
12 deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B Qwen2 0 0 PASS
13 unsloth/mistral-7b-instruct-v0.3-bnb-4bit Mistral 0 0 PASS
14 google/gemma-2b-it Gemma 0 0 PASS
15 google/gemma-1.1-2b-it Gemma 0 0 PASS
16 google/gemma-2-2b-it Gemma2 0 0 PASS
17 Qwen/Qwen3-0.6B Qwen3 0 0 PASS
18 Qwen/Qwen3-1.7B Qwen3 0 0 PASS
19 Qwen/Qwen2.5-Coder-1.5B-Instruct Qwen2 0 0 PASS
20 Qwen/Qwen2.5-Math-1.5B Qwen2 0 0 PASS

Note: This fix is independent of #4083 (batched left-padded generation). The shape bug pre-dates that PR and affects any batched inference path.

The temp_O output buffer was allocated as (1, bsz, hidden_size) but
torch.matmul expects (bsz, 1, hidden_size) when bsz > 1. With the
wrong shape, PyTorch silently resizes the output tensor, producing a
UserWarning about deprecated resize behavior that will become an error
in a future release.

This only affects the Pattern A allocation path (when attention_size !=
hidden_size, e.g. Mistral Nemo 12b). The Pattern B alias path already
gets the correct shape from temp_QA[1]. When bsz == 1, the shapes are
identical so there is no behavioral change for single-sequence
inference.

Files changed:
- unsloth/models/llama.py
- unsloth/models/gemma2.py
- unsloth/models/granite.py
- unsloth/models/cohere.py
- unsloth/models/qwen3.py
- unsloth/models/falcon_h1.py
@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 addresses a critical tensor shape mismatch that previously caused torch.matmul to issue resizing warnings during batched inference in several language models. By correcting the allocation of the self.temp_O buffer, the change prevents potential hard errors in future PyTorch versions and ensures the stability and correctness of batched operations, which is crucial for efficient model deployment and training.

Highlights

  • Corrected Tensor Shape for Batched Inference: The allocation shape for self.temp_O was fixed from (1, bsz, hidden_size) to (bsz, 1, hidden_size) across six model files to ensure correct behavior during batched inference.
  • Prevented Future PyTorch Errors: This change resolves a UserWarning issued by torch.matmul when bsz > 1 due to silent tensor resizing, which is slated to become a hard error in upcoming PyTorch releases.
  • Ensured Batched Generation Stability: Extensive testing confirmed that batched left-padded generation now produces coherent output without resize warnings across multiple architectures, while single-sequence generation and SFT training remain unaffected.

🧠 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/models/cohere.py
    • Updated the allocation shape for self.temp_O from (1, bsz, hidden_size) to (bsz, 1, hidden_size) within CohereAttention_fast_forward_inference.
  • unsloth/models/falcon_h1.py
    • Updated the allocation shape for self.temp_O from (1, bsz, hidden_size) to (bsz, 1, hidden_size) within FalconH1Attention_fast_forward_inference.
  • unsloth/models/gemma2.py
    • Updated the allocation shape for self.temp_O from (1, bsz, hidden_size) to (bsz, 1, hidden_size) within Gemma2Attention_fast_forward_inference.
  • unsloth/models/granite.py
    • Updated the allocation shape for self.temp_O from (1, bsz, hidden_size) to (bsz, 1, hidden_size) within GraniteAttention_fast_forward_inference.
  • unsloth/models/llama.py
    • Updated the allocation shape for self.temp_O from (1, bsz, hidden_size) to (bsz, 1, hidden_size) within LlamaAttention_fast_forward_inference.
  • unsloth/models/qwen3.py
    • Updated the allocation shape for self.temp_O from (1, bsz, hidden_size) to (bsz, 1, hidden_size) within Qwen3Attention_fast_forward_inference.
Activity
  • No specific review comments or discussions have been recorded for this pull request yet.
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 is an excellent pull request that fixes a subtle but important bug in the shape of the self.temp_O buffer for batched inference. The fix is correct, applied consistently across all relevant files, and will prevent a UserWarning from becoming a hard error in a future PyTorch release. The detailed explanation and thorough test plan are much appreciated. I have one minor suggestion regarding a potentially misleading comment.

Comment thread unsloth/models/granite.py
self.RH_Q = torch.empty((bsz, n_heads, 1, head_dim), dtype = dtype, device = device)
# Only for Gemma2
self.temp_O = torch.empty((1, bsz, hidden_size), dtype = dtype, device = device)
self.temp_O = torch.empty((bsz, 1, hidden_size), dtype = dtype, device = device)

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 the shape correction is correct, the comment on the preceding line, # Only for Gemma2, appears to be a copy-paste from gemma2.py and is misleading in this context. To improve clarity, I suggest removing this comment as this allocation is not specific to Gemma2.

@Datta0

Datta0 commented Feb 24, 2026

Copy link
Copy Markdown
Contributor

The same changes exist in #4100
Might want to cleanup this or that to avoid merge conflicts

@danielhanchen

Copy link
Copy Markdown
Member Author

Superseded by PR #4100 which includes the temp_O shape fix and all other batched generation fixes.

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.

2 participants