Skip to content

Gemma 4 packed SFT: efficient kernel for the 512-wide global layers, processor on text-only data - #13384

Merged
danielhanchen merged 35 commits into
mainfrom
gemma4-packed-wide-heads
Oct 12, 2026
Merged

danielhanchen merged 35 commits into
mainfrom
gemma4-packed-wide-heads

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

Stacked on #13326. Packed / padding-free SFT for Gemma 4 on the transformers modeling path: the 512-wide global attention layers stop building a dense T x T mask, and training with the processor on a text-only dataset (the usual notebook flow) can pack at all.

Global layers (head dim 512)

Gemma 4's global layers use head dim 512, past every flash-family kernel (256). Packed rows there went to SDPA over a dense block-causal mask, which only the masked memory-efficient kernel runs, and its cost grows with T squared.

  • Packed calls with head dim 257 to 512 now call SDPA's own memory-efficient kernel (aten._efficient_attention_forward / backward) with the packed cu_seqlens, causal per document, the window on sliding layers, and K/V repeated for GQA. No compile, no graph break, available from torch 2.7.
  • The same route takes shapes the active FA4 / FA3 impl refuses (sm100 head dim 256 with a window) when neither flash-attn nor xformers is installed, instead of the dense mask.
  • Every existing check still applies first: the mask must be exactly block-causal (with the window when sliding), scaling passed through, no softcap, sinks or dropout, batch 1. It stays off on ROCm, below sm80, under deterministic algorithms, with the efficient SDPA backend disabled, and past head dim 512. If the kernel refuses the shape, that call falls back to the wrapped SDPA, the route is turned off for the process and a warning says so; out of memory and CUDA faults are raised as before.
  • UNSLOTH_HF_PACKED_EFFICIENT=0 turns it off; HF_PACKED_ATTENTION_STATS["efficient"] counts it.
  • gemma4_unified / gemma4_unified_text (gemma-4-12b) join gemma4 in _FLEX_LARGE_HEAD_DIM_EXCLUDED_MODELS, so on large shared memory GPUs its text layers load as sdpa like the other Gemma 4 models instead of flex.

Forward + backward, bf16, 8 query heads, mixed document lengths 64 to 4096, median of alternating fresh-process runs:

head dim / KV heads / window tokens dense mask (main) per-document SDPA this PR
B200: 512 / 2 / none 8K 67.9 ms 20.6 ms 13.4 ms
B200: 512 / 2 / none 16K 244.6 ms 46.5 ms 30.9 ms
B200: 256 / 2 / 512 16K 19.6 ms 28.9 ms 7.4 ms
RTX PRO 6000: 512 / 2 / none 8K 83.4 ms 16.1 ms
RTX PRO 6000: 512 / 2 / none 16K 278 ms 36.6 ms

Compiled flex attention with a document block mask is about 2x faster again per layer, but needs explicit tiles at head dim 512 (the default ones fault), an 18 s first compile, and a block mask per batch; on E4B that is worth 2 to 4% of a step, so it is left as a follow-up.

Processor on a text-only dataset

FastModel returns a processor for Gemma 3 and Gemma 4, and passing it as processing_class turned packing and padding-free off unconditionally, even for text-only data.

  • For Gemma 3 / Gemma 4 / gemma-4-12b (gemma4_unified) (and their text-only decoders, gemma3_text / gemma4_text / gemma4_unified_text, which FastLanguageModel loads from a multimodal checkpoint) with a processor that has a tokenizer, and a dataset with no media, packing / padding-free is allowed through the processor's tokenizer. Other processor models keep today's behaviour: packed text rows were only verified to equal each document alone for these families (Mllama and PaliGemma build their masks without the packed boundaries on some transformers versions, and Qwen2-VL style models need 3D position ids).
  • "No media" is conservative: no Image / Audio / Video feature anywhere in the schema, and no column or nested key whose name mentions images, audio, video or pixels (so image_path, audio_url, input_values, or a string image inside messages keep the old behaviour), no message part that names its modality only in its type value ({"type": "audio", "url": ...}; only {type, text} parts count as text), and no with_transform / set_transform (their rows can hold images the stored columns do not show).
  • Needs TRL 1.10 or newer: every TRL up to 1.9.2 refuses packing and padding-free for any processor, and 1.10 refuses only datasets whose rows hold images. Older TRL keeps today's behaviour without trying. If TRL still refuses, the trainer falls back to the old behaviour.
  • UNSLOTH_PROCESSOR_TEXT_PACKING=0 (or false / off) turns it off.

unsloth/gemma-4-12b-it

4-bit, LoRA r=16, FineTome text, max length 4096, 20 steps, on a Colab RTX PRO 6000 (torch 2.14.1, transformers 5.17.0, TRL 1.13.0) with unslothai/unsloth-zoo#1690 and unslothai/unsloth-zoo#1708, arms alternating packed / padded / padding-free / padding-free / padded / packed:

