Repository navigation
[data] ConcatThenSplit: wrap processor positions longer than the context - #5664
Conversation
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
|
@claude review |
|
Claude finished @tianyu-l's task in 2m 12s —— View job Approve: the fix is correct and in the right place, so the uncapped concat-then-split path now wraps processor positions the same way FirstFit and the Summary
The full review is posted as a formal PR review with inline comments. |
| token_indices = np.arange(len(text_sequence.input_ids), dtype=np.int64) | ||
| if text_sequence.positions is None: | ||
| positions = token_indices % max_context_length | ||
| else: | ||
| document_starts = np.maximum.accumulate( | ||
| np.where(np.asarray(text_sequence.positions) == 0, token_indices, 0) | ||
| ) | ||
| positions = (token_indices - document_starts) % max_context_length |
There was a problem hiding this comment.
Optional: the None branch is the same formula with every document start at 0, so a single expression covers both cases and makes it clear that missing positions mean one document:
| token_indices = np.arange(len(text_sequence.input_ids), dtype=np.int64) | |
| if text_sequence.positions is None: | |
| positions = token_indices % max_context_length | |
| else: | |
| document_starts = np.maximum.accumulate( | |
| np.where(np.asarray(text_sequence.positions) == 0, token_indices, 0) | |
| ) | |
| positions = (token_indices - document_starts) % max_context_length | |
| token_indices = np.arange(len(text_sequence.input_ids), dtype=np.int64) | |
| document_starts = 0 | |
| if text_sequence.positions is not None: | |
| document_starts = np.maximum.accumulate( | |
| np.where(np.asarray(text_sequence.positions) == 0, token_indices, 0) | |
| ) | |
| positions = (token_indices - document_starts) % max_context_length |
| def test_concat_then_split_wraps_positioned_long_documents(): | ||
| """Without max_num_documents, processor positions longer than the context | ||
| restart every max_context_length tokens, the same as missing positions.""" | ||
|
|
||
| def pack(row): | ||
| documents = SingleDatasetConfig( | ||
| source=RowsSourceConfig(rows=(row,)), | ||
| processor=RowToTokens.Config(), | ||
| ) | ||
| context = replace(CONTEXT, max_context_length=4, num_tokens_per_microbatch=8) | ||
| return list( | ||
| ConcatThenSplitPackingConfig(dataset=documents).build( | ||
| context=context, | ||
| dataset_iteration_policy=dataset_iteration_policy( | ||
| shuffle=False, repeat=False | ||
| ), | ||
| ) | ||
| ) | ||
|
|
||
| positioned = pack({"tokens": list(range(17)), "positions": list(range(16))}) | ||
| unpositioned = pack({"tokens": list(range(17))}) | ||
|
|
||
| assert len(positioned) == len(unpositioned) == 2 | ||
| for row, expected in zip(positioned, unpositioned, strict=True): | ||
| np.testing.assert_array_equal(row.positions, [0, 1, 2, 3, 0, 1, 2, 3]) | ||
| np.testing.assert_array_equal(row.positions, expected.positions) | ||
| np.testing.assert_array_equal(row.input_ids, expected.input_ids) |
There was a problem hiding this comment.
Consider folding this into test_packing_splits_positioned_long_documents (line 1127) instead of adding a 29-line near-copy. That test already checks the real invariant (positions.max() < max_context_length) for both packers. It just never runs with max_num_documents=None, which is exactly the path this PR fixes. Suggested change:
- add
@pytest.mark.parametrize("max_num_documents", [2, None])and pass it intoreplace(CONTEXT, ...) - use
tokens=list(range(17)),positions=list(range(16)), so all four combinations produce 2 full rows (the uncapped concat-then-split path drops the partial last row, which is why 14 tokens doesn't work there) - only check the doc-count assert
if context.max_num_documents is not None, and change the final check tolist(range(16))
This runs the fixed path through both packers at no extra cost and adds no new test function. Comparing against the unpositioned run is redundant once the bound check passes.
There was a problem hiding this comment.
Verdict: Approve -- the bug is real on main, and the fix is at the right layer: the shared packing-input conversion. It makes the uncapped concat-then-split path do what FirstFit and the capped path already do. A maintainer still needs to review, since this touches torchtitan/components/data/.
What this PR does. In ConcatThenSplitPackingConfig with max_num_documents=None, positions that a processor supplies were passed straight into Grain's concat-then-split. _packing_output_to_text_sequence only rebases at zeros, so a positioned document longer than max_context_length produced row positions up to num_tokens_per_microbatch - 1. The PR restarts positions at each zero and every max_context_length tokens after it, which is the same wrapping that missing positions already got.
Example. One document, positions 0..15, max_context_length=4, 8-token rows:
main: row0 positions [0..7] -> rope_cache[4] out of bounds
this PR: row0 positions [0,1,2,3,0,1,2,3] (same as FirstFit / max_num_documents=2)
Should consider
torchtitan/components/data/packing.py:374-- the two branches can share one formula (document_starts = 0when positions areNone). Suggestion inline.tests/unit_tests/cpu/components/data/test_grain_data.py:1174-- fold the new test intotest_packing_splits_positioned_long_documentsby parametrizingmax_num_documentsover(2, None)with 16 tokens. That covers the fixed path through both packers without a new test function. Details inline.
Details
- Callers:
_text_sequence_to_packing_inputis used only by the uncapped concat-then-split path and FirstFit (packing.py:48,packing.py:263). FirstFit inputs are already split by_SplitTextSequenceDocumentsinto chunks no longer thanmax_context_lengththat start at 0, so the change is a no-op there. Output from an inner packer that feeds an outer packer is already canonical and bounded, so nesting is unaffected too. - Positions without a leading zero (e.g. a processor's continuation chunk
[100..199]): onmainthese were already rebased to the row start by_packing_output_to_text_sequence. Now they are also wrapped from the sample start. The bound holds either way. - Bound: within a row, every token's position is its distance to the most recent zero, and zeros now occur at least every
max_context_lengthtokens within a document, sopositions < max_context_length. - Numerics: in-tree
TextProcessor/ChatProcessorreturnpositions=None, so the c4 recipes and their golden losses are unchanged. Only custom processors that return positions see a difference, and onmainthose would have indexed past the RoPE cache. - No overlapping open PR found.
Not verified: I could not run the unit tests in this environment. Correctness was checked by reading the code.
|
@Sonica-B could you fix the claude suggestion |
## Why The first `@claude review` with the new skill (#5664) put four separate items on the PR: | Item | Cause | | --- | --- | | 2 empty COMMENTED reviews, each holding one inline comment | `create_inline_comment` posts every comment on its own, so GitHub wraps each one in a single-comment review | | 1 APPROVED review with the summary | `gh pr review` | | 1 tracking comment repeating the same summary | the bot also wrote the summary into its tracking comment | The reviewer has to read the same review twice, and the inline comments are detached from the verdict. **Example.** After this PR, the same run produces: ``` claude[bot] commented: Approve -- <one-line reason>. Review: <link> claude[bot] approved: <verdict, summary, example, pointers> packing.py:381 <inline comment> test_grain_data.py:1200 <inline comment> ``` ## What changed - **Skill.** `pr-review` now posts with the GitHub MCP server's pending-review tools, which ship with the pinned `claude-code-action`: 1. `create_pending_pull_request_review` 2. `add_comment_to_pending_review`, once per line-anchored finding 3. `submit_pending_pull_request_review` with the body and `APPROVE` / `REQUEST_CHANGES` / `COMMENT` If a pending review is left over from an interrupted run, the bot deletes it and retries. If the pending-review tools are unavailable, it falls back to the previous path (inline tool, then `gh pr review`) and never posts a finding through both. - **Tracking comment.** After a review it is one line: the verdict and a link to the review. - **`claude-code.yml`.** Allows only those four pending-review tools from the GitHub MCP server. Other tools in that server, such as merge, and `gh api` stay blocked. ## Testing The change only takes effect from `main`, so it can't be exercised before merging. After merge, run `@claude review` on a PR with line-level findings and check that the result is one review containing the inline comments, plus a one-line tracking comment. ## Known issues - Not verified: the pending-review tools look up "the caller's pending review" through GraphQL `viewer`. That should resolve to `claude[bot]` with the app's installation token, but this hasn't been checked. If it fails, the bot falls back to the previous ungrouped posting. - Not verified: if the lookup fails after a pending review was created, that pending review stays behind. It is invisible to others, and later runs fall back the same way.
Without max_num_documents, ConcatThenSplitPackingConfig passed processor-supplied TextSequence.positions through unchanged, so a positioned document longer than max_context_length produced 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. Restart positions at each document start and every max_context_length tokens after it, the same wrapping missing positions already get.
Missing positions are the same formula with every document starting at 0, so one expression now covers both cases. Drop test_concat_then_split_wraps_positioned_long_documents and instead run test_packing_splits_positioned_long_documents with max_num_documents=2 and max_num_documents=None. The document has 16 positioned tokens so every packer and cap combination yields two full rows; the document-count check applies only when a cap is set.
0704615 to
30698e8
Compare
|
Both suggestions are applied in 30698e8, and the tests pass. |
|
not introduced in this PR; fixed in another PR |
In
torchtitan/components/data/packing.py,ConcatThenSplitPackingConfigwithoutmax_num_documents(the default) passes processor-suppliedTextSequence.positionsthrough unchanged._text_sequence_to_packing_inputonly fills in positions when they areNone(arange % max_context_length), and_packing_output_to_text_sequencerebases them per document without wrapping. So a positioned document longer thanmax_context_lengthcomes out with row positions up tonum_tokens_per_microbatch - 1. Those index past the RoPE cache, which hasmax_context_lengthrows. FirstFit and the document-capped concat-then-split path already split such documents (since #4156), andtest_packing_splits_positioned_long_documentscheckspositions.max() < max_context_lengthfor them, but only withmax_num_documents=2.With one 14-token positioned document,
max_context_length=4and 8-token rows, the uncapped packer on main gives: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.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_lengthtokens 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-treeTextProcessorandChatProcessorleave positionsNone, 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_documentsnow also runs withmax_num_documents=None(17 tokens, 16 positions, so every combination packs two full rows) and checks that positions stay belowmax_context_lengthfor 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 oftests/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 runsgenerate.py --check. That was on Windows with Python 3.11 and torch 2.16.0.dev20261024+cpu.pre-commit runon 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.