Skip to content

[data] ConcatThenSplit: wrap processor positions longer than the context - #5664

Merged
tianyu-l merged 2 commits into
pytorch:mainfrom
Sonica-B:fix/cts-packing-long-positioned-docs
Oct 30, 2026
Merged

tianyu-l merged 2 commits into
pytorch:mainfrom
Sonica-B:fix/cts-packing-long-positioned-docs

Conversation

@Sonica-B

@Sonica-B Sonica-B commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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.

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"]
Loading

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.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 29, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 29, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

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

@pytorch-bot

pytorch-bot Bot commented Oct 29, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rl
  • ciflow/fake-pg

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.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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 max_num_documents path already do. A maintainer still needs to review, since this touches torchtitan/components/data/.

Summary
  • Bug: on main, when max_num_documents=None, a custom processor's positions pass through unchanged. A positioned document longer than max_context_length then produces row positions up to num_tokens_per_microbatch - 1, which index past the RoPE cache.
  • Fix: positions now restart at each zero and every max_context_length tokens after it. That bounds row positions below max_context_length.
  • Unaffected: FirstFit, nested packers, and the in-tree processors that leave positions as None. So the c4 recipes and their golden losses don't change.
  • Two optional suggestions (posted inline):
    • Merge the two branches in _text_sequence_to_packing_input into one formula.
    • Fold the new test into test_packing_splits_positioned_long_documents by parametrizing max_num_documents over (2, None) with 16 tokens.
  • Not run: I couldn't run the unit tests here; I checked the code by reading it.

The full review is posted as a formal PR review with inline comments.

Comment thread torchtitan/components/data/packing.py Outdated
Comment on lines +374 to +381
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

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

Suggested change
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

Comment on lines +1174 to +1200
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)

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.

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 into replace(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 to list(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.

@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 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 = 0 when positions are None). Suggestion inline.
  • tests/unit_tests/cpu/components/data/test_grain_data.py:1174 -- fold the new test into test_packing_splits_positioned_long_documents by parametrizing max_num_documents over (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_input is used only by the uncapped concat-then-split path and FirstFit (packing.py:48, packing.py:263). FirstFit inputs are already split by _SplitTextSequenceDocuments into chunks no longer than max_context_length that 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]): on main these 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_length tokens within a document, so positions < max_context_length.
  • Numerics: in-tree TextProcessor / ChatProcessor return positions=None, so the c4 recipes and their golden losses are unchanged. Only custom processors that return positions see a difference, and on main those 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.

@tianyu-l

Copy link
Copy Markdown
Contributor

@Sonica-B could you fix the claude suggestion

tianyu-l added a commit that referenced this pull request Oct 29, 2026
## 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.
@Sonica-B
Sonica-B force-pushed the fix/cts-packing-long-positioned-docs branch from 0704615 to 30698e8 Compare October 29, 2026 22:06
@Sonica-B

Copy link
Copy Markdown
Contributor Author

Both suggestions are applied in 30698e8, and the tests pass.

@tianyu-l

tianyu-l commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

@Sonica-B seems we need a rebase

not introduced in this PR; fixed in another PR

@tianyu-l
tianyu-l merged commit 8b136eb into pytorch:main Oct 30, 2026
21 of 25 checks passed
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

None yet

Development

Successfully merging this pull request may close these issues.

2 participants