run real tokens/s (2 runs) step peak allocated
padded, batch 4 (what a processor gets on main) 1346 / 1401 1.37 s 11.55 GB
padding-free 3035 / 3096 0.66 s 9.91 GB
packing=True, rows of 4096 3703 / 3690 1.10 s 9.91 GB

Packed runs about 2.7x the padded token throughput with 1.6 GB less memory. Every attention call took a varlen or efficient route (1920 sliding / 320 global per run, 0 fallbacks), losses fall from about 3.3 to 1.2 to 1.5 in every arm, and generate() after training works in every run.

Correctness

Tiny models built from the real E2B, E2B without KV sharing, E4B, 31B (attention_k_eq_v), 26B-A4B (MoE) and 12B (gemma4_unified, vision and audio towers) configs, keeping head dim 512, packed rows compared against each document run alone, compile on and off, torch 2.14 and 2.11:

  • Later-document logit gaps 0.02 to 0.05 (the same as the first document, which cannot leak) against 1.7 to 1.9 for a row that attends across documents; LoRA grad relative error 0.013 to 0.04 against 0.77 to 1.1.
  • Per forward on head: sliding layers on varlen, global layers on the efficient kernel, 0 dense T x T calls. Main runs all layers on the dense mask (compile off; compile on needs Compiler: do not emit imported helpers shadowed by a same-named method, and quote fixed-up annotations (Gemma 4 load on transformers 5.x) unsloth-zoo#1690 to load).
  • On the 26B-A4B MoE config a few tokens switch experts on bf16 noise in both main and this PR, so its check uses the mean gap (0.004 against 0.25).
  • With compile on, E4B gives the same graph count with the route on and off (24 graphs, 0 graph breaks, 0 recompiles).

ROCm

On a Radeon 8060S (gfx1151, torch 2.11 ROCm, transformers 5.5.0), main against this PR on a tiny packed Gemma 4 (sliding head dim 256, global 512): the efficient route never runs there (0 calls), losses are bit-identical to main with the route on and with UNSLOTH_HF_PACKED_EFFICIENT=0, and the PR's tests pass (236 passed, 0 failed; main fails 5 of the existing packed attention tests on that host, which #13326 fixes).

Tests

  • tests/test_hf_packed_attention.py: output and dQ / dK / dV parity against transformers' sdpa_attention_forward over its own mask at head dim 512 with 8, 2 and 1 KV heads, with and without a window; each document against its own run; every fallback reason; the kernel raising and handing back; FA4 refused shapes with and without flash-attn; reentrant checkpointing; fullgraph compile; a tiny Gemma4ForCausalLM end to end with head dim 512, attention_k_eq_v on and off.
  • tests/test_flex_gemma4_sliding_scope.py: gemma4_unified stays on sdpa.
  • tests/test_processor_text_packing_gate.py: text-only vs image / audio / message-part / media-named / transformed datasets, eval splits, the model families allowed and kept out, TRL before 1.10 never trying, TRL refusals falling back, the kill switch spellings.
  • These and the existing packing / attention test files pass on torch 2.14 + transformers 5.17, torch 2.11, torch 2.10 (no torch varlen) and torch 2.7.1 + transformers 4.57.6 + TRL 0.22.2 (no Gemma 4 there, so its tests skip; the head dim 512 parity tests run).

danielhanchen and others added 25 commits October 11, 2026 05:40
…_seqlens

Gemma 4 global layers (head_dim 512, scaling 1.0, GQA) fell back to SDPA over the dense T x T
block-causal mask. They now run torch's memory-efficient attention with cu_seqlens and a causal
mask per segment (window_size on sliding layers), K / V heads repeated, after the same checks as
the varlen route: the mask is exactly block-causal, no softcap / sinks / dropout, matching dtypes,
and no SDPA policy (deterministic, math-first, efficient disabled) asking for SDPA itself. Shapes
an FA4 / FA3 impl refuses with no flash-attn / xformers installed take it too instead of the dense
mask. UNSLOTH_HF_PACKED_EFFICIENT=0 turns it off; HF_PACKED_ATTENTION_STATS counts it.

Also keep gemma4_unified / gemma4_unified_text off the large head dim flex route, as gemma4.
FastModel returns a processor for Gemma 3 / Gemma 4 and most VLMs, and the
processor gate blocked packing even when every row is text. TRL tokenizes and
collates those rows through the processor's tokenizer, so they now pack.
Media columns or features, unknown schemas, custom collators, multimodal RoPE
models and TRL < 0.24 (which refuses any processor) keep the old block.
UNSLOTH_PROCESSOR_TEXT_PACKING=0 restores it everywhere.
…s stay blocked; efficient route reads its switch per call
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-12T13:30:49.001596Z 29ea1a1 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: a8777778a0

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/trainer.py Outdated
Comment on lines +327 to +330
if isinstance(node, dict):
if any(_is_media_name(key) for key in node):
return True
stack.extend(node.values())

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 Reject discriminator-only media entries before packing

For a Gemma 4 dataset using the documented audio-message shape {"type": "audio", "url": "..."}, the inferred feature tree contains only generic keys such as type and url, so this traversal returns false even though each row contains media. The same gap applies to similar image/video message formats whose modality appears only in the type value. _processor_text_only consequently enables packing or padding-free training for multimodal rows, despite that path being validated only for text and potentially dropping required media inputs or corrupting packed training; inspect modality discriminator values or conservatively reject such structured message schemas.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch, fixed in 270d20f. A nested struct with a type discriminator and any key besides text (url, path, base64, ...) now counts as media, so {"type": "audio", "url": ...} and the image / video equivalents keep packing off. Pure {type, text} parts and a top-level type column still read as text. Tests added; they fail without the check.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 270d20ff08

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Base automatically changed from packed-varlen-windows-fa4 to main October 12, 2026 12:33
# Conflicts:
#	tests/test_hf_packed_attention.py
#	tests/utils/test_flash_impl.py
#	unsloth/utils/hf_packed_attention.py
@danielhanchen
danielhanchen merged commit 37f9088 into main Oct 12, 2026
@danielhanchen
danielhanchen deleted the gemma4-packed-wide-heads branch October 12, 2026 13:31
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 16, 2026
…nslothai#13869)

Gemma-4 global attention layers use head_dim 512. FlashAttention-2 and
the flash / cuDNN SDPA backends stop at 256, so these layers run on
SDPA's memory-efficient or math kernels, and padded or packed batches
also materialise a dense 4D mask for them.

This adds `unsloth/kernels/large_head_attention.py`, a Triton flash
attention forward and backward for head_dim 512, and routes
transformers' `sdpa` attention through it when a call qualifies. It
reads GQA kv heads in place (the dK/dV pass loops over each kv head's
query heads, so there are no atomics and no repeated K/V), and takes any
mask whose allowed keys per query row form one interval with
non-decreasing ends: causal, bidirectional, packed documents, right
padding and sliding windows. Whole kv blocks outside a row block's
interval are skipped, which is where packed batches gain the most. Masks
are converted once per step with one host sync and the result is cached
on the mask tensor for every layer.

The route is installed by `FastModel.from_pretrained` only for models
with head_dim 512 layers. It engages for CUDA fp16 / bf16, dropout 0, no
softcap, equal query and key lengths, and after a one time forward and
backward self check against SDPA on that device and dtype; everything
else (left padding, per-head masks, decode with a cache, ROCm, fp32)
goes to the previous `sdpa` function unchanged. Under torch.compile the
maskless case runs the kernel as an opaque custom op with no graph
break; masked calls keep SDPA. `UNSLOTH_HD512_ATTENTION=0` disables it.
The tiling follows axolotl's flash_attn_d512 kernel (Apache-2.0).

Accuracy: against an fp64 reference over 1344 cases (S from 2 to 700,
GQA 1 to 8, seven mask kinds, fp16 and bf16) on B200 and A100, the mean
error of out / dQ / dK / dV is at or below SDPA's memory-efficient
backend at the same dtype (median ratios 0.99 / 0.84 / 0.77 / 0.81). On
q, k, v captured from Gemma-4 global layers the kernel is again at or
below SDPA's error. compute-sanitizer memcheck is clean on every config.
A 50-step LoRA run on a tiny Gemma-4 matches the SDPA path within the
SDPA path's own run-to-run noise, and the kernel path is deterministic.

Speed, attention forward plus backward on an A100 at head_dim 512: 1.4x
to 2.1x on causal rows (S 1024 to 8192) and 1.8x to 18x on packed rows
(more documents, larger gain), with 3x to 4.9x lower peak memory. The
packed numbers are against SDPA with a dense 4D mask. Main's packed
router (unslothai#13384) already sends packed rows that carry
`packed_seq_lengths` (the usual packing / padding-free SFT flow) to
SDPA's efficient kernel over cu_seqlens, and that route is kept: the
head_dim 512 wrapper sits beneath it. So in standard training the gains
apply to dense causal and right-padded batches. On a B200 the range is
1.09x to 1.80x causal and 1.5x to 19x packed; one case is slower (8
query heads on 1 kv head, S 1024, two packed documents: 0.73x), where
the per-call mask scan dominates in the microbenchmark (in training it
is shared across all global layers). In fp16, Unsloth's Gemma-4 path
computes attention in float32 and does not reach this kernel, so the
gain applies to bf16 training.

Not covered: T4 and L4 (the larger block configs do not fit T4 shared
memory; the self check should fall back to SDPA there, untested), an end
to end timing on a real Gemma-4 checkpoint, older torch versions and
ROCm (the route stays off on ROCm).

---------

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.

1 participant