Skip to content

enable cudagraph for varlen pretrain - #4156

Merged
shuhuayu merged 1 commit into
mainfrom
varlen_pretrain_cudagraph
Sep 9, 2026
Merged

shuhuayu merged 1 commit into
mainfrom
varlen_pretrain_cudagraph

Conversation

@liangel-02

@liangel-02 liangel-02 commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor
  1. cuseqlens varies depending on number of docs --> pin to max_docs + 1
  2. max_q/max_k also vary --> pin to seq_len
  3. we call nonzero and the max().item() sync --> use cumsum instead
Screenshot 2026-08-14 at 6 21 08 PM

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 14, 2026
@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch 2 times, most recently from a4121fb to 16c022f Compare August 14, 2026 22:44
@liangel-02
liangel-02 marked this pull request as ready for review August 14, 2026 22:45
@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch from 16c022f to 2ee380c Compare August 14, 2026 23:14
Comment thread torchtitan/models/common/attention.py Resolved
@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch from 2ee380c to 98db6d3 Compare August 15, 2026 19:45
@liangel-02 liangel-02 changed the title [WIP] enable cudagraph for varlen pretrain enable cudagraph for varlen pretrain Aug 15, 2026
Comment thread torchtitan/models/common/attention.py Resolved
Comment thread torchtitan/models/common/attention.py Resolved
Comment thread torchtitan/models/common/attention.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/models/common/attention.py Resolved
@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch from 98db6d3 to 408d667 Compare August 27, 2026 16:48
@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch 2 times, most recently from 04027dd to 52f66ca Compare August 27, 2026 17:07
@liangel-02
liangel-02 requested a review from tianyu-l August 27, 2026 17:07
@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch 3 times, most recently from 04c222e to e46fd4e Compare August 27, 2026 19:54
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/components/data/collators.py Resolved
Comment thread torchtitan/trainer.py Resolved
@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch from e46fd4e to 7804d1d Compare August 28, 2026 14:58
@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch from 7804d1d to ab86951 Compare August 28, 2026 17:33
@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch 2 times, most recently from 2274d97 to 9d25283 Compare August 28, 2026 18:11
@liangel-02
liangel-02 requested a review from tianyu-l August 28, 2026 18:12
@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch from 9d25283 to 25ba60f Compare August 28, 2026 20:59
Comment thread torchtitan/experiments/rl/types.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved
Comment thread torchtitan/trainer.py Resolved

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.

looks complicated

@tianyu-l

Copy link
Copy Markdown
Contributor

@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

  • Documents longer than max_context_length is properly treated, either filtered or truncated. What is being done today and what's your recommendation?
  • If a single row has max_num_documents documents to pack and they can all fit, we should pad the rest. What is the current behavior? We should make sure we don't "lose" any documents (unless it's too long, see above point). Also, does it work nicely with changes in torchtitan/models/common/attention.py? I think we should output padding mask from dataloader and RL batcher, so that attention metadata building (and later MoE router logic regarding load balancing) can be made clear.

@claude

claude Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

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


Review: enable cudagraph for varlen pretrain

I read through packing.py, attention.py, decoder.py, the trainer wiring, and the RL batcher. Answering your three questions directly, then the packing.py simplification.


1. Documents longer than max_context_length

The two packing strategies do different, inconsistent things, and there's a latent correctness risk in the varlen path.

  • ConcatThenSplitPackingConfig (the varlen/cudagraph path): chunked, never dropped. In _DocumentAwareConcatThenSplitIterator.__next__, when the incoming TextSequence has positions is None (the pretrain TextProcessor/RowToTokens case), positions are synthesized as np.arange(len) % max_context_length (packing.py:141-144). A 15-token doc with mcl=4 becomes positions [0,1,2,3,0,1,2,3,...], so next_starts splits it into mcl-sized segments. Each chunk becomes an independent "document" that does not attend across chunk boundaries. So a long doc is neither truncated nor dropped -- it's silently split into non-attending blocks. That's the standard concat-then-split behavior, and it keeps max_q == max_context_length valid.

  • FirstFitPackingConfig: dropped. packing.py:250-252 filters len(input_ids) <= max_context_length before packing. The existing TODO at packing.py:54 already flags this divergence.

  • Correctness risk worth flagging: the "chunk into mcl segments" only happens because upstream positions are None. If a processor emits real positions (e.g. an SFT/chat processor that preserves document positions) and a single document exceeds max_context_length, then in the capped path source_positions is taken as-is (packing.py:145-146), a segment can be > max_context_length, and create_varlen_metadata_for_document pins max_q = max_context_length (attention.py:647). The varlen kernel would then get a max_q smaller than an actual sequence length -- a silent kernel-correctness bug, not just a perf issue. The sft_qwen3_8b_math config already sets max_num_documents=32, so this path is reachable. I'd recommend an explicit assert/ValueError in the capped path when any segment length exceeds max_context_length, or a documented truncation policy.

