Skip to content

[data] Add opt-in per-sample padding for packed segments - #6059

Merged
tianyu-l merged 3 commits into
pytorch:mainfrom
sdmyzlp:dsv4-doc-alignment
Nov 19, 2026
Merged

tianyu-l merged 3 commits into
pytorch:mainfrom
sdmyzlp:dsv4-doc-alignment

Conversation

@sdmyzlp

@sdmyzlp sdmyzlp commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Summary (human-written)

The data pipeline can now pad each emitted document segment to a multiple before packing, through a helper shared with the RL batcher. This lands the padding capability only: no recipe enables it yet, and the DeepSeek-V4 alignment/compressor changes are deferred until the CP work.

Why

The document-aware concat-then-split packer had no way to make every emitted segment length a multiple; the RL batcher already does this per sample. This adds one opt-in knob and one shared implementation, without changing any existing config.

documents of 5 and 3 tokens, per_sample_pad_multiple=4, row 16
before: segments [5][3], then 8 pad tokens
after:  segments [8][4], then 4 pad tokens   # positions continue; padded tokens masked

No recipe enables per_sample_pad_multiple yet. The DeepSeek-V4 alignment requirement and the compressor simplification it enabled are dropped from this PR: they would introduce padding that no current configuration needs, and will be revisited with CP.

What changed

  • components/data/padding.py: append_padded_segment appends one segment's fields, positions and padding mask. Callers own label shifting, splitting, fill values and row-tail padding.
  • components/data/packing.py: the document-aware packer calls the helper and emits segments padded to the configured multiple.
  • components/data/loader.py / types.py: per_sample_pad_multiple: int = 1, where 1 leaves lengths unchanged; larger values require document-aware packing and must divide both context and microbatch lengths. Values below 1 are rejected.
  • rl/trainer/batcher.py: reuse the shared helper and round_up.
  • Tests: token preservation plus resume for the aligned packer, and RL field alignment and counts.

Numerics

Behavior is unchanged for every existing config (per_sample_pad_multiple=1), and no recipe enables it. No model-run numerics claim; the packer tests cover token preservation and the padded-token mask.

Testing

pytest -q tests/unit_tests/cpu/components/data tests/rl/unit_tests/cpu/test_batcher.py — 249 passed.

Pre-commit passes on the changed files; pyrefly reports only the two pre-existing baseline errors in untouched files.

Known issues / follow-ups

  • The DeepSeek-V4 alignment and compressor simplification are deferred until CP work actually needs the aligned layout.
  • No recipe sets per_sample_pad_multiple; the capability is unused today by design.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 12, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@sdmyzlp sdmyzlp changed the title [dataloader] Pad packed document segments to a configured alignment [dsv4] Require document-aligned packing and simplify compression Nov 12, 2026
@sdmyzlp
sdmyzlp marked this pull request as ready for review November 12, 2026 15:11
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 12, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 45s —— View job


Request changes: review -- DSV4 loss evidence is missing, and the recipe mutates nested loader configs in __post_init__.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Request changes -- the padding approach is sound, but the PR changes DeepSeek-V4's training data with no loss evidence, and the recipe enables it by mutating nested loader configs in __post_init__.

What this PR does. The document-aware concat-then-split packer gets an opt-in document_alignment. Each emitted segment is padded up to a multiple of it: padded tokens get labels=IGNORE, padding_mask=True, and positions that keep counting. DeepSeek-V4 sets the alignment to the lcm of its compression ratios. Because every segment then ends on a group boundary, the compressor can group the whole row as [L/R, R] directly, and the searchsorted / partial-group code is deleted.

Example. DSV4 debug model (ratios 4 and 128, so alignment 128), a 300-token document followed by a 37-token one:

before: segments [300][37]; group 2 of doc A holds tokens 256..299 only and
        its partial tail is dropped; doc B forms no 128-entry
after:  segments [384][128]; doc A = 300 real + 84 pad, doc B = 37 real + 91 pad;
        compressed groups regroup the row, and the overlap is cut where positions == 0

Real tokens never see the padded tail. The causal masks only reveal a compressed entry once its last token, here a padding token, has been reached.

