Skip to content

[varlen] Fix non-hub backends mispacking keys for non-contiguous masks#14152

Open
Functionhx wants to merge 1 commit into
huggingface:mainfrom
Functionhx:fix/varlen-nonhub-mispack
Open

[varlen] Fix non-hub backends mispacking keys for non-contiguous masks#14152
Functionhx wants to merge 1 commit into
huggingface:mainfrom
Functionhx:fix/varlen-nonhub-mispack

Conversation

@Functionhx

@Functionhx Functionhx commented Jul 9, 2026

Copy link
Copy Markdown

What does this PR do?

Fixes #14139.

Three non-hub varlen backends used a per-batch slice pattern that fails for non-contiguous attention masks. Applied the same nonzero-gather fix already used in the hub backends (#14115).

Before submitting

  • Read the contributor guideline
  • Discussed via GitHub issue
  • This PR adds a new model/pipeline — No
  • New tests — No, this is a targeted bug fix
  • Documentation — No changes needed

AI agent disclosure

  • Did you use an AI agent? Yes (code review and verification)
  • Did you read the Coding with AI agents guide? Yes
  • Did you self-review against .ai/review-rules.md? Yes

Who can review?

Anyone in the community.

…ous masks

The three non-hub varlen backends (_flash_varlen_attention,
_flash_varlen_attention_3, _sage_varlen_attention) used a per-batch
slice pattern (key[b, :valid_len]) that fails when the attention mask
is non-contiguous. The hub backends (FLASH_VARLEN_HUB,
_FLASH_3_VARLEN_HUB) already received this fix via the nonzero gather
pattern.

Root cause: The per-batch slice assumes a contiguous mask layout, but
non-contiguous masks have different cu_seqlens structures. The slice
picks up wrong positions from each batch element.

Fix: When a mask is present, use attn_mask.flatten().nonzero().flatten()
to gather valid positions from reshaped key/value tensors, which
correctly handles any mask contiguity. When no mask, use simple
flatten(), which is always contiguous. This matches the exact pattern
used in the hub backends.

Closes huggingface#14139.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Yuchen Fan <functionhx@gmail.com>
@github-actions github-actions Bot added fixes-issue size/M PR with diff < 200 LOC models and removed size/M PR with diff < 200 LOC labels Jul 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Non-hub varlen attention backends mispack keys for non-contiguous masks (missed in #14114/#14115)

1 participant