Skip to content

Fix batched padded generation - #4083

Closed
mmathew23 wants to merge 2 commits into
unslothai:mainfrom
mmathew23:fix/left-pad-batch-generate-fresh
Closed

mmathew23 wants to merge 2 commits into
unslothai:mainfrom
mmathew23:fix/left-pad-batch-generate-fresh

Conversation

@mmathew23

Copy link
Copy Markdown
Contributor

Fixes #3699

Using the script

import torch
from unsloth import FastLanguageModel

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="Qwen/Qwen2.5-0.5B",
    max_seq_length=2048,
    load_in_4bit=True,
)
FastLanguageModel.for_inference(model)

examples = [
    "Short prompt",
    "This is a longer prompt with more tokens",
]

# Single sequence generation works correctly
for ex in examples:
    enc = tokenizer.encode(ex, add_special_tokens=True)
    out = model.generate(torch.tensor([enc]).to(model.device), max_new_tokens=30)
    print(tokenizer.decode(out[0][len(enc):]))  # Correct output

# Batched generation with left-padding produces garbage for shorter sequences
tokenizer.padding_side = 'left'
tokenizer.pad_token = tokenizer.eos_token

batch = tokenizer(examples, padding=True, return_tensors='pt', add_special_tokens=True)
out_batch = model.generate(
    batch['input_ids'].to(model.device),
    attention_mask=batch['attention_mask'].to(model.device),
    max_new_tokens=30,
)
# Shorter sequence (index 0) produces garbage, longer sequence (index 1) is correct

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

@gemini-code-assist

Copy link
Copy Markdown
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 an issue where batched generation with left-padding in the unsloth library produced incorrect or "gibberish" output for shorter sequences within a batch. By refining how attention masks and position IDs are handled during batched decoding, particularly for padded inputs, the changes ensure that batched generation now yields correct and consistent results, matching single-sequence generation behavior.

Highlights

  • Batched Generation Mask Handling: Introduced attention_mask_2d to correctly handle per-row offsets in true batched generation, ensuring that the full 2D attention mask is retained during decoding to preserve padding and history context for batched sequences.
  • Position ID Calculation for Padded Batches: Implemented a new logic for calculating position_ids based on attention_mask_2d for padded batches, ensuring accurate positional encoding that accounts for varying sequence lengths within a batch.
  • Attention Backend Selection: Forced the use of the SDPA (Scaled Dot Product Attention) backend when a dense padding mask is detected in LlamaAttention_fast_forward, avoiding issues with other attention kernels that may not correctly handle such masks.
  • Optimized 4D Attention Mask Creation: Refined LlamaModel_fast_forward to only materialize a 4D attention mask when actual padding is present in the input, improving efficiency for fully unpadded inputs by avoiding unnecessary mask creation.

🧠 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/llama.py
    • Added attention_mask_2d to store a 2D attention mask copy for true batched generation.
    • Removed the attention_mask = attention_mask[:, [-1]] trimming logic to maintain full padding/history context during batched decoding.
    • Modified the position_ids calculation to derive per-row offsets from attention_mask_2d for padded batches, instead of relying solely on cache_position.
    • Introduced a condition in LlamaAttention_fast_forward to force the "sdpa" attention backend when a dense attention_mask is provided, ensuring compatibility with padded inputs.
    • Updated LlamaModel_fast_forward to only generate a 4D causal attention mask when padding (attention_mask == 0) is actually present in the input, otherwise setting attention_mask to None for unpadded inputs.
Activity
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. ↩

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread unsloth/models/llama.py
Comment on lines +999 to +1000
has_padding = bool(torch.any(attention_mask == 0))
if has_padding:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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

Comment thread unsloth/models/llama.py
Comment on lines +319 to +321
current_input_length = (
input_ids.shape[1] if input_ids is not None else 1
)

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

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.

Suggested change
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)
)

Comment thread unsloth/models/llama.py
past_key_values_length,
sliding_window = getattr(self.config, "sliding_window", None),
)
# Keep fast causal kernels for fully unpadded inputs. Only materialize

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

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.

Suggested change
# Keep fast causal kernels for fully unpadded inputs. Only materialize
has_padding = attention_mask.dim() == 2 and bool(torch.any(attention_mask == 0))

@Datta0

Datta0 commented Feb 20, 2026

Copy link
Copy Markdown
Contributor

Hey @mmathew23 I think something is wrong. batched generate was working for me on main and it is not working on this pr?

This is on main
image

This is on the PR
image

@mmathew23

Copy link
Copy Markdown
Contributor Author

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

@danielhanchen

danielhanchen commented Feb 23, 2026 •

Copy link
Copy Markdown
Member

Testing Results

Tested batched left-padded generation (3 prompts with varying padding ratios: 76-80%, 0%, 44-53%) on transformers==4.57.6, torch==2.9.1+cu130, B200 GPU.

Baseline (Unsloth 2026.2.1, no PR)

Individual generation works. Batched generation broken for padded sequences:

Model Prompt 0 (high pad) Prompt 1 (no pad) Prompt 2 (medium pad)
Llama-3.2-1B FAIL (loops) FAIL FAIL
Mistral-7B FAIL (truncated) PASS FAIL
Qwen2.5-0.5B PASS PASS FAIL

With PR #4083

Model Prompt 0 (high pad) Prompt 1 (no pad) Prompt 2 (medium pad)
Llama-3.2-1B PASS coherent near-match
Mistral-7B coherent (shorter) PASS near-match
gpt-oss-20B (MoE) coherent (minor diff) PASS PASS
Gemma3-4b-pt (Vision) PASS PASS PASS
Qwen3-VL-8B (Vision) PASS near-match near-match

"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.0

Unsloth 2026.2.1 is incompatible with transformers 5.x in general (all outputs are gibberish regardless of PR). Not a PR issue.

Notes

  • Vision models (Gemma3, Qwen3-VL) use their own prepare_inputs_for_generation in conditional generation classes, so the text-model fix in llama.py may not directly apply. They passed all tests regardless.
  • The LlamaAttention_fast_forward change to force SDPA when attention_mask is not None is the right approach -- the fast path does not thread masks through flash/xFormers kernels.
  • The conditional 4D mask materialization in LlamaModel_fast_forward (has_padding check) is a clean optimization that avoids unnecessary mask computation for unpadded inputs.

@danielhanchen

Copy link
Copy Markdown
Member

While testing this PR across additional architectures, I found a related but independent bug: self.temp_O is allocated as (1, bsz, hidden_size) but torch.matmul expects (bsz, 1, hidden_size) when bsz > 1. This causes a PyTorch UserWarning about deprecated resize behavior.

This bug pre-dates this PR and is in the Pattern A allocation path (when attention_size != hidden_size). Filed a separate fix in #4099.

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.

@danielhanchen

Copy link
Copy Markdown
Member

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 UserWarning: resized from torch.matmul.

All 20 models pass with zero resize warnings.

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

Baseline comparison: old (1, bsz, hidden_size) shape on gemma-2-2b-it produces 26 resize warnings with bsz=3. The fix eliminates all of them.

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.

@danielhanchen

Copy link
Copy Markdown
Member

Superseded by PR #4100 which is a comprehensive rework of the batched generation fix.

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.

[Bug] Batched generation with left-padding and caching produces incorrect output

3 participants