Recommendation: decide one policy (I'd pick chunk/truncate to max_context_length, never drop) and apply it uniformly to both packers, replacing the FirstFit drop-filter. At minimum, guard the "real positions with an over-long segment" case so it can't silently feed a too-small max_q to the kernel.


2. Do we lose documents when a row hits max_num_documents? + attention interaction

No documents are lost today in either path -- and I verified the mechanism:

  • ConcatThenSplit: when adding a segment would push num_documents_if_emitted > max_num_documents, the loop breaks (packing.py:167) with the segment retained in self._remainder, so it carries to the next row. Token-budget-limited segments likewise advance _remainder_offset only by what fit. The test test_packing_document_cap_preserves_all_documents confirms every real token survives. Padding fills the rest of the row (packing.py:191-198).
  • FirstFit: max_sequences_per_bin=_max_real_documents_per_row(context) caps real docs per row; overflow docs go to other bins. Nothing dropped (except the over-long filter from Q1).

The complication is padding accounting, and it stems from an inconsistency with the RL batcher:

  • The pretrain path pads with positions that reset modulo max_context_length (packing.py:193-195). Because attention re-derives document boundaries from positions == 0, every reset inside the padding region creates a new document start that consumes a fixed metadata slot. That's why the emit condition has to pre-compute the padding term ... + (num_segment_tokens - 1 + padded_length) // max_context_length (packing.py:161-166) -- it's reserving slots for padding chunks before committing a segment.
  • The RL batcher does the opposite and simpler thing: it keeps tail padding inside the final document with monotonic positions (positions.extend(range(positions[-1]+1, ...)), batcher.py:396-398), so padding never resets and never consumes a slot.

These two should agree. The reason the pretrain path can't just append padding to the last doc is that a padded last segment can exceed max_context_length, which would blow the pinned max_q. That is the real tension: to keep max_q fixed, padding must be chunked, and chunks cost slots.

This is exactly why your suggestion to emit an explicit padding mask / segment-ids from the dataloader is the right call. Today the padding-vs-real distinction is re-derived from positions == 0 in three places (get_document_mask_mod, get_efficient_causal_mask_mod_for_packed_document, create_varlen_metadata_for_document). If the loader/batcher emitted an explicit segment_ids (or a boolean padding mask) instead:

  • attention metadata building consumes it directly instead of inferring boundaries from position resets;
  • padding becomes a distinguished segment rather than a stream of fake documents, so the slot-accounting in packing.py:161-168 disappears;
  • MoE load-balancing later can exclude padding tokens cleanly (they must not count toward expert load), which is not possible today because padding is indistinguishable from a short real doc.

I'd endorse doing that, and unify pretrain + RL on the same padding convention while at it.


3. Can packing.py be simplified? Yes.

The _DocumentAwareConcatThenSplitIterator inline slot arithmetic (packing.py:161-169) is the hard-to-read part, and it's re-deriving something you already have a clean helper for:

  • FirstFit uses _max_real_documents_per_row(context) = max_num_documents - num_context_segments + 1 (packing.py:342-347) as a static cap on real docs, letting the fixed padding budget absorb the rest.
  • The ConcatThenSplit iterator instead recomputes an equivalent bound dynamically per segment, including the padded_length term. Since segments are <= max_context_length by construction, (num_segment_tokens - 1) // max_context_length == 0, so the whole expression collapses to "reserve ceil(pad_len / max_context_length) slots for padding" -- a fixed reservation.

Concrete simplification: cap real segments at a static _max_real_documents_per_row(context) (reuse the same helper), and drop the per-segment num_documents_if_emitted computation and the two asserts. The padding budget is then guaranteed by construction, and the loop condition becomes just "does this segment fit in the token budget and the real-doc count." This unifies the two packers on one notion of "reserved padding slots" and removes the most opaque block.

Even better, if you adopt the explicit-padding-mask approach from Q2, the modulo-reset padding goes away entirely and with it the whole reason this counting exists.


Other notes (smaller)

  • trainer.py -- the repeated getattr(getattr(self.config, "dataloader", None), "max_num_documents", None) block appears twice (trainer.py:702-711 and :759-771). Agree with your inline-into-preprocess_inputs suggestion; the double getattr with None fallbacks also reads defensively. If max_num_documents is only meaningful for varlen, passing it unconditionally to preprocess_inputs (letting get_attention_masks ignore it for flex) is cleaner than the conditional-kwarg construction. Also re: your earlier comment -- with model_spec now non-optional (good, the constructor=str trick + dropped asserts), the for fqn ... traverse(VarlenAttention.Config) validation at trainer.py:178-186 could adopt the reversed logic you asked for (if max_num_documents is None, only then traverse to see whether varlen is present and raise).
  • attention.py -- the capped branch silently drops doc-starts beyond max_num_documents via the num_slots dump slot (attention.py:632-636), backed only by an async assert. Since the loader enforces the cap upstream, this is belt-and-suspenders, but if the SFT-positions case from Q1 ever violates it, the failure is a delayed async assert rather than a clear error. Worth a comment noting the loader is the source of truth.
  • RL batcher -- _max_num_documents_per_row = max_num_documents // local_batch_size (batcher.py:110-115) gives every row an equal share to guarantee the local bound under round-robin. Consistent with the reviewer note to revisit when local_batch_size is removed.

Net: no documents are lost today (good), long-doc handling is inconsistent across packers and has a latent max_q correctness gap in the SFT-positions case, and the packing complexity is real but reducible -- reuse _max_real_documents_per_row for the concat path, and adopt the explicit padding-mask output you proposed to eliminate the position-reset accounting and set up MoE load-balancing correctly.
· branch varlen_pretrain_cudagraph

@liangel-02
liangel-02 force-pushed the varlen_pretrain_cudagraph branch 2 times, most recently from 61abf3c to 1458a33 Compare August 29, 2026 03:22
@liangel-02
liangel-02 requested a review from tianyu-l August 29, 2026 03:25

@tianyu-l tianyu-l 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.

overall looks great. Having some remaining questions but don't want to block merging

Comment thread torchtitan/components/data/collators.py Outdated
Comment on lines +58 to +75
else torch.as_tensor(row.padding_mask, dtype=torch.bool)
for row in rows
]
)

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.

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(

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.

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 = (

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 didn't understand what this count is for. Here's my guess but it could be off.

There are generally two types of padding

  1. per document padding, e.g. needed by FlexAttention to achieve batch invariance
  2. 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?

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude
For this new version, briefly state what happens for the two packing strategies. What I think we should achieve in both

  • no dropping of real data, unless it surpasses the min(tokens_per_batch, max_context_length) limit set by model
  • for the padding one, we start the data that couldn't fit on a new row
  • for the chunking one, we fit whatever we could on current row and start the rest on next row (but continue the positions counting)

Also take a look at my comment #4156 (comment) and provide insight.

@claude

claude Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 9m 11s —— View job


The two packing strategies in this version, vs. your three goals

First, the good news on the thing you flagged as complicated: the old _DocumentAwareConcatThenSplitIterator.__next__ (the num_documents_if_emitted slot-arithmetic + two asserts) is gone. The loop condition is now just num_tokens < num_tokens_per_row and len(position_parts) < max_num_documents_per_row (packing.py:127-130). Real segments are capped statically; padding slots are reserved separately in create_varlen_metadata_for_document. That reads much cleaner.

ConcatThenSplit — _DocumentAwareConcatThenSplitIterator (varlen / cudagraph path, i.e. max_num_documents set)

  • Pulls docs from parent, cuts each at a document boundary or an max_context_length chunk via _next_document_chunk_end (packing.py:149).
  • Fills a row until num_tokens_per_row OR max_num_documents_per_row segments is hit; a segment that doesn't fit the remaining token budget is split, with the tail carried in self._remainder / _remainder_offset (packing.py:155-173).
  • Tail-pads the row; padding positions reset % max_context_length (packing.py:184-186), and padding_mask=True.

FirstFit — FirstFitPackingConfig

  • _SplitTextSequenceDocuments (a FlatMapTransform, packing.py:294-332) chunks each doc into <= max_context_length pieces...
  • ...then FirstFitPackIterDataset bin-packs those chunks into num_tokens_per_batch rows, with max_sequences_per_bin = max_num_documents (packing.py:280-284).

Against your three goals

Goal ConcatThenSplit FirstFit
1. No dropping of real data (unless > min(tokens_per_batch, mcl)) Met -- never drops; over-length docs are chunked to mcl, remainders carried Now met -- the old len(input_ids) <= max_context_length drop-filter is replaced by chunking in _SplitTextSequenceDocuments. This is the key correctness fix vs. HEAD~1 (git show HEAD~1:.../packing.py still had the filter at line 81).
2. Padding strategy: data that can't fit starts a new row n/a (this is the chunking one) Met -- a chunk that doesn't fit the current bin lands in another bin; nothing is lost
3. Chunking strategy: fit what we can, rest on next row, continue positions Partially -- the fit/carry works, but positions do NOT continue. position_parts.append(np.arange(num_segment_tokens)) (packing.py:167) restarts at 0 for the carried tail, so a doc split across a row boundary becomes two independent segments (fresh RoPE positions on the second row). n/a -- chunks are atomic packing units, never split across a bin

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 segment_ids suggestion: document boundaries are re-derived from positions == 0 everywhere (get_document_mask_mod, create_varlen_metadata_for_document:628). If the carried tail continued its positions (e.g. [a..mcl)), then the first token of the next row would have position != 0, and create_varlen_metadata_for_document would fail to register the boundary at index 0 -- the cu_seqlens would be malformed. So "continue positions" is fundamentally incompatible with "position==0 means doc start." To get goal 3 you have to decouple boundaries from positions by emitting explicit segment_ids / a boundary mask from the loader (which is exactly the direction you pushed earlier). That single change buys goal 3, kills the position-reset padding accounting, and lets RoPE stay faithful across a split.

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 segment_ids change. If you keep the split, segment_ids becomes a prerequisite.

On discussion r3887847182 -- per-document vs per-row padding in the varlen metadata

Your two categories are the right frame. Here's what the metadata actually does with each:

  1. Per-document padding (your type 1 -- e.g. per_sample_pad_multiple in the RL batcher, batcher.py:416-431). This padding is folded into the owning document: positions.extend(range(sample_len)) counts straight through the pad, and padding_mask marks it True without a position reset. So it does not create a segment and does not consume a metadata slot -- it's absorbed into that document's seqlen. The varlen kernel does run attention over those pad tokens (wasted compute), but loss masking drops them.
  2. Per-row tail padding (your type 2). In pretrain this resets % max_context_length (packing.py:184-186), so a tail longer than mcl fragments into ceil(pad_len / mcl) padding segments. That is the only reason max_num_padding_segments = ceil(num_tokens / mcl) exists (attention.py:644-648) -- it bounds that fragmentation so the device metadata keeps a fixed shape for cudagraph.

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 max_q = max_context_length: every segment must be <= mcl, so a > mcl padding tail cannot be a single segment.

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 % mcl to keep it <= mcl is what forces the ceil(num_tokens/mcl) reservation. If the loader emitted an explicit padding mask (it now threads one through) and the metadata treated the whole trailing pad as a single excluded region rather than a stream of fake mcl-sized documents, max_num_padding_segments could drop toward a small constant and shrink the fixed metadata. That's the same segment_ids/padding-mask move that also unlocks goal 3 and clean MoE load-balancing.


  • Read packing.py (both strategies)
  • Check attention.py varlen metadata (r3887847182)
  • Summarize each strategy vs. the three goals
  • Insight on per-document vs per-row padding
    · branch varlen_pretrain_cudagraph

@shuhuayu
shuhuayu force-pushed the varlen_pretrain_cudagraph branch from cc4c96e to d8c32c5 Compare September 9, 2026 04:47
@shuhuayu
shuhuayu force-pushed the varlen_pretrain_cudagraph branch from d8c32c5 to ad79d1d Compare September 9, 2026 04:53
@shuhuayu
shuhuayu merged commit f23d7df into main Sep 9, 2026
28 of 29 checks passed
tianyu-l pushed a commit that referenced this pull request Sep 10, 2026
## 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.
@shuhuayu shuhuayu mentioned this pull request Sep 11, 2026
14 of 18 tasks
tianyu-l pushed a commit that referenced this pull request Oct 30, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu 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.

4 participants