Repository navigation
enable cudagraph for varlen pretrain - #4156
Conversation
a4121fb to
16c022f
Compare
16c022f to
2ee380c
Compare
2ee380c to
98db6d3
Compare
98db6d3 to
408d667
Compare
04027dd to
52f66ca
Compare
04c222e to
e46fd4e
Compare
e46fd4e to
7804d1d
Compare
7804d1d to
ab86951
Compare
2274d97 to
9d25283
Compare
9d25283 to
25ba60f
Compare
|
@claude review this PR. In particular, I found the logic in torchtitan/components/data/packing.py complicated. Could it be simplified? Overall, I would like to make sure
|
|
Claude finished @tianyu-l's task in 4m 57s —— View job Review: enable cudagraph for varlen pretrainI read through 1. Documents longer than
|
61abf3c to
1458a33
Compare
tianyu-l
left a comment
There was a problem hiding this comment.
overall looks great. Having some remaining questions but don't want to block merging
| else torch.as_tensor(row.padding_mask, dtype=torch.bool) | ||
| for row in rows | ||
| ] | ||
| ) |
There was a problem hiding this comment.
This seems to suggest that positions and padding_mask can be handled either before collator or by collator, correct?
| grid.append(ranks) | ||
| return grid | ||
|
|
||
| def _build_document_limited_microbatch_grid( |
There was a problem hiding this comment.
didn't check the internal of this function, but I believe things could be made simpler when we fold the batch dim in each microbatch @wwwjn
| "max_context_length is required when max_num_documents is set" | ||
| ) | ||
|
|
||
| max_num_padding_segments = ( |
There was a problem hiding this comment.
I didn't understand what this count is for. Here's my guess but it could be off.
There are generally two types of padding
- per document padding, e.g. needed by FlexAttention to achieve batch invariance
- per sequence / row padding, at the end of a (row of a) microbatch
I originally thought varlen meta data only needs to know about 2, but it seems here you are accounting for 1 as well? What's the tradeoff of varlen metadata to consider 1 vs. not? Naively it sounds to me that
- knowing 1 would help varlen to compute less (no attention on the per document padding)
- knowing 1 would require varlen to allocate more resource to take care of padding
Would you argue knowing 1 is strictly better?
|
@claude
Also take a look at my comment #4156 (comment) and provide insight. |
|
Claude finished @tianyu-l's task in 9m 11s —— View job The two packing strategies in this version, vs. your three goalsFirst, the good news on the thing you flagged as complicated: the old ConcatThenSplit —
FirstFit —
Against your three goals
So the one real divergence from your spec is goal 3's "continue the positions counting." Today a segment straddling the row's token budget resets to position 0 on the next row. Why it's not a one-line fix, and why it points at your Worth deciding explicitly: do you even want to split a segment across a row boundary (goal 3 as written), or push the whole segment to the next row when it doesn't fit? The latter costs a little padding but keeps every document contiguous with correct positions, and needs no On discussion r3887847182 -- per-document vs per-row padding in the varlen metadataYour two categories are the right frame. Here's what the metadata actually does with each:
So to answer your literal question: the metadata is not accounting for type-1 per-document padding as separate segments -- type 1 is hidden inside its document's seqlen. It is reserving slots for fragmented type-2 tail padding. The fragmentation is forced by the pinned Is "knowing type 1" strictly better? No. For causal attention, per-document pad tokens sit at the tail of a document, so they are only ever queries (masked out of loss) attending back to real keys -- there are no later real tokens in that doc to attend to them. Isolating them as their own segment therefore saves no correctness and only avoids the padding queries' own compute, at the cost of (a) more segment slots and (b) a larger fixed-shape metadata buffer under cudagraph. That's a pure compute-vs-metadata-footprint trade, not a strict win. Given cudagraph wants the metadata small and fixed, folding type-1 padding into the document (as the RL batcher already does) is the better default; the kernel wastes a little compute on tail pads but the slot count stays minimal. The place I'd actually change: type-2 tail padding. Resetting it
|
1458a33 to
cc4c96e
Compare
cc4c96e to
d8c32c5
Compare
d8c32c5 to
ad79d1d
Compare
## What changes - `KimiK3Model.get_attention_masks` returns a mask dict, like Qwen3.5. MLA layers read "quadratic_attention" and KDA layers read "kda". The "kda" entry is the VarlenMetadata that Attention Gym's causal_conv1d and chunk_kda use to reset the conv window and the recurrent state at each document start. Each block picks its own entry by `attn_mask_key`. The signature is the same as `Decoder.get_attention_masks` after #4156. - The multimodal packer numbers its padding positions from the first padded token, modulo max_context_length. - `kimi_k3_debugmodel` takes `seq_len` like every other debug config and sizes its rows from the model spec, so it runs 2048-token rows instead of a fixed 256. The text path and the helper itself landed in #4156. This PR only touches the multimodal packer, the multimodal collator and Kimi K3. ## Verification **Packing on the debug config.** `kimi_k3_debugmodel` rows are 2048 tokens and one cc12m sample is about 210 tokens, so without the packer a row holds one document and the rest is padding. With `MMSamplePackingConfig` wrapped around the dataset: | | Documents per row | Padding tokens per row | |---|---|---| | No packer | 1 | 1837 | | Packer | 16 | 3 | **End to end on B200.** `kimi_k3_debugmodel`, 10 steps, `--debug.seed 42 --debug.deterministic`. With the packer, loss went from 12.50 to 3.26 over 10 steps and grad_norm from 15.1 to 2.2. Without the packer, loss went from 12.45 to 4.50. These numbers come from the previous revision of this branch; the K3 wiring is unchanged. TODO: re-run on this revision. Kimi K3 does not match main bitwise on rows with padding, and should not: on main the KDA layers receive no offsets at all. ## TODO - [ ] `get_attention_masks` in Kimi K3 and Qwen3.5 are near-identical and should be shared; needs a design.
…ext (#5664) In `torchtitan/components/data/packing.py`, `ConcatThenSplitPackingConfig` without `max_num_documents` (the default) passes processor-supplied `TextSequence.positions` through unchanged. `_text_sequence_to_packing_input` only fills in positions when they are `None` (`arange % max_context_length`), and `_packing_output_to_text_sequence` rebases them per document without wrapping. So a positioned document longer than `max_context_length` comes out with row positions up to `num_tokens_per_microbatch - 1`. Those index past the RoPE cache, which has `max_context_length` rows. FirstFit and the document-capped concat-then-split path already split such documents (since #4156), and `test_packing_splits_positioned_long_documents` checks `positions.max() < max_context_length` for them, but only with `max_num_documents=2`. With one 14-token positioned document, `max_context_length=4` and 8-token rows, the uncapped packer on main gives: ``` ConcatThenSplit, max_num_documents=None: positions=[0, 1, 2, 3, 4, 5, 6, 7] -> rope_cache[positions] IndexError: index 4 is out of bounds for dimension 0 with size 4 ConcatThenSplit, max_num_documents=2 : positions=[0, 1, 2, 3, 0, 1, 2, 3] FirstFit, max_num_documents=None: positions=[0, 1, 2, 3, 0, 1, 2, 3] ``` With this change the first row is `positions=[0, 1, 2, 3, 0, 1, 2, 3]`, the same as the other two paths, and the other lines do not change. ```mermaid flowchart LR P["processor positions 0..13"] --> I["_text_sequence_to_packing_input"] I -->|"main: passed through"| B["row positions 0..7 >= max_context_length"] I -->|"this PR: restart at each 0 and every max_context_length"| A["row positions 0..3, 0..3"] B --> R["RoPE cache index out of bounds"] A --> OK["same as FirstFit and the capped packer"] ``` The fix restarts provided positions at each document start (a zero position) and every `max_context_length` tokens after it. Missing positions already get exactly this wrapping. FirstFit and nested packers feed this function segments that already fit the context, so nothing changes for them. In-tree `TextProcessor` and `ChatProcessor` leave positions `None`, so the c4 recipes are not affected. This only matters for custom processors that return positions. Test, in `tests/unit_tests/cpu/components/data/test_grain_data.py`: `test_packing_splits_positioned_long_documents` now also runs with `max_num_documents=None` (17 tokens, 16 positions, so every combination packs two full rows) and checks that positions stay below `max_context_length` for both packers; the doc-count assert applies only to the capped case. The uncapped concat-then-split case fails on main and passes with this change; the other three cases pass on both. In all of `tests/unit_tests/cpu/components/data`, 201 pass. The 3 failures there also fail on main on Windows: two need the inductor C++ compiler (`cl`) and one runs `generate.py --check`. That was on Windows with Python 3.11 and torch 2.16.0.dev20261024+cpu. `pre-commit run` on the two changed files passes flake8, ufmt, pydoclint, codespell and pyrefly. The lychee hook needs `/bin/bash`, so it did not run on Windows. These ran on Windows 11, CPU only. Nothing was run on Linux or GPU, so Linux CI will confirm.
Uh oh!
There was an error while loading. Please reload this page.