Repository navigation
Gemma 4 packed SFT: efficient kernel for the 512-wide global layers, processor on text-only data - #13384
Conversation
…sm90, gated and probed
… reused padding-free collator
…_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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
# Conflicts: # unsloth/utils/packing.py
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if isinstance(node, dict): | ||
| if any(_is_media_name(key) for key in node): | ||
| return True | ||
| stack.extend(node.values()) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
# Conflicts: # tests/test_hf_packed_attention.py # tests/utils/test_flash_impl.py # unsloth/utils/hf_packed_attention.py
…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>
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.
aten._efficient_attention_forward / backward) with the packedcu_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.UNSLOTH_HF_PACKED_EFFICIENT=0turns it off;HF_PACKED_ATTENTION_STATS["efficient"]counts it.gemma4_unified/gemma4_unified_text(gemma-4-12b) joingemma4in_FLEX_LARGE_HEAD_DIM_EXCLUDED_MODELS, so on large shared memory GPUs its text layers load assdpalike 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:
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_classturned packing and padding-free off unconditionally, even for text-only data.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).Image/Audio/Videofeature anywhere in the schema, and no column or nested key whose name mentions images, audio, video or pixels (soimage_path,audio_url,input_values, or a stringimageinsidemessageskeep the old behaviour), no message part that names its modality only in itstypevalue ({"type": "audio", "url": ...}; only{type, text}parts count as text), and nowith_transform/set_transform(their rows can hold images the stored columns do not show).UNSLOTH_PROCESSOR_TEXT_PACKING=0(orfalse/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:
packing=True, rows of 4096Packed 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: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_forwardover 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 tinyGemma4ForCausalLMend to end with head dim 512,attention_k_eq_von and off.tests/test_flex_gemma4_sliding_scope.py:gemma4_unifiedstays 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.