Repository navigation
Fix/pr 3699 leftpad prefill main - #4100
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 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 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.
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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.
There was a problem hiding this comment.
💡 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".
| if hasattr(past_key_values, "get_max_cache_shape"): | ||
| m = int(past_key_values.get_max_cache_shape()) |
There was a problem hiding this comment.
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 👍 / 👎.
| else: | ||
| if input_ids is not None and input_ids.numel() > 0: | ||
| bs, cache_length = input_ids.shape | ||
| bs, _seq_length = input_ids.shape |
There was a problem hiding this comment.
Is this a typo? seq_length perhaps?
| bs, _seq_length = input_ids.shape | ||
| input_ids = input_ids[:, [-1]] | ||
| device = input_ids.device | ||
| seq_length = input_ids.shape[1] |
There was a problem hiding this comment.
Maybe we should fix L248 and remove this?
| 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? |
There was a problem hiding this comment.
| 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) |
There was a problem hiding this comment.
NIT: we should move these to get_cached function itself then?
| bs, seq_length = 1, 0 | ||
| device = "cuda" if torch.cuda.is_available() else "cpu" | ||
|
|
||
| if hasattr(past_key_values, "get_seq_length"): |
There was a problem hiding this comment.
perhaps lets move all this to a separate function ?
| # Attention module | ||
| use_varlen = seq_info is not None and past_key_value is None | ||
| backend = select_attention_backend(use_varlen) | ||
| backend = ( |
There was a problem hiding this comment.
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.
|
Pushed a follow-up commit (26f23be) with additional fixes found during testing: 1. Centralized flash-to-SDPA fallback ( 2. Gemma2 decode inference mask ( 3. Granite decode inference mask ( 4. Mistral 2D-to-4D mask conversion ( 5. padding_idx zeroing for tied embeddings ( 6. Same padding_idx fix for vision path ( Test results (flash-attn 2.8.3, B200 GPU)
All outputs coherent, zero crashes, zero resize warnings. Remaining mismatches are expected floating-point divergence between flash (individual) and SDPA (batched) backends. |
|
/gemini review |
There was a problem hiding this comment.
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.
| 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, :, :] | ||
| ) |
There was a problem hiding this comment.
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.
| 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, :, :] | |
| ) |
| # ---- 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 |
There was a problem hiding this comment.
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| bs, seq_length, _ = inputs_embeds.shape | ||
| device = inputs_embeds.device |
There was a problem hiding this comment.
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.
| bs, seq_length, _ = inputs_embeds.shape | |
| device = inputs_embeds.device | |
| elif inputs_embeds is not None: | |
| bs, seq_length, _ = inputs_embeds.shape |
| bs, seq_length = 1, 0 | ||
| device = "cuda" if torch.cuda.is_available() else "cpu" |
There was a problem hiding this comment.
… inspect.signature, add Granite SDPA split
- 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
|
Pushed Changesgemma.py (high impact):
gemma2.py:
granite.py:
cohere.py:
falcon_h1.py:
llama.py:
VerificationTested 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.
|
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.
|
/gemini review |
There was a problem hiding this comment.
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:
- Correct RoPE
position_idsand Attention Mask Handling: The logic for generatingposition_idsand 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. - Sliding Window Attention Fix: A bug in the slicing logic for sliding window attention has been corrected across all relevant models.
- 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. - 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.
- 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.
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).
* 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]>
…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).
…consolidated CI)
…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>
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/1livuOKZoEUu04IEUP_gftcf_A_dz_zzF?usp=sharing