Skip to content

Fix/pr 3699 leftpad prefill main - #4100

Merged
danielhanchen merged 15 commits into
unslothai:mainfrom
mmathew23:fix/pr-3699-leftpad-prefill-main
Feb 25, 2026
Merged

danielhanchen merged 15 commits into
unslothai:mainfrom
mmathew23:fix/pr-3699-leftpad-prefill-main

Conversation

@mmathew23

@mmathew23 mmathew23 commented Feb 24, 2026 •

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/1livuOKZoEUu04IEUP_gftcf_A_dz_zzF?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 left-padded batched generation produced incorrect or 'garbage' output, particularly for shorter sequences. The changes primarily focus on improving the handling of attention masks and tensor shapes within various attention mechanisms (Llama, Qwen3, Cohere, FalconH1, Gemma2, Granite) to ensure proper processing during batched inference. Key updates include robust normalization of attention masks for SDPA, precise calculation and application of position_ids, and a fix for a tensor shape mismatch, collectively leading to stable and correct batched generation results.

Highlights

  • Tensor Shape Correction: Corrected the shape of the self.temp_O tensor from (1, bsz, hidden_size) to (bsz, 1, hidden_size) across multiple attention modules (Cohere, FalconH1, Gemma2, Granite, Llama, Qwen3) to ensure proper tensor dimensions.
  • Enhanced Input Preparation for Generation: Improved the _fast_prepare_inputs_for_generation function in Llama models to accurately manage attention_mask, cache_position, and position_ids, which is crucial for correct left-padded batched inference.
  • Robust SDPA Attention Mask Normalization: Implemented comprehensive logic in attention_dispatch.py and within Llama/Qwen3 attention modules to normalize various attention_mask formats (2D, 3D, 4D) into boolean keep masks compatible with Scaled Dot Product Attention (SDPA), addressing issues with left-padding and preventing NaNs.
  • Rotary Embedding and Sliding Window Refinements: Refined the application of rotary embeddings in Llama attention to ensure position_ids are correctly shaped and cos/sin tensors are on the appropriate device and dtype. Also adjusted sliding window logic to correctly slice KV caches and attention masks.
  • Conditional SDPA GQA Disabling: Introduced logic to conditionally disable SDPA Grouped Query Attention (GQA) for batched masked inference to mitigate 'row-coupled drift' and ensure more stable and deterministic outputs.

🧠 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
    • Corrected the shape of self.temp_O tensor from (1, bsz, hidden_size) to (bsz, 1, hidden_size).
  • unsloth/models/falcon_h1.py
    • Corrected the shape of self.temp_O tensor from (1, bsz, hidden_size) to (bsz, 1, hidden_size).
  • unsloth/models/gemma2.py
    • Corrected the shape of self.temp_O tensor from (1, bsz, hidden_size) to (bsz, 1, hidden_size).
  • unsloth/models/granite.py
    • Corrected the shape of self.temp_O tensor from (1, bsz, hidden_size) to (bsz, 1, hidden_size).
  • unsloth/models/llama.py
    • Imported SDPA for attention backend selection.
    • Refactored _fast_prepare_inputs_for_generation to correctly determine batch size, sequence length, and device, and to manage cache_position and position_ids for generation.
    • Updated _fast_prepare_inputs_for_generation to dynamically calculate target_length for attention mask preparation and pass mask_kwargs correctly.
    • Modified LlamaAttention_fast_forward_inference to ensure position_ids have the correct shape and device, and to properly extend rotary embeddings.
    • Adjusted sliding window logic in LlamaAttention_fast_forward_inference to correctly slice KV caches and attention masks.
    • Added attention mask normalization for SDPA in LlamaAttention_fast_forward_inference, converting 2D masks to 4D boolean masks.
    • Ensured cos and sin tensors are moved to the correct device and dtype in LlamaAttention_fast_forward.
    • Conditionally selected SDPA as the attention backend if an attention_mask is provided in LlamaAttention_fast_forward.
    • Changed the condition for preparing 4D causal attention mask in LlamaModel_fast_forward_inference_custom to attention_mask is not None.
    • Corrected the shape of self.temp_O tensor from (1, bsz, hidden_size) to (bsz, 1, hidden_size).
  • unsloth/models/qwen3.py
    • Imported SDPA for attention backend selection.
    • Conditionally selected SDPA as the attention backend if an attention_mask is provided in Qwen3Attention_fast_forward.
    • Corrected the shape of self.temp_O tensor from (1, bsz, hidden_size) to (bsz, 1, hidden_size).
    • Implemented attention mask normalization for SDPA in Qwen3Attention_fast_forward_inference, including conversion to boolean masks and conditional disabling of SDPA GQA for batched masked decode.
  • unsloth/utils/attention_dispatch.py
    • Imported torch.
    • Added comprehensive SDPA mask normalization logic within run_attention to handle 2D, 3D, and 4D attention masks, converting them to boolean keep masks, applying causal and sliding window constraints, and preventing NaNs.
    • Introduced logic to conditionally disable SDPA GQA for batched masked inference to prevent 'row-coupled drift'.
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. ↩

@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

The pull request addresses an issue with left-padding in batched generation by adjusting tensor dimensions and attention mask handling across several model files. The changes primarily involve modifying the shape of self.temp_O from (1, bsz, hidden_size) to (bsz, 1, hidden_size) and refining how attention_mask and position_ids are processed, especially for SDPA and sliding window mechanisms. The changes appear to correctly resolve the reported gibberish characters issue during batched generation with left-padding.

I am having trouble creating individual review comments. Click here to see my feedback.

unsloth/utils/attention_dispatch.py (289-299)

critical

