Repository navigation
[Grain] Replace dataset/dataloader with grain - #4088
Conversation
There was a problem hiding this comment.
I will review the PR. I believe I took care of that here.
There was a problem hiding this comment.
I believe I took care of that here.
I would put a question mark because numerics would have changed?
| **dataloader_kwargs, | ||
| ) | ||
| # Add your dataset here - more information at docs/datasets.md | ||
| DATASETS: dict[str, SingleDatasetConfig] = { |
| return model_inputs, labels | ||
|
|
||
|
|
||
| class TextCollator(Collator): |
There was a problem hiding this comment.
I feel we no longer need a text collator after @acisseJZhong kills batch dim
There was a problem hiding this comment.
if we assume we always use packing, i think thats true. But, otherwise, we would still need it for padding.
There was a problem hiding this comment.
please see https://github.com/pytorch/torchtitan/pull/4121/changes changes in torchtitan/hf_datasets/text_datasets.py after we kill the batch dim. We pack samples to [T] instead of [B, S] and only pad at the end of [T].
| ### Checkpointing | ||
| ```text | ||
| random-access source -> global shuffle -> DP stride shard | ||
| Hugging Face stream -> source-level DP shard |
There was a problem hiding this comment.
| Hugging Face stream -> source-level DP shard | |
| HuggingFace stream -> source-level DP shard |
| Use concatenation to treat finite datasets as one corpus. Every row appears once; dataset sizes determine their proportions. Use mixing instead for explicit weights or streaming datasets. | ||
|
|
||
| All sources must share the same `infinite` setting. | ||
| ```python | ||
| from torchtitan.components.data import DatasetConcatConfig | ||
|
|
||
| pretraining_corpus_ds = DatasetConcatConfig( | ||
| datasets=(books_ds, code_ds, math_ds), | ||
| ) | ||
| ``` |
There was a problem hiding this comment.
Maybe we can explicitly state here that TorchTitan support data repeating, i.e., allow part of the data corpus to appear more than once in training, so that the model learns sth better. It should be doable but plz correct me if im wrong:
If I want a data subset books_ds to appear, say 3 times. Can I do sth like (books_ds, ) *3 + (code_ds, math_ds)?
Then, pretraining_corpus_ds is shuffled globally such that the 3 books_ds are away from each other during training.
| context=context, | ||
| dataset_iteration_policy=dataset_iteration_policy, | ||
| ) | ||
| dataset = dataset.filter( |
There was a problem hiding this comment.
The length filter runs after DP sharding and repetition.
If a rank’s shard contains only oversized samples, it scans an infinite rejected stream while other ranks enter training collectives, which can result in hanging.
There was a problem hiding this comment.
good find! But this is here more for sanity check. Its up to the upstream dataset to decide if they should truncate or not. We could add an extra check here that if >99% of data is filtered, to raise an error. Grain makes it pretty neat
dataset = grain.experimental.WithOptionsIterDataset(
dataset,
grain.experimental.DatasetOptions(
filter_raise_threshold_ratio=0.999,
),
)
but then we have to expose this flag as well and it only works for iterable. I think it will leave as is. Let me know if you disagree.
|
@aelavender has imported this pull request. If you are a Meta employee, you can view this in D116061491. |
ee5bb27 to
7dafc4c
Compare
8b5bdea to
1fdff6c
Compare
|
@aelavender The PR was rebased onto current |
Need to land the rest of the internal diff train first (I've kicked off the land), then can re-import this on top. |
… the HF delegate) Phase 2 died at dataloader build with the NotImplementedError I put in blendcorpus_builder during the 80th sync: dataset=fineweb_edu_local used the HF delegate, which the 80th sync removed That guard was correct -- it named the problem instead of failing obscurely -- but I then built the optimizer comparison on exactly the path it blocks. Two decisions made hours apart that contradicted each other. This ports the arms to the replacement object graph: GrainDataLoader over a ConcatThenSplitPackingConfig / SingleDatasetConfig / HuggingFaceRandomAccessSource, reading the parquet shards directly (path=parquet + data_files), which is the same shape torchtitan/hf_datasets/text_datasets.py uses for c4_test. Why not just fall back to blendcorpus: books.txt is the ONLY blendcorpus list that resolves on Sunspot. Every other list under data-lists/sunspot/ points at /gila, which is not mounted here. So there is no bigger-corpus blendcorpus option, and books is 5.8B tokens against a 10B budget (1.7x looped). 16 shards, not all 140: HuggingFaceRandomAccessSource materializes what it is given (streaming=False), so 140 files would try to hold 267 GB. 16 is ~22B tokens -- more than the 10B budget so no arm repeats data -- and the list is sorted+sliced, never sampled, so all three arms read byte-identical input. Verified end to end on the RC4 stack: dataloader builds, first batch is input shape (20480,) int64 -- exactly num_tokens_per_microbatch_per_dp_rank -- max id 100257 < vocab 100352, and positions is emitted.
Third sub-minute Phase 2 failure: GrainDataLoader.Config has no num_workers (grain owns its own prefetch), so the flag was Unrecognized. Checked every other flag the script passes against the real parser -- that one was the only invalid one. Fixing these one launch at a time was the actual problem: renamed flags (pytorch#4121), a deleted dataloader (pytorch#4088), then a nonexistent flag, each costing a 48-node allocation to discover something a single-process parse catches in seconds. So the script now parses its own argv before allocating. The preflight stops at config construction and deliberately does NOT build the Trainer: that calls set_device, and a login/head context has no GPU, so it would fail for a reason unrelated to the arguments (confirmed -- the first version did exactly that and rejected valid args). It also asserts the resulting batch, not just that the flags parsed: max_context_length 4096, LBS 5, GBS 960, GAS 1, decay_ratio 0.0. A flag that parses but yields a different GBS would silently invalidate the comparison against the Phase 1 LRs, which is worse than a crash. Verified positively (all three arms print PREFLIGHT OK with LBS=5 GBS=960 GAS=1) and negatively -- it REJECTS an unknown flag, a halved GBS that still parses, and decay_ratio flipped back to 0.8.
…d flag Muon won an earlier 2B competition and has never been run at 30B. Adds it as a fourth arm against the identical Phase 1 protocol (1e-6 -> 1e-1, 90 steps after 10 warmup, GBS=960, fineweb-edu) so its suggestion is comparable to the measured 3.05e-05 / 5.61e-05 / 3.55e-05. Launched as job 12474326. Removes --dataloader.num-workers=2, which this script still carried at line 126. It parsed on 2026-08-23 but pytorch#4088 replaced the dataloader with Grain and GrainDataLoader.Config has no such field, so the script would have aborted in flag parsing for ANY arm -- adamw and mano and sophiag included, not just the new one. optcmp.pbs had already dropped it when Phase 2 hit this same failure class; lrfind_opt.pbs was never re-run and stayed stale for a week. Caught by a preflight that parses the flag list extracted FROM the script rather than a retyped copy, which is the only version of that check that works. Records the Muon-specific reading caveat in the script itself, because the number is easy to misread. Muon partitions parameters by tensor SHAPE (muon.py:85-89), so at 30B only wq/wk are on the Muon path -- w1/w2 at 16384 and the embedding/head at 100352 exceed the hardcoded 10000 cutoff and fall to an internal AdamW branch. For the Muon-path tensors the LR is rescaled by 0.2*sqrt(max(A,B)), which is a uniform 15.677x at this config since every one of those shapes has max dim 6144. The finder sweeps the BASE lr, so a suggestion near 2-4e-06 would be the rescale showing up rather than Muon wanting a wildly different LR. Also adds a known-bugs writeup for something the preflight exposed: 99 of the ~100 .pbs scripts at the repo root still pass a dead flag on a live line, and every one would abort today. Not mass-fixed, and the doc says why -- they are mostly concluded one-off diagnostics, the newest predates the renames, none can be tested without an allocation, and a naive bulk sed would also rewrite sync82_smoke.pbs where the flags appear only in a comment explaining their removal. The doc gives the grep to run before reusing any of them and names the three known-good templates.
… error Job 12474399 aborted in the config gate after ~1 minute with `ModuleNotFoundError: No module named 'grain'`. I had copied the environment header from 30b_smoke.pbs, which points at venvs/fw-2026.1-rc2 -- but that script predates pytorch#4088, and the current dataloader imports grain.python, which only venvs/fw-2026.1-rc2-grain has. Every verification I ran today used the -grain venv and passed; the job used the other one and died. Noted in the script so the wrong header is not copied again. THE ABORT PRINTED NOTHING USEFUL, which is the more annoying half. The gate did its job -- it caught a broken config before 64 nodes ran three arms -- but its error line greps for a hardcoded alternation (AssertionError|ImportError|AttributeError|KeyError) and the real error was ModuleNotFoundError, which is not in it. So the .o file said "ABORT: ladder failed to resolve" and then nothing, and the actual traceback was only in a side file. Now it tails the real capture instead of guessing which exception class to look for. An abort message that omits the error wastes the job twice: once on the failure, once on the diagnosis. Gate re-verified in the corrected venv before relaunch -- all four CFG_OK lines, dim 9216 / vocab 256128 identical across 48L / 72L / 84L. Relaunched as 12474403.
…4088 Grain API) HFDataSource / InterleavedHuggingFaceTextDataLoader were removed in the Grain-era text_datasets refactor (pytorch#4088); the agpt CPT mix builders kept importing them and died with ImportError on every MDS-mix CPT job (e.g. agpt2b_posttrain o12481877 VERDICT: cpt_failed). Replace with the current Grain API (SingleDatasetConfig + HuggingFaceStreamingSource + DatasetMixConfig + ConcatThenSplitPacking) matching the proven tulu_math_uc_streaming pattern in sft_data.py. Co-authored-by: internal-model
Grain (pytorch#4088) deleted HuggingFaceTextDataLoader. The old function raised NotImplementedError; now it builds a GrainDataLoader from core DATASETS["c4_test"] (bundled tests/assets/c4_test, no network). This unblocks Sirius (workq/datascience is home-only, no tegu dolma) to run a real 3-step smoke on c4_test instead of hitting the blendcorpus data wall. Co-Authored-By: internal-model
HFDataSource/InterleavedHuggingFaceTextDataLoader deleted in pytorch#4088; previous mix builders always crashed. Port to GrainDataLoader (DatasetMix after ConcatThenSplitPacking) so weights count packed 8192-token rows (token-weighted). Adds agpt_2b_mds_mix_owm_edu_6040 (SmolLM2 60/40). CPT script already switched to PPN=8 and MDS_ANNEAL_BASE TEGU path (prior 12483035 failed on both). Co-Authored-By: internal-model
HFDataSource/InterleavedHuggingFaceTextDataLoader deleted in pytorch#4088; previous mix builders always crashed. Port to GrainDataLoader (DatasetMix after ConcatThenSplitPacking) so weights count packed 8192-token rows (token-weighted). Adds agpt_2b_mds_mix_owm_edu_6040 (SmolLM2 60/40). CPT script already switched to PPN=8 and MDS_ANNEAL_BASE TEGU path (prior 12483035 failed on both). Co-Authored-By: internal-model
HFDataSource/InterleavedHuggingFaceTextDataLoader deleted in pytorch#4088; previous mix builders always crashed. Port to GrainDataLoader (DatasetMix after ConcatThenSplitPacking) so weights count packed 8192-token rows (token-weighted). Adds agpt_2b_mds_mix_owm_edu_6040 (SmolLM2 60/40). CPT script already switched to PPN=8 and MDS_ANNEAL_BASE TEGU path (prior 12483035 failed on both). Co-Authored-By: internal-model
HFDataSource/InterleavedHuggingFaceTextDataLoader deleted in pytorch#4088; previous mix builders always crashed. Port to GrainDataLoader (DatasetMix after ConcatThenSplitPacking) so weights count packed 8192-token rows (token-weighted). Adds agpt_2b_mds_mix_owm_edu_6040 (SmolLM2 60/40). CPT script already switched to PPN=8 and MDS_ANNEAL_BASE TEGU path (prior 12483035 failed on both). Co-Authored-By: internal-model
…30B infeasible on current frameworks (#76) * fix(ezpz): gate 30B v2 4K to selective remat Full (torch_remat 0.2.0 on aurora_frameworks-2026.1.0) hits _set_storage_data_ptr_access_error_msg bomb; none OOMs at 30B even at 8N (9053526 CCL scaleout_device_buf malloc fail). Selective (DefaultActivationRematConfig, model-declared regions) uses a different torch_remat path and may fit within XPU memory. 4B/10B stay on none (already finite-loss). * fix(ezpz): sync attn_gym lazy-export deferral from main (pytorch#5565) Branch was 124 commits behind main; attn_gym.py predated 3ed5aa9 which defers backend ImportError from attn_gym.linear._lazy (causal_conv1d via cute.py:26 import cutlass) to a _MissingKernel placeholder. Without it, any import of torchtitan.models.common — including torchtitan.experiments.ezpz.agpt.config_registry via agpt/__init__.py:36 — hard-fails on macOS where attn-gym 0.0.17 is installed but cutlass is absent. Aurora (Intel XPU via aurora_frameworks-2026.1.0 / oneAPI, no CUDA) was never affected — its XPU path does not hit cutlass the same way and all 4B/10B jobs reached Training starts at step 1. Bring file verbatim from origin/main. * Revert "fix(ezpz): gate 30B v2 4K to selective remat" 30B 8N selective (9053611, E 143) hits the same _set_storage_data_ptr_access_error_msg bomb as full: _placeholder.py:101 torch._C._set_storage_data_ptr_access_error_msg AttributeError: module torch._C has no attribute ... Both DefaultActivationRematConfig and FullActivationRematConfig go through torch_remat 0.2.0 on aurora_frameworks-2026.1.0 (torch 2.13). 30B stays infeasible until frameworks pins a compatible torch_remat. Keep 30B on none and document the failure; keep attn_gym pytorch#5565 sync. * feat(ezpz): agpt-v2 4B/10B 4K configs streaming full raw olmo-mix-1124 Add agpt_v2_{4b,10b}_4k_olmo_mix, which stream the raw olmo-mix-1124 JSON shards listed in $AGPT_V2_DATA_MANIFEST through the Grain HF streaming source, and build_olmo_mix_manifest.py, which sizes that list to a multiple of the DP world size so split_dataset_by_node assigns whole files per rank. * fix(ezpz): complete attn_gym deferral sync — wire require_attn_gym + is_missing_kernel in callers Sourcery flagged that only attn_gym.py was synced from main (pytorch#5565); its callers still did bare require_attn_gym()/identity checks that TypeError'd or leaked placeholders into SPMD registration when cutlass/triton absent. Pull the companion 4 files from main and add a compat shim for the renamed prepare_cp_linear_attention_metadata. Co-Authored-By: internal-model * docs(ezpz): 60/40 corpus kind-shift + MMLU letter-prior gating notes Subagent fanout: FineWeb-Edu 60/40 kind-shift proposal (SmolLM2 33.6% @38B vs current 94.8% DCLM monoculture) + MMLU letter-prior gating appendix (constant-D 0.2689 > all 2B 0.2413-0.2655 is harness prior). 5 files (2 new + 3 updated indexes), no compute. Co-Authored-By: internal-model * fix(ezpz): CPT-FWE 4N to PPN=8 + 60/40 kind-shift config 12483035 failed: world_size 60 (5xPPN12) 11008%60!=0 FSDP uneven sharding plus missing MDS_ANNEAL_BASE on Sunspot (~/torchtitan has no outputs/, lives on TEGU at .../projects/saforem2/.../step-0). Fix: select=4 PPN=8 -> 32r (11008%32==0), export MDS_ANNEAL_BASE to TEGU path. Adds agpt_2b_mds_mix_owm_edu_6040 (SmolLM2 60/40 FWE/DCLM stage-1). Co-Authored-By: internal-model * fix(ezpz): port _agpt_2b_mds_mix_blend to Grain DatasetMix + 60/40 HFDataSource/InterleavedHuggingFaceTextDataLoader deleted in pytorch#4088; previous mix builders always crashed. Port to GrainDataLoader (DatasetMix after ConcatThenSplitPacking) so weights count packed 8192-token rows (token-weighted). Adds agpt_2b_mds_mix_owm_edu_6040 (SmolLM2 60/40). CPT script already switched to PPN=8 and MDS_ANNEAL_BASE TEGU path (prior 12483035 failed on both). Co-Authored-By: internal-model * fix(ezpz): re-add agpt_debugmodel_gsm8k_plus_distill_streaming (clobbered by CPT push) * docs(ezpz): 2088N umbrella post-mortem + per-seat resubmit Placeholder 9053470 (select=2088, 24h) ran 4h26m — a single GPU fatal error (grf_fatal_singlesubslice_error on x4415c5s5b0n0, 10B slice) made PBS kill the whole 2088N job and all four seats. 20B-512 hung after 10854 (watchdog restart, no new ckpt), 20B-256 saved step-21100, 4B saved step-2600, 10B at 768N never trained (step-1 loss 17788+). Resubmitted as one PBS job per seat (seat-autoretry-20261111.pbs + submit-seats-20261111.sh): 10B moved 768N->512N, HF cache on /tmp. Umbrella PBS retained for provenance. Journal + PROD/README updated. Co-Authored-By: internal-model * style(ezpz): lint grain-sft-cot ufmt on config_registry and cp_linear_attention, license header on build_olmo_mix_manifest, spell out FW-Edu and 'reused' for codespell. * docs(ezpz): fix broken journal links in production README * fix(ezpz): shuffle olmo-mix manifests so the v2 mix is not a curriculum split_dataset_by_node gives rank r files r, r+dp, ..., so a sorted manifest feeds the subsets in path order. The builder now writes a seed-0 shuffle by default. The 10B seat defaults to olmo-mix-dp6144-shuf0.txt; the 4B stays on the sorted file it resumes from. * fix(models): CP KDA/GDN check their attn_gym exports at build Port upstream's require_attn_gym calls for ContextParallelInnerKDA and ContextParallelInnerGDN. Without them the four context-parallel cases in test_optional_imports.py (copied from upstream on this branch) built successfully with a missing backend and failed. * SFT script: CKPT_DIR respect -v override so CPT-17000 lane writes agpt2b-cpt17000-gsm8k-3ep not default ep3 (avoids clobbering ckpt93 B2) --------- Co-authored-by: sim <sim@localhost>
Read datasets.md first! Seriously.
Summary
Previous behavior
New behavior
GrainDataLoaderbatches and checkpoints a composed dataset graph for every supported workload.Validation
Ran on DP=2 text, SFT, MM, flux.
For each workload:
Findings:
*The Flux overlay includes an isolated accelerator-RNG restoration experiment. RNG checkpointing is deferred from this PR; the current data pipeline still restores its own state exactly.Performance
These are local debug-model results, not production-scale throughput claims.
Note: The SFT main and PR timings are not an apples-to-apples speedup: main mixes already-packed rows, while the PR mixes examples before packing. The absolute timings are retained as a regression check.