Must fix

  1. Numerics proof is missing (description). For DSV4 this is a computation and data change: the token stream gains about 3% padding, and documents whose last group used to be dropped now get an entry made partly of padding. The description reports padding stats and CPU equivalence tests but no loss curve. Per CLAUDE.md "Validating Numerics", add a before/after loss comparison on the DSV4 debug recipe over C4. The fsdp4_ep4 integration config at 10 steps is enough to show it converges the same way.
  2. torchtitan_recipes/tests/models/deepseek_v4.py:293 -- __post_init__ mutates the loader configs and silently re-enables max_num_documents=64. Set document_alignment= explicitly in each recipe (the same pattern as num_mtp_layers) and only validate here.

Should consider

  • torchtitan/components/data/packing.py:33 -- move the checks that don't depend on context to GrainDataLoader.Config.__post_init__.
  • torchtitan/components/data/packing.py:127 -- drop the duplicated = None / or 1 defaults on the internal classes.
  • torchtitan/models/deepseek_v4/compressor.py:168 -- the overlap now cuts at position resets even when no varlen metadata exists, so the compressor and attention can disagree about document boundaries. State that contract or reject the combination.
  • torchtitan/models/deepseek_v4/compressor.py:149 -- the seqlen == 0 branch has no named caller.
  • Tests: test_alignment_rejects_unsupported_packing, test_alignment_must_divide_context_and_row and test_unaligned_packing_is_rejected only check error messages for config validation. rules/tests.md asks tests to guard an invariant that would otherwise fail silently, which these don't. Keep the token/resume test and the compressor equivalence test, which do. Also, test_packed_attention_matches_each_document_alone no longer covers a document with in-segment padding, which is now the common case. Changing one length to e.g. [300 real + 84 pad] would check that padding cannot leak into real-token outputs.
Details
  • Packer and metadata interaction (checked). create_varlen_metadata_for_document starts a new segment only at positions == 0. In-segment padding keeps counting positions, so it does not split a document, and cu_seq_q stays aligned. Row-tail padding is arange(pad_len) % max_context_length, and pad_len is a multiple of the alignment because the alignment divides both the row length and the context length. A segment padded up to the next multiple stays at or below max_context_length. Resume is deterministic because remainder_offset counts only real tokens.
  • compressed_cu_seqlens = cu_seqlens // ratio. Unused fixed slots hold num_tokens, which divides by the ratio, so they map to the same end offset as before.
  • MoE / indexer loss. In-segment padding carries padding_mask=True through the same paths as tail padding (routing_token_counts, padding_mask_T).
  • Placement. document_alignment on the shared GrainDataLoader.Config has one consumer today. That is acceptable because padding has to happen in the packer, and the summary names the CP / V4.1 follow-up. The direction rules ("padding and document boundaries are passed explicitly from the data side") agree with this.
  • A maintainer still needs to review the core data-loader change.

Not verified: the CUDA fused gather_attn path with the new offsets, and the _assert_async behavior on GPU (it is a device-side assert there, not a RuntimeError). Both need a GPU run.

Comment thread torchtitan/components/data/packing.py Resolved
Comment thread torchtitan/components/data/packing.py Resolved
@sdmyzlp
sdmyzlp force-pushed the dsv4-doc-alignment branch 2 times, most recently from b8f61bd to 7bb8405 Compare November 13, 2026 02:15
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 7s —— View job


Approve (please address the two small items first): review. Both earlier must-fix items are resolved.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. Both must-fix items from the last review are resolved, and no new correctness problems turned up.

What this PR does. The document-aware packer pads every emitted segment up to a multiple of document_alignment. Padded tokens get labels=IGNORE, padding_mask=True, and positions that keep counting. DeepSeek-V4 sets the alignment to the lcm of its compression ratios, so the compressor can regroup the whole row as [L/R, R] and drop the per-document searchsorted remap.

Example. Debug model (ratios 4 and 128, alignment 128), documents of 133, 7 and 116 tokens:

before: segments [133][7][116]; doc A's last group (tokens 128..132) is dropped,
        docs B and C form no 128-entry
after:  segments [256][128][128]; each tail is padding; cu_seq_q = [0, 256, 384, 512]
        and compressed_cu_seqlens = cu_seqlens // 128

