Repository navigation
Conversation
Summary of ChangesHello @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 an issue where batched generation with left-padding in the Highlights
🧠 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
Activity
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2670026045
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| has_padding = bool(torch.any(attention_mask == 0)) | ||
| if has_padding: |
There was a problem hiding this comment.
Preserve sliding-window masking for unpadded inference
The new has_padding gate only materializes a 4D mask when the 2D mask contains zeros, so unpadded batches now set attention_mask = None even when self.config.sliding_window is enabled. In that case SDPA falls back to plain causal attention with no local-window constraint (unsloth/utils/attention_dispatch.py uses is_causal_local = local_mask is None and q_len_local == k_len_local), which changes model behavior for sliding-window architectures and can increase attention scope unexpectedly. Keep building a mask whenever sliding-window attention is configured, not only when padding exists.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Code Review
This pull request addresses a critical issue in batched generation with left-padding, where shorter sequences would produce incorrect (gibberish) output. The fix involves correctly computing per-row position_ids based on the attention mask, which is necessary because the default cache_position is shared across the batch and cannot account for differing padding offsets. Additionally, the PR optimizes the attention path by only materializing 4D masks when padding is actually present, allowing for faster causal kernels in unpadded scenarios, and forces the SDPA backend when dense padding masks are provided to ensure correctness.
| current_input_length = ( | ||
| input_ids.shape[1] if input_ids is not None else 1 | ||
| ) |
There was a problem hiding this comment.
When input_ids is None (e.g., when using inputs_embeds), current_input_length defaults to 1. While this is correct for standard token-by-token decoding, it might be incorrect if inputs_embeds contains multiple tokens during a decode step (e.g., in speculative decoding or prompt extension scenarios). It would be safer to check inputs_embeds.shape[1] if input_ids is missing.
| current_input_length = ( | |
| input_ids.shape[1] if input_ids is not None else 1 | |
| ) | |
| if past_key_values is not None: | |
| current_input_length = ( | |
| input_ids.shape[1] if input_ids is not None else | |
| (inputs_embeds.shape[1] if inputs_embeds is not None else 1) | |
| ) |
| past_key_values_length, | ||
| sliding_window = getattr(self.config, "sliding_window", None), | ||
| ) | ||
| # Keep fast causal kernels for fully unpadded inputs. Only materialize |
There was a problem hiding this comment.
The has_padding check using attention_mask == 0 assumes that the input attention_mask is a 2D padding mask (where 0 is padding). However, if attention_mask is already a 4D SDPA mask (where 0 means 'don't mask' and -inf means 'mask'), this check will return True if there are any valid tokens, potentially leading to redundant re-materialization of the mask. Adding a dimension check would make this optimization more robust.
| # Keep fast causal kernels for fully unpadded inputs. Only materialize | |
| has_padding = attention_mask.dim() == 2 and bool(torch.any(attention_mask == 0)) |
|
Hey @mmathew23 I think something is wrong. batched generate was working for me on main and it is not working on this pr? |
|
Will take a look but batched generation is not fully correct on main. If you try with the example from the issue pr, batched generate doesn't match single generate on the shorter prompt. The longer prompt is fine |
Testing ResultsTested batched left-padded generation (3 prompts with varying padding ratios: 76-80%, 0%, 44-53%) on Baseline (Unsloth 2026.2.1, no PR)Individual generation works. Batched generation broken for padded sequences:
With PR #4083
"near-match" means outputs are coherent and topically identical but have minor wording differences, which is expected when switching between attention backends (SDPA for batched vs flash for individual). transformers 5.2.0Unsloth 2026.2.1 is incompatible with transformers 5.x in general (all outputs are gibberish regardless of PR). Not a PR issue. Notes
|
|
While testing this PR across additional architectures, I found a related but independent bug: This bug pre-dates this PR and is in the Pattern A allocation path (when Extended test results with this PR + the temp_O fix across 6 architectures (Llama, Qwen2, Qwen3, Gemma, Gemma2, Mistral): all produce coherent batched output with zero resize warnings. |
|
Extended testing with the temp_O shape fix (PR #4099) on top of this PR across 20 models covering all active architectures. Test: batched left-padded generation (bsz=3) checking for All 20 models pass with zero resize warnings.
Baseline comparison: old Architecture coverage: Llama (6), Qwen2 (8), Mistral (1), Gemma (2), Gemma2 (1), Qwen3 (2). Cohere, Granite, and FalconH1 have the same fix applied but are currently commented out in the loader dispatcher. |
|
Superseded by PR #4100 which is a comprehensive rework of the batched generation fix. |


Fixes #3699
Using the script
posted by @afspies
we no longer get gibberish characters and the batched output matches the single generation.
Notebook: https://colab.research.google.com/drive/1TlcaWlzsc1uuoCxwuNycR_BbMRlcgch6?usp=sharing