This conditional logic to disable use_sdpa_gqa for batched masked inference when local_mask.dim() >= 3 and local_mask.shape[0] > 1 is a critical fix. It explicitly addresses the row-coupled drift issue observed with SDPA GQA in such scenarios, ensuring deterministic and correct behavior by falling back to explicit KV expansion.

unsloth/utils/attention_dispatch.py (238-281)

critical

This extensive block of code for SDPA mask normalization is a critical improvement. It correctly handles 2D, 3D, and 4D attention masks, converts them to boolean keep masks for stability, and addresses potential NaNs from fully-masked rows. This directly resolves the gibberish characters issue by ensuring the attention mask is correctly formatted and applied for SDPA.

unsloth/models/qwen3.py (355-363)

critical

The logic to conditionally disable use_sdpa_gqa for batched masked inference when attention_mask.dim() >= 3 and attention_mask.shape[0] > 1 is a critical fix. This addresses the row-coupled drift observed with SDPA GQA in such scenarios, ensuring deterministic and correct behavior by falling back to explicit KV expansion.

unsloth/models/llama.py (347-357)

high

The updated logic for position_ids generation, especially when original_attention_mask is present and for handling cache_position dimensions, is crucial for correctly managing positional embeddings in batched and left-padded scenarios. This directly contributes to solving the gibberish characters issue.

unsloth/models/qwen3.py (343-350)

high

This block of code correctly handles the attention_mask for SDPA when a 2D padding mask or a 4D non-boolean mask is provided. Converting to a boolean keep mask for stability is a good practice and directly addresses potential issues with gibberish characters by ensuring the mask is interpreted correctly by SDPA.

unsloth/models/llama.py (578-587)

high

This block of code correctly handles the attention_mask for SDPA when a 2D padding mask or a 4D non-boolean mask is provided. Converting to a boolean keep mask for stability is a good practice and directly addresses potential issues with gibberish characters by ensuring the mask is interpreted correctly by SDPA.

unsloth/models/llama.py (493-502)

high

The explicit reshaping of position_ids to [:, None] and ensuring it's on the correct device, along with the dynamic calculation of rotary_seq_len and casting cos and sin to the correct device and dtype, are critical for robust rotary embedding application, especially with variable batch sizes and sequence lengths. This is a significant improvement for correctness.

unsloth/models/llama.py (259-284)

high

The added logic to handle past_len, max_cache_len, and cache_position is critical for accurate KV cache management, especially with varying sequence lengths and attention masks. This directly addresses the problem of gibberish characters by ensuring correct positional embeddings.

unsloth/models/llama.py (455)

medium

The change in self.temp_O dimensions here is consistent with other model files and addresses the issue of incorrect tensor shapes for batched operations.

unsloth/models/llama.py (763)

medium

Conditionally setting the backend to SDPA when attention_mask is not None ensures that the appropriate attention mechanism is used, which is important for performance and correctness, especially with masked inputs.

unsloth/models/llama.py (326)

medium

Changing kwargs["device"] to mask_kwargs["device"] is a necessary correction to ensure the device parameter is passed to the correct set of arguments for _prepare_4d_causal_attention_mask_with_cache_position.

unsloth/models/llama.py (335)

medium

Using **mask_kwargs instead of **kwargs ensures that the correct set of parameters, specifically tailored for mask generation, is passed to the function. This is a logical and correct refactoring.

unsloth/models/llama.py (338)

medium

Removing the line if attention_mask is not None: attention_mask = attention_mask[:, [-1]] is important because the new logic for _prepare_4d_causal_attention_mask_with_cache_position handles the attention mask more comprehensively, making this specific slicing redundant and potentially incorrect.

unsloth/models/llama.py (303-311)

medium

The introduction of target_length calculation based on max_cache_len, original_attention_mask, or past_len + seq_length provides a more flexible and accurate way to determine the target length for attention mask preparation. This is a good improvement for handling diverse input scenarios.

unsloth/models/cohere.py (299)

medium

The change from (1, bsz, hidden_size) to (bsz, 1, hidden_size) for self.temp_O is consistent across multiple model files and seems to correctly align the tensor dimensions for batched operations, which is crucial for the fix.

unsloth/models/llama.py (248-251)

medium

The change from cache_length to _seq_length and then re-assigning seq_length based on input_ids.shape[1] is a bit confusing. It seems _seq_length is unused after its initial assignment. Consider directly using input_ids.shape[1] for seq_length if _seq_length serves no other purpose.

unsloth/models/llama.py (534-538)

medium

The introduction of start = kv_seq_len - sliding_window and the conditional slicing of attention_mask are crucial for correctly implementing sliding window attention. This ensures that the attention mechanism only considers relevant tokens within the window, which is important for performance and correctness in long-context scenarios.

unsloth/models/llama.py (216-230)

medium

Storing the original_attention_mask and dynamically determining bs, seq_length, and device based on input_ids or inputs_embeds is a robust improvement. This ensures that the generation process correctly handles various input scenarios and device placements.

unsloth/models/llama.py (742-743)

medium

Explicitly moving cos and sin to the correct device and dtype is a good practice to prevent potential device or type mismatches, especially in multi-GPU or mixed-precision environments.

unsloth/models/llama.py (313-320)

medium

Creating mask_kwargs with sequence_length, target_length, dtype, cache_position, batch_size, config, and past_key_values centralizes the parameters needed for attention mask generation, improving readability and maintainability.

unsloth/models/llama.py (1340)

medium

Changing the condition from bsz != 1 to attention_mask is not None is a more accurate and robust way to determine when to prepare the 4D causal attention mask. This ensures that the mask is processed only when it's actually provided, regardless of batch size.

unsloth/models/qwen3.py (24)