Resolved since last review

  • Numerics proof: the description now has a 10-step seed-42 deterministic run (8.032 -> 6.103 on main, 8.033 -> 6.152 here, with row boundaries that differ). It also shows that losses are bit-identical when no padding is inserted. That is enough to explain the change.
  • Recipe mutation: every recipe now passes document_alignment=model_config.document_alignment, and _DeepSeekV4TrainerConfig.__post_init__ only validates.
  • The duplicated = None / or 1 defaults are gone. The internal classes require the argument, and the single call site normalizes it.
  • The compressor contract is now stated in the positions docstring.
  • The seqlen == 0 branch is removed.
  • The in-segment-padding case is covered by test_in_segment_padding_is_invisible_to_real_tokens.

Must fix

  1. torchtitan/components/data/loader.py:78 -- __post_init__ sits in the middle of the field list. Move it after the last field (inline comment). The other context-free checks can move there too.
  2. Tests (still open, and grown): test_alignment_rejects_unsupported_packing, test_alignment_must_divide_context_and_row, test_alignment_must_be_positive (new), test_unaligned_packing_is_rejected and test_unaligned_documents_are_rejected (new) only check that a ValueError/RuntimeError message fires. Per rules/tests.md, delete them. The invariants are already guarded by test_aligned_packing_preserves_tokens_and_checkpoint, test_aligned_documents_match_per_document_compression and test_in_segment_padding_is_invisible_to_real_tokens.
Details
  • Packer bounds (checked at HEAD). num_tokens is always a multiple of the alignment, so available_tokens is too. A padded segment then never goes past the row or past max_context_length, since the alignment divides both. Row-tail padding, arange(pad_len) % max_context_length, starts new segments only at aligned offsets. _remainder_offset counts only real tokens, so resume stays deterministic.
  • Metadata. create_varlen_metadata_for_document classifies a segment as real or padding by its position-0 token. In-segment padding keeps counting positions and never opens a new segment, so cu_seq_q stays aligned, and the new _assert_async holds for loader-produced batches.
  • Minor redundancy (no action needed). DeepSeekV4Model.Config.__post_init__ and the packer both check max_context_length % alignment. The model-side check runs at config time and is cheap.
  • A maintainer still needs to review the core data-loader change (components/data/).

Not verified: the CUDA fused gather_attn path with cu_seqlens // ratio offsets, and the _assert_async device-side failure mode on GPU.

Comment thread torchtitan/components/data/loader.py Resolved
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 0s —— View job


Approve: review. Both items from the last review are fixed, and no new issues came up.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- both items from the last review are fixed at HEAD (2d25d55), and nothing new came up in a full re-read.

What this PR does. The document-aware concat-then-split packer gets an opt-in document_alignment and pads each emitted segment up to a multiple of it. Padded tokens get labels=IGNORE, padding_mask=True, and positions that keep counting. DeepSeek-V4 sets the alignment to the lcm of its compression ratios. Every segment then ends on a group boundary, so the compressor groups the whole row as [L/R, R], and the per-document searchsorted remap is deleted.

Example. Debug model (ratios 0/0/4/128, so alignment 128), documents of 133, 7 and 116 tokens:

before: segments [133][7][116]; doc A's tail group (128..132) forms no entry,
        docs B and C form no 128-entry; compressor gathers per-document groups
after:  segments [256][128][128]; padded tails are masked; cu_seq_q = [0, 256, 384, 512],
        compressed_cu_seqlens = cu_seqlens // 128; compressor is a plain unflatten

Resolved since last review

  • GrainDataLoader.Config.__post_init__ now comes after the last field. It also holds every check that doesn't depend on context: positive, requires max_num_documents, requires ConcatThenSplitPackingConfig. packing.py keeps only the divisibility check, and the redundant max_num_documents check in _DeepSeekV4TrainerConfig is gone.
  • The tests that only checked error messages are deleted. Three tests that guard invariants remain: token preservation plus resume, regrouped vs per-document compression, and padded tokens not affecting real ones.
Details
  • Packer bounds (rechecked). num_tokens stays a multiple of the alignment, so available_tokens is one too. A padded segment therefore never runs past the row, and since the alignment divides max_context_length, it never runs past that either. Row-tail padding (arange(pad_len) % max_context_length) starts new segments only at aligned offsets. _remainder_offset counts only real tokens, so resume is deterministic.
  • Remaining cu_seqlens consumers. SWA/HCA (attention.py:212-226), Indexer.select and compressed_gather_indices still take cu_seq_q. With aligned offsets, cu // ratio gives the same per-document counts as the old cumsum(diff // ratio). The aligned cu values in the existing indexer-loss tests ([0, 4, 4, 12], [0, 4, 12]) give the same result under both formulas.
  • torch._assert_async in build_attention_metadata. It follows the existing pattern in models/common/rope.py and adds no host sync.
  • document_alignment property. max(1, compress_ratio) covers the 0 ratios the flavors use for uncompressed layers, and MTP layers are included in the lcm.
  • A maintainer still needs to review the core data-loader change (torchtitan/components/data/).

Not verified: the CUDA fused gather_attn / lightning_indexer path with the new offsets, and how _assert_async fails on GPU (a device-side assert there, not a RuntimeError).

@sdmyzlp

sdmyzlp commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

Not verified: the CUDA fused gather_attn / lightning_indexer path with the new offsets, and how _assert_async fails on GPU (a device-side assert there, not a RuntimeError).

Working on it, will post result later.