medium

Importing SDPA directly into qwen3.py is a good step towards explicitly managing attention backends, especially when attention_mask is present, as seen in later changes.

unsloth/models/qwen3.py (143)

medium

Conditionally setting the backend to SDPA when attention_mask is not None ensures that the appropriate attention mechanism is used, which is important for performance and correctness, especially with masked inputs.

unsloth/models/qwen3.py (253)

medium

The change in self.temp_O dimensions here is consistent with other model files and addresses the issue of incorrect tensor shapes for batched operations.

unsloth/models/llama.py (38)

medium

Importing SDPA directly into llama.py is a good step towards explicitly managing attention backends, especially when attention_mask is present, as seen in later changes.

unsloth/models/granite.py (327)

medium

This change in granite.py is consistent with the other model files, fixing the self.temp_O tensor shape for proper batched operations.

unsloth/models/qwen3.py (367)

medium

Changing the condition to (not use_sdpa_gqa) and n_groups != 1 correctly integrates the new use_sdpa_gqa flag, ensuring that grouped query attention is handled appropriately based on the determined SDPA GQA usage.

unsloth/models/qwen3.py (393)

medium

Using use_sdpa_gqa instead of SDPA_HAS_GQA directly ensures that the conditional logic for enabling GQA in scaled_dot_product_attention respects the dynamic decision made earlier to avoid drift in batched masked inference.

unsloth/models/gemma2.py (355)

medium

The adjustment of self.temp_O dimensions in gemma2.py follows the pattern seen in other models, ensuring correct tensor shapes for batched inference.

unsloth/models/falcon_h1.py (268)

medium

Similar to cohere.py, this change in falcon_h1.py corrects the shape of self.temp_O for consistency in batched processing. This is a good fix for potential dimension mismatches.

@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: 198fd942f4

ℹ️ 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 Outdated
Comment on lines +266 to +267
if hasattr(past_key_values, "get_max_cache_shape"):
m = int(past_key_values.get_max_cache_shape())

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 Guard get_max_cache_shape before int conversion

In _fast_prepare_inputs_for_generation, get_max_cache_shape() is cast with int(...) unconditionally, but the Transformers cache API returns an optional value and DynamicCache commonly reports no fixed maximum (None). In that case, int(None) raises TypeError during cached generation (typically from the second decoding step onward), causing generation to fail for DynamicCache-based paths. Please add a None check before converting, like the existing get_max_length() branch does.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/llama.py Outdated
else:
if input_ids is not None and input_ids.numel() > 0:
bs, cache_length = input_ids.shape
bs, _seq_length = input_ids.shape

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.

Is this a typo? seq_length perhaps?

Comment thread unsloth/models/llama.py Outdated
bs, _seq_length = input_ids.shape
input_ids = input_ids[:, [-1]]
device = input_ids.device
seq_length = input_ids.shape[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.

Maybe we should fix L248 and remove this?

Comment thread unsloth/models/llama.py
else:
if attention_mask is not None and attention_mask.dim() == 2:
attention_mask = attention_mask[:, None, None, :].to(torch.bool)
# is it more appropriate to use _prepare_4d_causal_attention_mask_for_sdpa?

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.

Comment thread unsloth/models/llama.py
rotary_emb = self.rotary_emb
rotary_emb.extend_rope_embedding(V, seq_len = kv_seq_len)
cos, sin = rotary_emb.get_cached(kv_seq_len, Q.device.index)
cos = cos.to(device = Q.device, dtype = Q.dtype)

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.

NIT: we should move these to get_cached function itself then?

Comment thread unsloth/models/llama.py
bs, seq_length = 1, 0
device = "cuda" if torch.cuda.is_available() else "cpu"

if hasattr(past_key_values, "get_seq_length"):

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.

perhaps lets move all this to a separate function ?

Comment thread unsloth/models/qwen3.py
# Attention module
use_varlen = seq_info is not None and past_key_value is None
backend = select_attention_backend(use_varlen)
backend = (

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.

I see the same select_attention_backend(use_varlen) call happening in other model files like mistral, gemma2 etc. There's also cohere and granite but rn they go through autocompile path iirc.

… generation

1. attention_dispatch.py: Fall back from flash/xformers to SDPA when an
   attention_mask is present, since flash attention only supports causal
   masking via flag and cannot consume arbitrary padding masks.

2. gemma2.py: Apply attention_mask during decode inference for bsz > 1.
   Guard against boolean SWA/GA flags with isinstance check. Slice mask
   to match K/V length when sliding window is active. Remove dead
   commented-out SDPA branch (SDPA does not support softcapping).

3. granite.py: Apply attention_mask during decode inference for bsz > 1.
   Remove dead commented-out SDPA branch and misleading comment.

4. mistral.py: Fix 2D-to-4D padding mask conversion -- convert 0/1 mask
   to additive format (0 for keep, -inf for mask) before combining with
   the causal mask. Force SDPA backend when attention_mask is present.

5. llama.py: Skip zeroing embed_tokens.weight[padding_idx] when the
   embedding is weight-tied to lm_head, since zeroing the shared weight
   forces logit(pad) = 0 which is higher than real token logits in models
   like Gemma, causing the decoder to emit pad tokens as gibberish. Also
   add eos != pad guard, clean up unused _seq_length variable, and fix
   get_max_cache_shape handling.

6. vision.py: Same padding_idx fix as llama.py for the vision model
   loading path.

Tested on gemma-2b-it, gemma-2-2b-it, Llama-3.2-1B, Mistral-7B-v0.3,
Qwen2.5-0.5B, Qwen3-0.6B with flash-attn 2.8.3 active. All outputs
coherent, zero crashes, zero resize warnings.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed a follow-up commit (26f23be) with additional fixes found during testing:

1. Centralized flash-to-SDPA fallback (attention_dispatch.py)
Flash attention and xFormers do not support arbitrary padding masks -- they only handle causal masking via a boolean flag. When attention_mask is present (batched left-padded generation), run_attention now falls back to SDPA, which consumes attn_mask properly.

2. Gemma2 decode inference mask (gemma2.py)
The attention mask was commented out in Gemma2Attention_fast_forward_inference. Uncommented and activated it for bsz > 1 decode steps. Added isinstance(attention_mask, torch.Tensor) guard because Gemma2Model_fast_forward_inference passes boolean True/False as attention_mask for SWA/GA layer selection when flash softcapping is available. Also added mask slicing to handle sliding window K/V truncation. Removed the dead SDPA branch since SDPA does not support softcapping.

3. Granite decode inference mask (granite.py)
Same pattern as Gemma2 -- attention mask was commented out. Activated it. Removed dead SDPA branch and a misleading # Only for Gemma2 comment on temp_O.

4. Mistral 2D-to-4D mask conversion (mistral.py)
The previous code added a raw 0/1 padding mask directly to the causal mask, which inverted the semantics (pad tokens got 0 = "allowed", real tokens got 1). Fixed by converting to additive format first: torch.where(mask.bool(), 0.0, -inf). Also force SDPA backend when attention_mask is present and imported the SDPA constant.

5. padding_idx zeroing for tied embeddings (llama.py)
Unsloth zeros embed_tokens.weight[padding_idx] during model loading. For models where embed_tokens is weight-tied with lm_head (Gemma, Gemma2, Llama), this also zeros the lm_head row, forcing logit(pad) = 0. Since real token logits are negative (-7 to -13 range), the model predicts <pad> as the top token and generates gibberish. Fix: skip zeroing when module.weight.data_ptr() == lm_head_weight.data_ptr(). Also added eos != pad guard, cleaned up unused _seq_length, and fixed get_max_cache_shape handling.

6. Same padding_idx fix for vision path (vision.py)
Mirrors the llama.py fix for the vision model loading path.

Test results (flash-attn 2.8.3, B200 GPU)

Model P0 (high pad) P1 (no pad) P2 (mid pad) Pad in output
google/gemma-2b-it MATCH MATCH MISMATCH no
unsloth/mistral-7b-instruct-v0.3-bnb-4bit MATCH MATCH MATCH no
google/gemma-2-2b-it MISMATCH MATCH MISMATCH no
unsloth/Llama-3.2-1B-Instruct MATCH MISMATCH MATCH no

All outputs coherent, zero crashes, zero resize warnings. Remaining mismatches are expected floating-point divergence between flash (individual) and SDPA (batched) backends.

@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@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

The pull request addresses an issue where batched generation with left-padding produced incorrect output for shorter sequences. The changes primarily involve adjusting tensor dimensions for self.temp_O across several model files (cohere, falcon_h1, gemma2, granite, llama, qwen3) from (1, bsz, hidden_size) to (bsz, 1, hidden_size). Additionally, the _fast_prepare_inputs_for_generation function in llama.py has been significantly refactored to handle attention_mask and position_ids more robustly, especially for batched inference and dynamic caching. The from_pretrained method in llama.py and vision.py now includes logic to prevent zeroing out padding token embeddings when they are tied to the lm_head and eos_token == pad_token, which previously led to 'gibberish' output. The attention_dispatch.py file has been updated to fall back to SDPA when a padding mask is present, as FlashAttention and xFormers do not fully support arbitrary attention masks. Overall, these changes improve the correctness and stability of batched inference, particularly with left-padding and dynamic KV caching.

Comment thread unsloth/models/mistral.py
Comment on lines 222 to +233
if attention_mask.dim() == 2:
# [bsz, seq_len] -> [bsz, 1, 1, seq_len]
attention_mask = attention_mask[:, None, None, :]
attention_mask = attention_mask.expand(bsz, 1, q_len, q_len)
attention_mask = attention_mask + causal_mask_values[None, None, :, :]
# Convert 0/1 padding mask to additive format: 1->0 (keep), 0->-inf (mask)
padding_mask = torch.where(
attention_mask[:, None, None, :].bool(),
0.0,
-torch.inf,
)
attention_mask = causal_mask_values[None, None, :, :] + padding_mask
else:
attention_mask = (
attention_mask + causal_mask_values[None, None, :, :]
)

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

This updated logic for handling attention_mask is crucial for Mistral models. It correctly converts 2D padding masks to an additive format (0.0 for keep, -torch.inf for mask) and combines them with the causal mask. This ensures that both padding and causality are correctly applied, preventing issues like 'gibberish' output in batched inference.

Suggested change
if attention_mask.dim() == 2:
# [bsz, seq_len] -> [bsz, 1, 1, seq_len]
attention_mask = attention_mask[:, None, None, :]
attention_mask = attention_mask.expand(bsz, 1, q_len, q_len)
attention_mask = attention_mask + causal_mask_values[None, None, :, :]
# Convert 0/1 padding mask to additive format: 1->0 (keep), 0->-inf (mask)
padding_mask = torch.where(
attention_mask[:, None, None, :].bool(),
0.0,
-torch.inf,
)
attention_mask = causal_mask_values[None, None, :, :] + padding_mask
else:
attention_mask = (
attention_mask + causal_mask_values[None, None, :, :]
)
if attention_mask.dim() == 2:
# Convert 0/1 padding mask to additive format: 1->0 (keep), 0->-inf (mask)
padding_mask = torch.where(
attention_mask[:, None, None, :].bool(),
0.0,
-torch.inf,
)
attention_mask = causal_mask_values[None, None, :, :] + padding_mask
else:
attention_mask = (
attention_mask + causal_mask_values[None, None, :, :]
)

Comment on lines +251 to +302
# ---- SDPA mask normalization for left padding / 2D masks ----
if local_mask is not None and isinstance(local_mask, torch.Tensor):
local_mask = local_mask.to(device = Q.device)

if local_mask.dim() == 2:
# key padding keep mask: (bsz, k_len), 1/True = real token
if local_mask.dtype == torch.bool:
key_keep = local_mask
else:
# tokenizer attention_mask is typically int 0/1
key_keep = local_mask != 0

past_len = (
k_len_local - q_len_local
) # works for prefill (0) and decode
q_pos = torch.arange(
past_len, past_len + q_len_local, device = Q.device
)
k_pos = torch.arange(k_len_local, device = Q.device)

causal_keep = (
k_pos[None, :] <= q_pos[:, None]
) # True = allowed (SDPA)
if sliding_window is not None:
causal_keep &= k_pos[None, :] >= (
q_pos[:, None] - (sliding_window - 1)
)

# (bsz, 1, q_len, k_len) boolean keep mask
local_mask = (
causal_keep[None, None, :, :] & key_keep[:, None, None, :]
)

elif local_mask.dim() == 3:
# (bsz, q_len, k_len) -> (bsz, 1, q_len, k_len)
local_mask = local_mask[:, None, :, :]

elif local_mask.dim() == 4:
if local_mask.dtype != torch.bool:
# Use boolean keep masks for better SDPA stability.
local_mask = local_mask.eq(0)
else:
raise ValueError(
f"Unsupported SDPA attention_mask rank: {local_mask.dim()}"
)

# Avoid NaNs from fully-masked rows (common with left padding).
if local_mask.dtype == torch.bool:
no_allowed = ~local_mask.any(
dim = -1, keepdim = True
) # (bsz,1,q_len,1)
local_mask = local_mask | no_allowed

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

This extensive block for SDPA mask normalization is a critical improvement. It correctly handles various dimensions of local_mask (2D, 3D, 4D), converting them into the appropriate boolean keep mask format for SDPA. The logic for deriving causal_keep and key_keep from 2D masks, and especially the handling of no_allowed rows to prevent NaNs from fully-masked rows, directly addresses the 'gibberish' output problem in left-padded batched generation. This is a high-impact change for correctness.

            if local_mask is not None and isinstance(local_mask, torch.Tensor):
                local_mask = local_mask.to(device = Q.device)

                if local_mask.dim() == 2:
                    # key padding keep mask: (bsz, k_len), 1/True = real token
                    if local_mask.dtype == torch.bool:
                        key_keep = local_mask
                    else:
                        # tokenizer attention_mask is typically int 0/1
                        key_keep = local_mask != 0

                    past_len = (
                        k_len_local - q_len_local
                    )  # works for prefill (0) and decode
                    q_pos = torch.arange(
                        past_len, past_len + q_len_local, device = Q.device
                    )
                    k_pos = torch.arange(k_len_local, device = Q.device)

                    causal_keep = (
                        k_pos[None, :] <= q_pos[:, None]
                    )  # True = allowed (SDPA)
                    if sliding_window is not None:
                        causal_keep &= k_pos[None, :] >= (
                            q_pos[:, None] - (sliding_window - 1)
                        )

                    # (bsz, 1, q_len, k_len) boolean keep mask
                    local_mask = (
                        causal_keep[None, None, :, :] & key_keep[:, None, None, :]
                    )

                elif local_mask.dim() == 3:
                    # (bsz, q_len, k_len) -> (bsz, 1, q_len, k_len)
                    local_mask = local_mask[:, None, :, :]

                elif local_mask.dim() == 4:
                    if local_mask.dtype != torch.bool:
                        # Use boolean keep masks for better SDPA stability.
                        local_mask = local_mask.eq(0)
                else:
                    raise ValueError(
                        f"Unsupported SDPA attention_mask rank: {local_mask.dim()}"
                    )

                # Avoid NaNs from fully-masked rows (common with left padding).
                if local_mask.dtype == torch.bool:
                    no_allowed = ~local_mask.any(
                        dim = -1, keepdim = True
                    )  # (bsz,1,q_len,1)
                    local_mask = local_mask | no_allowed

Comment thread unsloth/models/llama.py
Comment on lines +253 to 254
bs, seq_length, _ = inputs_embeds.shape
device = inputs_embeds.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

This correctly extracts bs and seq_length from inputs_embeds when they are used, ensuring that the model's dimensions are accurately reflected. This is important for consistent tensor handling across different input types.

Suggested change
bs, seq_length, _ = inputs_embeds.shape
device = inputs_embeds.device
elif inputs_embeds is not None:
bs, seq_length, _ = inputs_embeds.shape

Comment thread unsloth/models/llama.py
Comment on lines +256 to 257
bs, seq_length = 1, 0
device = "cuda" if torch.cuda.is_available() else "cpu"

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

This fallback ensures that bs and seq_length are initialized to default values when neither input_ids nor inputs_embeds are present. This prevents errors in subsequent operations that rely on these variables, providing robustness for edge cases.

            else:
                bs, seq_length = 1, 0

pre-commit-ci Bot and others added 2 commits February 24, 2026 14:10
- gemma: hoist rotary_seq_len computation to model level (eliminates N
  per-layer GPU-CPU syncs from position_ids.max().item()), pre-convert
  attention mask to bool once for all layers, use scalar float multiply
  instead of torch.tensor allocation for embedding scaling
- gemma2: use in-place tanh_() for softcap attention, use scalar float
  multiply for embedding scaling
- granite: pre-convert attention mask to bool once for all layers
- cohere: use in-place neg_() for rotary embedding (consistent with
  all other model files)
- falcon_h1: use in-place mul_() for key_multiplier scaling
- llama: use in-place tanh_() for logit softcapping
@danielhanchen

Copy link
Copy Markdown
Member

Pushed abe780a6 with more inference path optimizations across 6 model files (18 insertions, 11 deletions). All changes are in *_fast_forward_inference functions only -- training paths are not affected.

Changes

gemma.py (high impact):

  • Hoist rotary_seq_len computation to model level and pass it to each layer. Previously, LlamaAttention_fast_forward_inference called position_ids.max().item() per layer, causing N GPU-to-CPU synchronization points per decode step. Now computed once at the model level (1 sync instead of N).
  • Pre-convert attention mask to bool at model level (same .eq(0) hoisting pattern from llama.py and granite.py).
  • Replace torch.tensor(math_sqrt(...), dtype=...) with plain math_sqrt(...) scalar multiply to avoid per-step tensor allocation.

gemma2.py:

  • Replace torch_tanh(A, out=A) with A.tanh_() in the softcap attention path (per-layer hot path).
  • Same math_sqrt scalar multiply optimization as gemma.py.

granite.py:

  • Pre-convert attention mask to bool at model level (matching llama.py pattern).

cohere.py:

  • Replace torch.neg(x, out=x) with .neg_() for rotary embedding negation, consistent with all other model files.

falcon_h1.py:

  • Replace Kn = Kn * self.config.key_multiplier with Kn.mul_(...) to avoid per-layer tensor allocation.

llama.py:

  • Replace torch.tanh(logits, out=logits) with logits.tanh_() in the logit softcapping path.

Verification

Tested on 7 models (gemma-2b-it, mistral-7b, gemma-2-2b-it, Llama-3.2-1B, Qwen3-0.6B, Qwen2.5-0.5B, granite-3.0-2b) with single inference, batched inference, extreme padding, and long generation (4096 tokens). Also ran 21-step SFT training on Llama-3.2-1B and Qwen3-0.6B.

  • 0 resize warnings across all models
  • 0 pad tokens in output
  • Training loss decreased as expected (Llama 1.54 to 1.46, Qwen3 2.06 to 1.64)
  • Post-training inference works correctly for both single and batched

danielhanchen and others added 7 commits February 25, 2026 02:51
The original torch.tensor(..., dtype=hidden_states.dtype) is intentional:
sqrt(3072) rounds to 55.5 in bfloat16 vs 55.4256 in float32. A plain
scalar multiply may compute at higher precision internally, producing
different results. Restore the explicit dtype-cast tensor to match the
training path in LlamaModel_fast_forward.
Replace 15 hardcoded "cuda:0" with f"{DEVICE_TYPE_TORCH}:0" across
gemma.py, gemma2.py, cohere.py, and falcon_h1.py to support multi-GPU
and non-CUDA devices (XPU, etc.). Add .eq(0) bool mask pre-conversion
in CohereModel_fast_forward_inference for batched inference consistency
with llama.py, granite.py, and gemma.py.
Mllama's _update_causal_mask uses the deprecated make_flex_block_causal_mask
which creates a BlockMask with Q_LEN=KV_LEN=total_seq_len. During decode
with KV cache, q_len=1 but the block_mask still has Q_LEN=total_seq_len,
causing a ValueError. This is an upstream transformers issue -- newer models
use flex_attention_mask from masking_utils which handles decode correctly
via cache_position, but mllama has not been updated yet.

Add mllama to the exclusion list in prefer_flex_attn_if_supported alongside
gpt_oss so it falls back to sdpa, which works correctly for both training
and inference.
…n_h1, cohere

The old formula `slicing_tokens = 1 - sliding_window` uses negative indexing
that keeps `sliding_window - 1` tokens instead of `sliding_window`. For example
with sliding_window=32 and kv_seq_len=100, `1-32 = -31` keeps indices 69..99
(31 tokens) instead of the correct 68..99 (32 tokens).

Replace with `start = kv_seq_len - sliding_window` to match the fix already
applied in llama.py and the canonical definition in transformers masking_utils
(sliding_window_overlay: kv_idx > q_idx - W, which keeps exactly W tokens).

Also add attention_mask slicing after K/V trim in qwen3, falcon_h1, and cohere
to prevent mask/K dimension mismatch during batched SDPA inference, matching
the pattern already used in llama.py.

Currently only gemma2 (sliding_window=4096) is actively affected. The other
three models have sliding_window=None in their configs so the code path is
not triggered, but this keeps it correct for any future models that set it.
The attention mask must be applied AFTER logit softcapping, not before.
Both the Google DeepMind reference implementation (google-deepmind/gemma,
gm/nn/_modules.py lines 254-277) and transformers' eager_attention_forward
(gemma2/modeling_gemma2.py lines 187-193) use this order:

  1. logits = Q @ K^T * scale
  2. logits = tanh(logits / softcap) * softcap   # softcap first
  3. logits = logits + mask                       # mask after
  4. probs  = softmax(logits)

The PR had the mask addition before softcapping, which causes tanh to
clamp the -inf mask values to -softcap instead of preserving them as -inf
for softmax. While the practical impact is small (masked positions get
~1e-23 probability instead of exact zero), this should match upstream.
Add explicit parentheses to grouped query attention conditions in
llama.py, qwen3.py, granite.py to make operator precedence clear.
The expression `bsz == 1 or not X and Y` relies on Python binding
`not` > `and` > `or` which is correct but easy to misread.

Remove dead commented-out code (`# else: # Knn, Vnn = Knn, Vnn`)
and stale mask comments (`# if attention_mask ...`) from the bsz==1
fast path in llama, qwen3, cohere, falcon_h1, gemma2 inference
functions. These were leftover from the pre-batched-inference
structure and no longer apply.
@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@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 introduces a comprehensive set of fixes to address issues with left-padded batched generation, which previously resulted in incorrect outputs. The changes span multiple model implementations and the core attention dispatch logic. Key improvements include:

  1. Correct RoPE position_ids and Attention Mask Handling: The logic for generating position_ids and attention masks during decoding has been significantly improved to correctly handle non-contiguous token positions arising from left padding. This is a critical fix for models using Rotary Position Embeddings.
  2. Sliding Window Attention Fix: A bug in the slicing logic for sliding window attention has been corrected across all relevant models.
  3. Tied Embeddings: A subtle but critical bug has been fixed where zeroing out the padding token embedding could lead to incorrect logits when the embedding layer is tied to the lm_head.
  4. Robust Attention Backend Selection: The attention dispatch logic now correctly falls back to SDPA when an attention mask is present, as other backends like FlashAttention do not support arbitrary masks.
  5. Performance and Consistency: The PR also includes several performance optimizations, such as pre-computing values outside of loops, and improves code consistency by using device-agnostic initializations and more idiomatic in-place operations.

Overall, these changes are well-implemented and crucial for ensuring the correctness and robustness of batched inference with left padding. The code quality is high, and the fixes are thorough.

@danielhanchen
danielhanchen merged commit 0981c44 into unslothai:main Feb 25, 2026
vivekkalyanarangan30 added a commit to vivekkalyanarangan30/unsloth that referenced this pull request Feb 26, 2026
Integrates upstream PRs unslothai#4100 (leftpad prefill) and unslothai#4112 (v5 RoPE fix)
while preserving our multi-token prefill logic in
_fast_prepare_inputs_for_generation.

Key resolution: upstream's input_ids[:, [-1]] replaced with our
multi-token slicing (input_ids[:, past_len:]) while keeping upstream's
new infrastructure (max_cache_len, _unsloth_mask_needs_device caching,
mask_kwargs pattern, original_attention_mask-based position_ids).
abiswas-realadvice pushed a commit to abiswas-realadvice/unsloth that referenced this pull request May 14, 2026
* Fix left-padding masks and positions in batched decode/prefill

* Fix batched generation with left padding

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix attention mask handling, padding_idx zeroing, and Mistral batched generation

1. attention_dispatch.py: Fall back from flash/xformers to SDPA when an
   attention_mask is present, since flash attention only supports causal
   masking via flag and cannot consume arbitrary padding masks.

2. gemma2.py: Apply attention_mask during decode inference for bsz > 1.
   Guard against boolean SWA/GA flags with isinstance check. Slice mask
   to match K/V length when sliding window is active. Remove dead
   commented-out SDPA branch (SDPA does not support softcapping).

3. granite.py: Apply attention_mask during decode inference for bsz > 1.
   Remove dead commented-out SDPA branch and misleading comment.

4. mistral.py: Fix 2D-to-4D padding mask conversion -- convert 0/1 mask
   to additive format (0 for keep, -inf for mask) before combining with
   the causal mask. Force SDPA backend when attention_mask is present.

5. llama.py: Skip zeroing embed_tokens.weight[padding_idx] when the
   embedding is weight-tied to lm_head, since zeroing the shared weight
   forces logit(pad) = 0 which is higher than real token logits in models
   like Gemma, causing the decoder to emit pad tokens as gibberish. Also
   add eos != pad guard, clean up unused _seq_length variable, and fix
   get_max_cache_shape handling.

6. vision.py: Same padding_idx fix as llama.py for the vision model
   loading path.

Tested on gemma-2b-it, gemma-2-2b-it, Llama-3.2-1B, Mistral-7B-v0.3,
Qwen2.5-0.5B, Qwen3-0.6B with flash-attn 2.8.3 active. All outputs
coherent, zero crashes, zero resize warnings.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Inference path optimizations: eliminate per-layer GPU-CPU sync, cache inspect.signature, add Granite SDPA split

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* More inference path optimizations across model files

- gemma: hoist rotary_seq_len computation to model level (eliminates N
  per-layer GPU-CPU syncs from position_ids.max().item()), pre-convert
  attention mask to bool once for all layers, use scalar float multiply
  instead of torch.tensor allocation for embedding scaling
- gemma2: use in-place tanh_() for softcap attention, use scalar float
  multiply for embedding scaling
- granite: pre-convert attention mask to bool once for all layers
- cohere: use in-place neg_() for rotary embedding (consistent with
  all other model files)
- falcon_h1: use in-place mul_() for key_multiplier scaling
- llama: use in-place tanh_() for logit softcapping

* Revert scalar multiply for Gemma/Gemma2 embedding scaling

The original torch.tensor(..., dtype=hidden_states.dtype) is intentional:
sqrt(3072) rounds to 55.5 in bfloat16 vs 55.4256 in float32. A plain
scalar multiply may compute at higher precision internally, producing
different results. Restore the explicit dtype-cast tensor to match the
training path in LlamaModel_fast_forward.

* Fix hardcoded cuda:0 device strings and add Cohere .eq(0) bool mask

Replace 15 hardcoded "cuda:0" with f"{DEVICE_TYPE_TORCH}:0" across
gemma.py, gemma2.py, cohere.py, and falcon_h1.py to support multi-GPU
and non-CUDA devices (XPU, etc.). Add .eq(0) bool mask pre-conversion
in CohereModel_fast_forward_inference for batched inference consistency
with llama.py, granite.py, and gemma.py.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Disable flex_attention for Mllama (Llama 3.2 Vision)

Mllama's _update_causal_mask uses the deprecated make_flex_block_causal_mask
which creates a BlockMask with Q_LEN=KV_LEN=total_seq_len. During decode
with KV cache, q_len=1 but the block_mask still has Q_LEN=total_seq_len,
causing a ValueError. This is an upstream transformers issue -- newer models
use flex_attention_mask from masking_utils which handles decode correctly
via cache_position, but mllama has not been updated yet.

Add mllama to the exclusion list in prefer_flex_attn_if_supported alongside
gpt_oss so it falls back to sdpa, which works correctly for both training
and inference.

* Fix off-by-one in sliding window K/V slicing for gemma2, qwen3, falcon_h1, cohere

The old formula `slicing_tokens = 1 - sliding_window` uses negative indexing
that keeps `sliding_window - 1` tokens instead of `sliding_window`. For example
with sliding_window=32 and kv_seq_len=100, `1-32 = -31` keeps indices 69..99
(31 tokens) instead of the correct 68..99 (32 tokens).

Replace with `start = kv_seq_len - sliding_window` to match the fix already
applied in llama.py and the canonical definition in transformers masking_utils
(sliding_window_overlay: kv_idx > q_idx - W, which keeps exactly W tokens).

Also add attention_mask slicing after K/V trim in qwen3, falcon_h1, and cohere
to prevent mask/K dimension mismatch during batched SDPA inference, matching
the pattern already used in llama.py.

Currently only gemma2 (sliding_window=4096) is actively affected. The other
three models have sliding_window=None in their configs so the code path is
not triggered, but this keeps it correct for any future models that set it.

* Fix Gemma2 softcapping order: apply mask after softcap, not before

The attention mask must be applied AFTER logit softcapping, not before.
Both the Google DeepMind reference implementation (google-deepmind/gemma,
gm/nn/_modules.py lines 254-277) and transformers' eager_attention_forward
(gemma2/modeling_gemma2.py lines 187-193) use this order:

  1. logits = Q @ K^T * scale
  2. logits = tanh(logits / softcap) * softcap   # softcap first
  3. logits = logits + mask                       # mask after
  4. probs  = softmax(logits)

The PR had the mask addition before softcapping, which causes tanh to
clamp the -inf mask values to -softcap instead of preserving them as -inf
for softmax. While the practical impact is small (masked positions get
~1e-23 probability instead of exact zero), this should match upstream.

* Clarify GQA condition precedence and remove stale comments

Add explicit parentheses to grouped query attention conditions in
llama.py, qwen3.py, granite.py to make operator precedence clear.
The expression `bsz == 1 or not X and Y` relies on Python binding
`not` > `and` > `or` which is correct but easy to misread.

Remove dead commented-out code (`# else: # Knn, Vnn = Knn, Vnn`)
and stale mask comments (`# if attention_mask ...`) from the bsz==1
fast path in llama, qwen3, cohere, falcon_h1, gemma2 inference
functions. These were leftover from the pre-batched-inference
structure and no longer apply.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Jun 10, 2026
…oral tests

No new workflow and no new CI job: the guard now runs as one HARD GATE step
inside consolidated-tests-ci.yml, right after the callback signature drift
detector, where the CPU torch stack is already installed. The AST structural
checks and the behavioral unit tests live in a single file
(tests/utils/test_prepare_inputs_leftpad.py); the AST layer stays stdlib-only
with unsloth imported lazily inside the behavioral tests, so import breakage
cannot mask the structural checks.

Revalidated after the merge: 11 assertions pass on main, 8 fail at
6d0f864~1 (pre #4100).
danielhanchen referenced this pull request in danielhanchen/unsloth-staging-2 Jun 10, 2026
danielhanchen added a commit that referenced this pull request Jun 10, 2026
…egress again (#1066, #3699) (#6145)

* Add regression guard for batched left-padded generation (#1066, #3699)

Three layers of tests plus a path-filtered CI workflow so the left-padding
position_ids / attention-mask bug class cannot silently return:

- tests/utils/test_prepare_inputs_ast_guard.py: import-free AST checks on
  _fast_prepare_inputs_for_generation (cumsum-from-mask branch present,
  cache_position only as fallback, no mask truncation, model families wired)
- tests/utils/test_prepare_inputs_leftpad.py: CPU behavioral unit test with
  synthetic left-padded masks and fake caches; exact expected position_ids
  for prefill and cached decode
- tests/utils/test_batched_leftpad_generation_gpu.py: optional GPU e2e,
  solo vs batched prefix match, skipped without CUDA
- .github/workflows/batch-inference-guard.yml: ubuntu-latest CPU job running
  the two deterministic layers on PRs touching unsloth/models/**

Validated: all pass on main; both CPU layers fail at 6d0f864~1 (pre #4100)
and at 332eabf~1 (pre #2216), reproducing the historical bug signatures.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Cite staging proof in batch-inference-guard header (staging-2 PRs 170/171)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fold left-padding guard into consolidated Core CI; merge AST + behavioral tests

No new workflow and no new CI job: the guard now runs as one HARD GATE step
inside consolidated-tests-ci.yml, right after the callback signature drift
detector, where the CPU torch stack is already installed. The AST structural
checks and the behavioral unit tests live in a single file
(tests/utils/test_prepare_inputs_leftpad.py); the AST layer stays stdlib-only
with unsloth imported lazily inside the behavioral tests, so import breakage
cannot mask the structural checks.

Revalidated after the merge: 11 assertions pass on main, 8 fail at
6d0f864~1 (pre #4100).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update staging proof reference for consolidated gate (PRs 170/172)

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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