Comment thread torchtitan/components/data/loader.py Outdated
class Config(BaseDataLoader.Config):
dataset: DatasetConfig
document_alignment: int | None = None
"""Pad document segments to this multiple; requires document-aware packing."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is it similar to what per_sample_pad_multiple does for RL collator? https://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/trainer/batcher.py#L258-L261
If so, can we unify things, at least the name, but maybe also utils / classes?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

As for

DeepSeek-V4 / V4.1 has sequence-level pooling which makes varlen and context parallel hard to implement. Add mandatory padding to alleviate this pain and simplify existing code.

I'll let @liangel-02 @drisspg comment.

@sdmyzlp sdmyzlp Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

DeepSeek-V4 / V4.1 has sequence-level pooling which makes varlen and context parallel hard to implement. Add mandatory padding to alleviate this pain and simplify existing code.

Adding our debugging experience for @liangel-02 @drisspg:

  1. Misaligned blocks alone are manageable: with ragged documents, the torch-native compressor has to gather along cu_seqlens (as it already does today). A fused kernel can absorb that cost, so this is not the blocker.
  2. Context parallel is. A compression block can be split across CP shards while the compressor needs the full block, so shards must exchange and reorder partial blocks. That adds fragmented and intricate communication and reordering traffic (as well as implementation complexity), and ranks end up with different numbers of blocks, which in varlen means more dynamic shapes.

@sdmyzlp sdmyzlp Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Is it similar to what per_sample_pad_multiple does for RL collator? https://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/trainer/batcher.py#L258-L261
If so, can we unify things, at least the name, but maybe also utils / classes?

@tianyu-l Yes, same mechanism. At the new head I unified the name (per_sample_pad_multiple everywhere) and the padding utility (append_padded_segment, shared by both packers); packing algorithms and the config/class layer stay separate for now.

Does that cover what you had in mind?

@sdmyzlp
sdmyzlp requested a review from tianyu-l November 13, 2026 16:50
@sdmyzlp

sdmyzlp commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

@tianyu-l @liangel-02 @drisspg Hi, could you please help review this PR?

@tianyu-l

Copy link
Copy Markdown
Contributor

@sdmyzlp structure-wise it looks OK. I think the non-CP part refactor might be worth merging anyways.

The CP part sounds reasonable, but I would like @drisspg and @liangel-02 to take a look. Let me ping them offline.

@liangel-02

Copy link
Copy Markdown
Contributor

@sdmyzlp thanks for submitting this! could you split this up into 2 separate prs, one for the non-CP refactoring and one for the CP padding changes?

i'll keep this in mind when we start implementing CP and will do more performance investigations to determine what the best solution is

@sdmyzlp

sdmyzlp commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator Author

@sdmyzlp thanks for submitting this! could you split this up into 2 separate prs, one for the non-CP refactoring and one for the CP padding changes?

@liangel-02
Thanks! Small clarification: this PR contains no CP code. The padding is what enables the compressor simplification — without aligned segments the compressor has to keep the per-document cu_seqlens gather, so "refactor" and "padding" can't be split along the CP/non-CP line.

A split by layer is possible:

  1. data + RL: shared append_padded_segment + per_sample_pad_multiple on the loader; no DSV4 change, no recipe enables it, behavior unchanged.
  2. DSV4: enable alignment in the recipes, derive the LCM, assert it in metadata, drop the gather path in the compressor.

(2) depends on (1), but (1) is only exercised by (2): without DSV4 the data-padding change has no consumer. So the two really are one change — unless you'd rather I land just the shared helper + RL reuse first, which does stand alone.

Comment on lines +287 to +290
if (loader.per_sample_pad_multiple or 1) != (alignment or 1):
raise ValueError(
f"DeepSeek V4 loaders must set per_sample_pad_multiple={alignment}."
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Do we need this even when CP is off?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

No, the current simplification is more about consistency, i.e. the same aligned layout whether CP is on or off, so one invariant and one metadata path cover both instead of maintaining two layouts.

If the compressor part is the concern, I can split it out and submit only the padding (no consumer yet), deferring the simplification. @tianyu-l

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think we shouldn't introduce unnecessary padding. We could either

  1. only keep the padding capability part (your proposal), or
  2. keep the property, but only configure dataloader in a recipe where CP is used (currently none)

I think it's less confusing if we do 1.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Got it, I will drop the DSv4 compressor modification and keep only the data/rl part.

tianyu-l pushed a commit that referenced this pull request Nov 19, 2026
## Summary (human-written)
1. Every `compress_ratio`-derived quantity — compressed pool offsets,
compressor group indices, and the heavily compressed variant's causal
mask — is now computed once per variant in `build_attention_metadata`,
instead of being rebuilt inside every layer on every forward.
2. The layer and indexer interfaces take `attention_metadata` instead of
`cu_seqlens`, so an overriding `InnerAttention` can pair its own
`build_attention_metadata` with its consumers and have the produced
metadata flow to them automatically.

## Why

All sparse-attention layers share one metadata entry per variant, yet
each layer still rebuilt everything derived from `compress_ratio`: the
compressed pool offsets, the compressor's group indices, and the heavily
compressed variant's causal mask.

```text
before: each layer, each forward
    cu_seqlens_k = compressed_cu_seqlens(cu_seq_q, ratio)
    group_start / group_first = searchsorted + arange
    cmp_topk = where(cmp_s < (pos_t + 1) // ratio, ...)   # HCA only

after: once per variant in build_attention_metadata
    metadata.cu_seq_compressed / group_start / group_first / compressed_causal_indices
```

This is independent of the document-padding work (#6059); the geometry
uses the current unaligned layout.

## What changed

- `attention.py`: `DeepSeekV4CompressedSparseAttentionMetadata` extends
`VarlenAttentionMetadata` with `cu_seq_compressed`, `group_start`,
`group_first` and `compressed_causal_indices`. The sliding-window
builder creates the empty-compressed-pool default; HCA and CSA override
it with their geometry, and HCA adds the causal mask. `positions` is
required on `DeepSeekV4Attention.forward`.
- `compressor.py`: `Compressor`, `Indexer.forward`, `Indexer.select` and
`SparseIndexerLoss` take the metadata and unpack it internally;
positions and metadata are required, and the per-layer
`searchsorted`/`arange` work is gone.
- `model.py`: `forward` requires attention metadata. The flavors derive
attention, inner attention, compressors and indexer from one
`compress_ratio`, so the shared metadata and its consumers agree by
construction.

## Numerics / performance

Cleanup, no intended numerics change: the packed-vs-per-document tests
and the dense-masked GPU test still match. No step-time or memory
measurement is claimed.

## Testing

`pytest -q tests/unit_tests/cpu/models/deepseek_v4
tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py
tests/unit_tests/gpu/models/deepseek_v4/test_deepseek_v4_attention.py` —
27 passed, 3 CUDA cases skipped.

`pytest -q tests/unit_tests/cpu/recipes/test_deepseek_v4_dist_muon.py
tests/unit_tests/cpu/models/test_state_dict_adapter.py::DeepSeekV4StateDictAdapterTest`
— 10 passed.
@sdmyzlp sdmyzlp changed the title [dsv4] Require document-aligned packing and simplify compression [data] Add opt-in per-sample padding for packed segments Nov 19, 2026
@sdmyzlp

sdmyzlp commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Done in 4388790: rebased onto current main and took option 1. The PR now contains only the data + RL padding capability (7 files: append_padded_segment, the opt-in per_sample_pad_multiple loader field, the packer change, and the RL batcher reuse). The DeepSeek-V4 alignment/compressor commit and the recipe wiring are dropped; no recipe enables the field, so no padding is introduced today.

Tests: pytest -q tests/unit_tests/cpu/components/data tests/rl/unit_tests/cpu/test_batcher.py — 249 passed.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude do a final check

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 48s —— View job


Approve: review. No correctness issues at HEAD; one optional item (None and 1 both mean "no padding").

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- the PR is now only the data + RL padding capability that tianyu-l agreed to. I re-read all 7 files at HEAD (4388790) and found no correctness problems.

What this PR does. It adds a new helper, append_padded_segment (components/data/padding.py), which appends one segment and pads it to a multiple. Padded tokens get the fill values, positions that keep counting, and padding_mask=True. The RL batcher's old inline padding is replaced by this helper and round_up. The document-aware concat-then-split packer also uses it, behind a new opt-in GrainDataLoader.Config.per_sample_pad_multiple. No recipe enables the loader field, and the DeepSeek-V4 changes are gone.

Example. Grain packer, max_context_length=8, row of 16, multiple 4, documents of 4, 19 and 6 tokens (3, 18 and 5 after the label shift):

before: segments [3][8][8] | [2][5] + 9 tail pad
after:  segments [4][8][4] | [8][4][4]   (3 real + 1 pad, 8, 4 real, then 2 real + 2 pad, 5 real + 3 pad)
        every positions==0 index is a multiple of 4; padded labels = IGNORE_INDEX

Should consider

  • torchtitan/components/data/loader.py:76 -- both None and 1 mean "no padding". Using int = 1 would remove the three or 1 normalizations (inline).
Details
  • RL unchanged. For each sample, the fields, positions = arange(padded_len), the padding mask (arange >= unpadded_len, now ones with the real prefix cleared) and sample_lens are the same as before. The pad arrays now use the sample's dtype instead of _DTYPES, but np.concatenate(..., dtype=_DTYPES[key]) still casts the result. Every TrainingSample field is an np.ndarray, so values.dtype is always defined. The new per_sample_pad_multiple <= 0 error replaces the old "0 means off" behavior. The only in-repo caller, alphabet_sort.py:358, passes block_size.
  • Grain packer bounds. The multiple divides both the row length and max_context_length, so num_tokens stays a multiple and available_tokens does too. A padded segment therefore never goes past the row or past the context limit. The document count still uses len(parts["positions"]), which gets one entry per segment even when padding is added. _remainder_offset counts only real tokens, so resume is deterministic, and the new test checks this.
  • MTP and loss counts. In-segment padding sets padding_mask=True, and roll_mtp_sequence refuses to cross padding, so get_mtp_token_counts leaves padded tokens out of both the loss and the routing counts.
  • Config validation. The checks that need no context (positive, max_num_documents set, ConcatThenSplitPackingConfig) run in __post_init__. Only the divisibility check, which needs the context and microbatch lengths, stays in packing.py.
  • No consumer yet. The loader field has no in-repo user. tianyu-l chose this explicitly ("only keep the padding capability part"), so I have not flagged it.
  • A maintainer still needs to review the core data-loader change (torchtitan/components/data/).

Comment thread torchtitan/components/data/loader.py Outdated
@dataclass(kw_only=True, slots=True)
class Config(BaseDataLoader.Config):
dataset: DatasetConfig
per_sample_pad_multiple: int | None = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Optional: "no padding" can be written two ways here, None and 1. Because of that, or 1 shows up three times (packing.py:56, batcher.py:343, and here as is None or == 1). This is not a size-like optional component, so X | None doesn't buy anything. A plain per_sample_pad_multiple: int = 1 on both GrainDataLoader.Config and Batcher.Config (and DatasetBuildContext), validated as >= 1, would remove all three normalizations and the None entries in the tests. alphabet_sort.py:358 already passes a concrete block_size, so no recipe depends on None.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@sdmyzlp do you think we should do this? It sounds cleaner to me.

None and 1 both meant no padding, which forced the "or 1" normalizations in
the loader, the packer and the RL batcher. Use int = 1 everywhere and reject
values below 1; update the tests to use 1 instead of None.
@sdmyzlp

sdmyzlp commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Done in a90cc4f: per_sample_pad_multiple is now int = 1 on GrainDataLoader.Config, DatasetBuildContext and Batcher.Config; 1 means no padding and values below 1 are rejected. The three or 1 normalizations and the None test cases are gone. Tests: 249 passed.

@tianyu-l
tianyu-l merged commit cc02098 into pytorch:main Nov 19, 2026
25 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Nov 19, 2026
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…er override; agent self-review; rl/transport (#6407)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why

Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it
approved,
30 then got a formal "request changes" from a maintainer, and about 20
more got
substantive inline asks. In nearly all of them the bot either saw the
problem
and approved anyway, or never asked the questions maintainers ask most
("does
the repo already do this?", "who should own this?"). The opposite
failure, the
bot blocking something a maintainer was fine with, is rare: in the PRs
we
sampled, 2 of its 81 must-fix items were wrong and about a third were
minor
(the empty human-written summary was the biggest source).

**Example** (#6112, controller sizes the rollout worker pool):

```
before: bot approved 10 times; tianyu-l then blocked: "the controller reads
        rollouter.rollouts_per_worker to compute a count it hands back to the
        Rollouter -- violates encapsulation"
after:  same commit, new skill -> Request changes, must-fix #1:
        "controller.py:589 -- wrong owner for the worker count ..."
```

There was also no way for a code owner to overrule the bot except
dismissing
its review in the GitHub UI, and a later `@claude review again` would
block
again.

## What changed

**Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`):
- Verdict rules: Approve only when every remaining item is an edit the
bot
could write itself. Anything the author still owes (a design change, an
unexplained golden change, evidence the PR rests on) is Request changes;
anything only a maintainer can decide is Needs discussion. A hedge like
"a
  maintainer should decide" can't come with Approve.
- Always must-fix: a violated written rule, a silent wrong result, a
second
  definition of an existing concept, a gate finding.
- Design gate: new questions for the existing counterpart, in-repo
ownership,
and the design behind a bug; "ban only what doesn't work on main"; read
the
numbers behind a claim. The overlapping-PR search is mandatory and
reported.
- Re-review covers every commit since the last full review, including
code
taken from the bot's own suggestions. A scoped question gets a
`COMMENT`, not
  a whole-PR verdict.
- The bot fact-checks its own proposed fixes, and cites a source for
claims
  about external tools or marks them unverified (never must-fix).
- An empty "Summary (human-written)" is a one-line "Before merge" note
that
  never affects the verdict.
- Checklist: config ownership direction, general shared wrappers, dead
code the
PR creates, model variants as flavors, a mechanical pass over every new
or
  changed function.

**Code owner override** (`SKILL.md`, `claude-code.yml`,
`CONTRIBUTING.md`): a
code owner comments `@claude override` (optionally `@claude override
2,3:
<reason>`); the bot approves if nothing else is open and doesn't
re-raise the
overridden items. A code owner's GitHub approval or "LGTM" is not an
override,
so a teammate can approve without the bot dropping its findings.
Dismissing the
bot's review still unblocks the PR, but isn't an override: the bot can't
tell
who dismissed it.

**Agent self-review** (`CLAUDE.md`, `pr-description`): an agent
preparing a PR
runs `pr-review` in branch mode first and records unaddressed items in
an
optional "Self-review" section. PRs written without an agent are
unaffected; a
missing section is never a finding.

Where each new rule comes from (maintainer asks the bot missed):

| Change | PRs |
| --- | --- |
| No Approve with open design/evidence items or a "maintainer should
decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 |
| Author waiver can't clear a must-fix | #6201, #6202, #6203 |
| Existing counterpart; one source of truth | #5228, #6169, #5881,
#5823, #5824, #6059, #5812 |
| Responsibility owner; config ownership direction | #6112, #6332,
#5802, #5803, #6325 |
| Fix the design behind the bug; a TODO doesn't justify a workaround |
#5572, #5689, #5657 |
| Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819,
#5543 |
| Re-review covers all new commits; scoped asks don't approve | #5824,
#5842 |
| Mandatory overlap search | #5885, #6248 |
| Ban only what doesn't work on main | #5543 |
| Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868
|

**Rules**: `design.md` gets the one-general-wrapper rule (moved from
`models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the
consumer owning its values; `config.md` gets ownership direction and "a
Config
doesn't read runtime state"; `direction.md` calls all-to-all the MoE
reference
implementation, so a new vendor-specific dispatch path (e.g. #6242)
needs a
reason the existing backends can't serve.

**Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/`
-> d4l3k.

**Mechanical, skim**: `torchtitan/rl/transport/` holds data movement
between RL
actors.
- `rl/model_state_dict_transport.py` ->
`rl/transport/model_state_dict.py`
- `rl/MODEL_STATE_DICT_TRANSPORT.md` ->
`rl/transport/MODEL_STATE_DICT_TRANSPORT.md`
- `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py`
- tests:
`tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py`
->
`tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py`
- imports, READMEs and `scripts/install_rl_env.sh` updated; no code
changes.

## User-facing changes

| Before | After |
| --- | --- |
| Overrule the bot: dismiss its review in the UI, and it blocks again on
the next run | `@claude override [items]: <reason>`; the bot approves
and doesn't re-raise them |
| Empty human-written summary: bot must-fix | One "Before merge" line,
no effect on the verdict |
| `from torchtitan.rl.model_state_dict_transport import ...` | `from
torchtitan.rl.transport.model_state_dict import ...` |
| `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from
torchtitan.rl.transport.rdma_microbatch import ...` |

## Testing

Backtest: the new skill run locally (nothing posted) on each PR at the
commit
and thread state the bot originally saw.

| PR | Bot then | New skill | What the maintainer asked |
| --- | --- | --- | --- |
| #6112 | Approve | Request changes | worker-count ownership (caught) |
| #5837 | Approve | Request changes | apply to `dp_shard` too (caught) |
| #5572 | Approve | Request changes | delete the injection design
(caught) |
| #6201 | Approve after author waived pins | Request changes, waiver
ignored | pins broke GPU tests after merge (caught) |
| #6007 | Approve | Request changes | fold K3.1 into K3 (caught) |
| #5543 | Request changes: "ban it" | Request changes: keep main's path
| don't break gpt-oss + DeepEP (fixed) |
| #6144, #5905 (controls) | Approve | Approve | -- |
| #6137 (control) | Approve | Needs discussion | -- (merge gate on an
upstream API) |

Code owner override, simulated on #6201: override by a code owner lifts
the
named item; `@claude override` from the author changes nothing; a code
owner's
"LGTM" approval followed by "review again" keeps Request changes.

Transport move: 83 RL CPU unit tests pass locally
(`transport/test_model_state_dict.py`, `test_trainer.py`,
`test_engine_loop.py`). `transport/test_rdma_microbatch.py`,
`test_generator.py` and
`test_batcher_actor.py` fail to collect in my env on `origin/main` too
(stale
attention-gym / Monarch), so CI is the check for those.

## Known issues / follow-ups
- Open PRs that edit the moved files rebase cleanly (git follows the
renames),
but new imports of the old module paths will break: #6309 (adds a delta
transport that should live in `rl/transport/`), #6237, #6176, #6177,
#5862,
  and drafts #6127, #6393, #6163, #5764.
- The Actions bot can't read dependency source (e.g. SGLang); follow-up
for the
  workflow.

## Self-review
pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch
mode diffs
against `origin/main` and skips description findings before a
description
exists; the "Config doesn't read runtime state" rule no longer
contradicts
hardware validation; dismissal dropped as an override form (the bot
can't tell
who dismissed); `test_rdma_microbatch.py` added to the transport area.
Not
addressed:
- One concern per PR -- the five changes ship together at the
maintainer's
  request.
- Open PRs touching the moved files -- listed above; the maintainer will
  coordinate.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants