Repository navigation
fold batch dim - #4121
fold batch dim#4121
Conversation
| --job.config-file torchtitan/models/llama3/train_configs/llama3_8b.toml \ | ||
| --metrics.enable_wandb \ | ||
| --training.local_batch_size=2 \ | ||
| --training.num_tokens_per_dp_rank=16384 \ |
There was a problem hiding this comment.
this command was run on old commit, so shouldn't change?
| *, | ||
| parallelism: ParallelismConfig, | ||
| local_batch_size: int, | ||
| n_microbatches: int, |
There was a problem hiding this comment.
| n_microbatches: int, | |
| num_microbatches: int, |
| @@ -108,11 +108,12 @@ def forward( | |||
|
|
|||
| # TODO(pianpwk): same QKV:S(2) unflatten case handled by even sharding | |||
| from torchtitan.protocols.module import Module, Sequential | ||
|
|
||
|
|
||
| class FluxScaledDotProductAttention(ScaledDotProductAttention): |
There was a problem hiding this comment.
why we need this? SDPA is only used by Flux anyway.
There was a problem hiding this comment.
it's also used by graph trainer.
for flux, SDPA needs to still accept [B, L, N, H] while the core SDPA has been changed to accept [1, T, N, H] since SDPA CP assumes shard(2).
There was a problem hiding this comment.
Can we not change core SDPA? It's not used for any LLM / VLM, but only used for FLUX
There was a problem hiding this comment.
it's only used by FLUX and graph trainer
let me restore core SDPA and let flux uses core SDPA, graph trainer can use a SDPA wrapper that supports flattened input.
There was a problem hiding this comment.
this PR shouldn't change input layout for flux, for which we need full bidirectional attention for each row, so it shouldn't be folded
There was a problem hiding this comment.
Flux’s actual data/model layout is not folded. It remains:
dataloader: [B,...]
latents/text: [B,L,D]
Q/K/V: [B,L,N,H]
SDPA: [B,N,L,H], is_causal=False
| @dataclass(kw_only=True, slots=True) | ||
| class TrainingConfig: | ||
| local_batch_size: int = 8 | ||
| num_tokens_per_dp_rank: int = 16384 |
There was a problem hiding this comment.
see comment in trainer.py, I wonder if we can put this into dataloader config, just like RL batcher
There was a problem hiding this comment.
sounds good, i will update after @felipemello1 landed his grain PR tonight.
| local_batch_size: int = 8 | ||
| """Per-DP-rank microbatch size (rows per forward pass). If the number of tokens in the | ||
| rollouts exceed the number of rows*seq_len, a new microbatch is started. | ||
| If it is less, the remaining rows are padded to this size.""" | ||
|
|
||
| seq_len: int = 2048 | ||
| """Tokens per row (packed sequence length).""" |
There was a problem hiding this comment.
no longer need this BatchConfig, just need a num_tokens
There was a problem hiding this comment.
let's follow up RL in a separate PR as it requires larger changes.
Right now RL concats [local_batch_size, seq_len] batches into [local_batch_size * seq_len].
| # RL policy inputs are shaped by BatchConfig, so mirror its shape | ||
| # into the trainer's token-based configuration. | ||
| batch_config = self.async_loop.batcher.batch | ||
| self.trainer.training.max_seq_len = batch_config.seq_len |
There was a problem hiding this comment.
we need to improve the original logic
trainer.training.max_seq_lenis about model capability and rope cache allocationbatch_config.seq_lenis about actual input length. It shouldn't be longer than model capability, but if it's less we can save some overhead on rope cache allocation
There was a problem hiding this comment.
once we merge RL batcher config into pretrain batch config, there will be no batch_config.seq_len, only trainer.training.num_tokens_per_dp_rank and trainer.training.max_content_length for RL?
| parallelism=training_parallelism, | ||
| training=TrainingConfig( | ||
| local_batch_size=1, | ||
| num_tokens_per_dp_rank=( |
There was a problem hiding this comment.
used in token dispatcher to calculate required_num_max_tokens_per_rank
| # and the required RoPE cache length. | ||
| seq_len: int = 2048 | ||
| """Sequence length""" | ||
| max_seq_len: int = 2048 |
There was a problem hiding this comment.
I found this to be confusing, how about
| max_seq_len: int = 2048 | |
| max_context_length: int = 2048 |
There was a problem hiding this comment.
this aligns with rope.config's max_seq_len, do we want to update rope as well?
|
|
||
| def _vision_spans(self, vision_mask: torch.Tensor) -> list[tuple[int, int, int]]: | ||
| """Find contiguous vision spans as ``(sample_idx, start, n_tokens)``. | ||
| def _vision_spans(self, vision_mask: torch.Tensor) -> list[tuple[int, int]]: |
There was a problem hiding this comment.
I think this function and _inject_vision can be replaced by the common function in common/multimodal.py?
There was a problem hiding this comment.
changed, please help double check!
…oudly Upstream's fold-batch-dim (pytorch#4121, in the 35 commits we have not merged) reshapes the LM stack from [B, L] to a flat [T] token layout. Our three hand-written SDPA/flex wrappers take q_BLNH/k_BLNH/v_BLNH and immediately do transpose(1, 2). If 3D tensors ever reach them, that transpose swaps N with H instead of L with N -- and SDPA ACCEPTS the result. There is no traceback; you get a quietly degraded loss curve, which is the single worst failure mode in that whole sync and the hardest to attribute after the fact. The _BLNH suffixes already state the contract. This makes it checkable: assert q_BLNH.ndim == 4 at each of the three entry points (agpt/__init__.py x2, moe/__init__.py x1), with a message naming fold-batch-dim as the likely cause so whoever hits it does not have to rediscover this. Passes today -- production is [B, L] -- so this is inert now and a tripwire later. A python assert on .ndim is static under dynamo (constant-folded, not a data-dependent guard), so it costs nothing in the compiled path. Note the earlier analysis said four sites. There are exactly three: grep -rn "_BLNH.transpose(1, 2)" over experiments/ezpz/ returns three wrappers, all now guarded.
Update the K3 decoder, KDA, MoE, vision path, dataloader config, tests, and numerical script for the token-major and packed-vision interfaces introduced by pytorch#4121. Preserve the latest upstream Kimi-VL numerical-test documentation while rebasing the feature history.
Phase 2 (12473720/21/22) died at argument parsing in 47s with
Unrecognized options: --training.seq-len, --training.local-batch-size,
--training.global-batch-size
because the 80th upstream sync renamed all three, and the sync reached the
cluster between the Phase 1 finders (which ran on the old tree and succeeded)
and the Phase 2 launch.
The rename also changes UNITS, sequences -> tokens, so this is not a
search-and-replace:
--training.seq-len=4096 -> --training.max-context-length=4096
--training.local-batch-size=5 -> --training.num-tokens-per-microbatch-per-dp-rank=20480 (5 x 4096)
--training.global-batch-size=960 -> --training.num-tokens-per-train-step=3932160 (960 x 4096)
Verified by round-trip through the real parser: 20480/4096 = LBS 5,
3932160/4096 = GBS 960, GAS = 1 at 192 ranks -- i.e. the batch is bit-identical
to the one Phase 1 measured its LRs at, which is the property the whole
comparison depends on.
lrfind_opt.pbs gets the same treatment so a re-run of Phase 1 stays comparable.
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.
…h#4121 Job 12473732 died at dataloader build: GrainDataLoader.__init__() missing 2 required keyword-only arguments: max_context_length and num_tokens_per_batch pytorch#4121 renamed the dataloader kwargs, and the ezpz trainer still passed the old seq_len / local_batch_size. Upstream trainer.py:559 already uses the new names. The fix is not a rename, because this tree runs TWO dataloaders whose signatures did not converge: GrainDataLoader wants max_context_length / num_tokens_per_batch BlendCorpusDataLoader wants seq_len / local_batch_size Both accept **kwargs and ignore what they do not name, so the callsite sends BOTH pairs. Renaming instead of adding would have swapped one breakage for a worse one: blendcorpus is every production config (2B/20B/30B chains), and it would have failed the same way. Values are identical either way -- dataloader_batch_size is already num_tokens_per_microbatch_per_dp_rank, a TOKEN count post-pytorch#4121. Verified both paths accept the exact kwargs the callsite now sends: GrainDataLoader builds; BlendCorpusDataLoader passes signature matching (its later failure is the absent data-file cache on a login node, not the args).
…moke Fifth sub-minute Phase 2 failure, and the first one past argument parsing: NameError: name global_batch_size is not defined (trainer.py:794) Two leftovers from the pytorch#4121 port, both in logging. Line 564 sits inside the batch-ramp branch (disabled by default, so it never fired); line 794 is the unconditional init banner, which is why every rank died. The second also gets relabelled -- post-pytorch#4121 the value is TOKENS per train step, so calling it global batch size would misread by 4096x. pyflakes now reports zero undefined names in trainer.py. The five remaining hits across ezpz are in files this path does not touch, including the deliberately-dead HuggingFaceTextDataLoader reference after the raise. optcmp_smoke.pbs is the process fix. Five 48-node launches each died on a DIFFERENT layer -- CLI flags, dataloader class, dataloader kwargs, then a log line -- and every one was reachable at 2 nodes. This runs all three arms sequentially, 3 steps each, in one 2N allocation, and prints a PASS/FAIL verdict per arm. GBS is intentionally NOT 960 here: 24 ranks cannot reach the comparison batch, and this job tests the code path, not the numerics.
The 2N smoke caught this before any 48-node launch: all three arms hit
assert q_BLNH.ndim == 4 -- expected 4D [B, L, N, H], got (20480, 48, 128)
The assertion fired exactly as designed; its own message predicted this case
("if the fold-batch-dim token layout landed, this wrapper needs updating").
pytorch#4121 reshaped the LM stack to a flat token layout, so q/k/v now arrive 3D.
Why the wrapper and not upstream: upstream ScaledDotProductAttention does the
same bare transpose(1, 2), and the flat-layout path it does provide
(VarlenAttention) requires CUDA flash attention, which XPU lacks. Neither
upstream branch covers this configuration.
Why this is not a one-line transpose change: on a 3D tensor transpose(1, 2)
swaps N with H, and SDPA ACCEPTS the result. The failure mode is a quietly
degraded loss curve, not a traceback -- the same class of silent-wrongness as
the LR-decay bug that invalidated the 64N run.
B is recoverable because ConcatThenSplitPacking emits fixed-length rows: T is
a whole number of max_context_length sequences (measured 20480/4096 = 5,
exactly the configured LBS). A divisibility check keeps that verified rather
than assumed and raises on a ragged batch.
max_context_length reaches the wrapper through a module-level setter, not an
argument: the forward positional-arg names are contract-checked under TP>1
(set_gqa_inner_attention_local_map matches in_dst_shardings by name), so the
signature must not change.
Verified numerically, not just by shape: the flat path and the 4D path produce
allclose outputs on the same data; the 4D path is unchanged (production
blendcorpus configs); a ragged token count raises. SoftcappedFlexAttention has
an identical assert but is a separate flex path and is deliberately untouched.
… its own unit Three fixes from smoking the 20B path on post-80th-sync main. Each was found by a 2N debug run, and each would have killed the 130-node chain. 1. pytorch#4121 removed --training.{local,global}-batch-size and --seq-len. The submit script still emitted them, so every run died at argparse ("Unrecognized options"). Ported to the token-unit replacements, DERIVING them from the script's existing LBS/GAS/GBS arithmetic rather than hardcoding: num-tokens-per-microbatch-per-dp-rank = LBS * SEQ_LEN num-tokens-per-train-step = GBS * SEQ_LEN max-context-length = SEQ_LEN At the chain's settings that is 1024 x 8192 = 8,388,608 tokens/step, IDENTICAL to before the rename -- which is what makes resuming step-5600 safe. A hardcoded guess would have used LBS=1 (the script defaults to 2) and silently halved the batch. Both values now log at startup so a future mismatch is visible instead of silent. 2. BlendCorpus counts SEQUENCES; Grain counts TOKENS. Post-pytorch#4121 both were being handed the same token count. On blendcorpus that made the embedding request 8192 seq x 8192 tok x 2048 dim x 2 B = exactly 256 GiB on a 40 GiB card -- with 32 GiB free (smoke 7554426). A shape bug wearing an OOM costume. Each loader now gets the unit it means: sequences to blendcorpus, tokens to Grain. Added a guard that raises when the token count is under one full sequence, so a future mis-set fails loudly instead of truncating the batch. Note this REPLACES the "same value either way" comment that arrived with the concurrent upstream fix -- the values are not the same, and collapsing them mis-sizes whichever loader disagrees. 3. Documented the venv-tarball staleness trap: a dependency fix must land in the live .venv AND in .venv.tar.gz, since compute nodes unpack /tmp/.venv from the tarball. `ezpz tar-env` SKIPS with exit 0 when the tarball exists, so it must be moved aside and the artifact verified by listing the module out of the new archive. The grain dependency (declared in pyproject.toml + requirements.txt, never installed) hit exactly this: installing it into the login venv left the next smoke failing identically. The dangling `global_batch_size` NameError was fixed concurrently upstream; that resolution is taken as-is rather than kept as a duplicate. Not fixed here: the attention wrappers still assert 4D [B, L, N, H] and the model now hands them a folded [B, L*N, H]. That assert is load-bearing -- transpose(1,2) on a 3D tensor swaps N with H, SDPA ACCEPTS it, and the result is a quietly degraded loss curve rather than a traceback. Porting it needs numerics validation against the existing checkpoint, so it is deliberately left failing loudly.
The verification smoke in the fresh-venv guide still passed --training.local-batch-size / --training.seq-len, which the 80th sync replaced with token-unit flags. Anyone following the guide to validate a new venv would hit an argument error and think the venv was broken. Ported to --training.num-tokens-per-microbatch-per-dp-rank / --num-tokens-per-train-step / --max-context-length, and noted that submit_agpt_20b_autoretry.sh is already on the new names while submit_agpt_2b_autoretry.sh (line 268-270) is not.
…layout BlendCorpus yielded a [B, L] batch, but upstream pytorch#4121 (80th sync) moved the LM stack to a flat [T] token layout. Every production agpt config died at the first attention layer on Polaris job 7557496: ValueError: token count 1 is not a multiple of max_context_length 8192 Root cause, reproduced from the shipped reshape rather than inferred: QKVLinear reads num_tokens = x.shape[0] then x.view(num_tokens, -1, head_dim) (models/common/attention.py:696,704), and GQAttention ends with out_TNH.view(out_TNH.shape[0], -1). Both treat dim 0 as TOKENS. Given [1, 8192, 2048] that leaves dim 0 = B, so sequence and heads merge: q comes out (1, 131072, 128) instead of (8192, 16, 128). Ran both through the real ops -- the first is bit-for-bit the shape the 2026-08-24 crash reported. Grain never hit this because TextCollator already emits torch.cat(rows) (components/data/collators.py:57). flatten() is row-major, so it is identical to that cat: token ORDER is unchanged, which is what makes this safe for the in-flight chains and their checkpoints. positions folds too, and that half is the dangerous one -- it does not raise. get_efficient_causal_mask_mod_for_packed_document reads positions.shape[0] as seq_len and cumsums along dim 0 (attention.py:485-487); on [B, L] that reads the BATCH size and yields document ids of -1, so flex attention would mask the wrong spans and show up only as a worse loss curve. Positions are derived before the fold, since _document_positions reduces along dim 1 to find EOD. Tests cover the fold's order-preservation against core's cat, both attention shapes incl. GQA n_kv, and the -1 document-id failure. 7/7. Not yet smoked on hardware -- next step is a 2N Polaris run on .venv-torch213 checking that loss actually descends, since a wrong reshape scrambles Q/K and still runs.
…th the smoke Writes up the fix in 42f4edf: what broke, the measured shapes on both sides, why the positions half was the dangerous one (silent -1 document ids rather than a raise), and why flatten() is safe for in-flight chains. Records the Polaris 7557829 evidence -- 12/12 steps, loss 12.91 -> 8.19, step-1 within 0.007 nats of the known-good Grain baseline -- because rc=0 by itself would not have proven the reshape correct. Also states the rule the two reverted attempts violated: do not read a tensor layout off its name suffix, run the reshape.
…kwargs
Gate job 7558514 aborted in config.build() before step 1:
TypeError: Validator.__init__() missing 1 required keyword-only
argument: 'num_tokens_per_batch'
pytorch#4121 renamed core's Validator kwarg local_batch_size (SEQUENCES) ->
num_tokens_per_batch (TOKENS). It is keyword-only with no default, so
the old name is a hard TypeError. A trainer.py comment asserted
'upstream did not change the validator path' -- that was wrong, and the
crash is what disproved it.
Three stale references, all from the same rename:
- trainer.py passed local_batch_size= to validator.build().
- validator.py read self.local_batch_size, which core no longer sets
(it stores self.num_tokens_per_batch as of pytorch#4121).
- validator.py read training.global_batch_size, renamed to
num_tokens_per_train_step. getattr(..., None) meant this one failed
SILENTLY: the sample budget quietly fell back and overwrote the
blendcorpus bc_set_config global with wrong values.
The dataloader build now sends both unit pairs, matching what the
trainer already does -- blendcorpus counts sequences, Grain counts
tokens, and both take **kwargs and ignore what they do not name.
Only fires with the validator enabled, which is why the 2N sync smokes
missed it: they all ran --checkpoint.no-enable with no validator.
…tract
Gate 7558682 aborted in config.build(), one rename past the last one:
TypeError: BlendCorpusDataLoader.Config.__init__() got an unexpected
keyword argument 'repeat'
core's Validator.__init__ runs
`replace(config.dataloader, repeat=config.steps != -1)` unconditionally
(components/validate.py:132), and dataclasses.replace raises on an
unknown field -- so the validator simply cannot be built on this path.
`repeat` is upstream's spelling of our `infinite`; added as a field with
a __post_init__ that reconciles the two, since the rest of the loader
reads `infinite` and a silent divergence would hand the validator an
endless dataloader.
Also fixed the same class of break one level down, before it could
surface as gate #5: __init__ REQUIRED seq_len + local_batch_size, but
core's own Validator.validate() calls dl_config.build() with only
max_context_length + num_tokens_per_batch (validate.py:235). ezpz
overrides _get_validation_dataloader and sends the old pair, which is
the only reason that path had not fired yet. All four names now bind,
with tokens -> sequences conversion at the boundary.
This is the FOURTH pytorch#4121 casualty on the blendcorpus path, and they
share a shape: each fires only where the 2N sync smokes did not look
(#3 and #4 both need --validator.enable, which the smokes had off). So
the tests here assert the CONTRACT -- the names core reaches for -- on
CPU with no GPU, no corpus, and no cluster. 14 tests; both real gate
failures are covered as explicit negative controls.
…d is not tripped
Smoke 8781152 reached build_mesh and then every rank died in the forward:
ValueError: token count 2 is not a multiple of max_context_length 8192;
this wrapper assumes the fixed-length rows ConcatThenSplitPacking emits
agpt_debugmodel is agpt("debugmodel", local_batch_size=2) and agpt() defaults
seq_len=8192, so the debugmodel inherits max_context_length=8192 while its
dataloader hands attention T=2 tokens. The pytorch#4121 folded-attention wrapper
recovers B as T // max_context_length, and 2 // 8192 = 0 -- it refuses rather
than building a [0, 8192, N, H] view.
The config is what is wrong, not the wrapper. That guard is the thing standing
between us and a silent failure: on 3D input a bare transpose(1,2) swaps N with
H, SDPA ACCEPTS it, and the symptom is a degraded loss curve with no traceback.
Left it alone.
Production is unaffected, and that is measured rather than argued: q=(8192,16,
128) at seq_len=8192 on 4 A100s, i.e. T is a whole number of packed rows
(Perlmutter 57536150, plus a 4-step train at 57536357 -- see
tests/test_attn_unflatten.py, which passes 5/5 including
test_ragged_batch_raises).
The moe arm already pinned seq-len, but for an unrelated reason (a
(8,H,8192,8192) attention matrix is a 32 GiB single alloc on the XPU MATH
fallback). Comment now distinguishes the two so neither gets "cleaned up" into
the other.
…d by 42f4edf I wrote that page against a smoke (8781152) that ran on a clone at c102006, which predates 42f4edf "fold [B, L] -> [T] for the pytorch#4121 token layout" by ten minutes. blendcorpus_builder.py:457 now does input_ids.flatten(), so attention receives T = B*L and the guard's divisibility check passes for every LBS >= 1. The page's core claim -- that blendcorpus emits 2D [B, L] and the wrapper therefore reads dim0 as batch -- was true of the pre-flatten tree and is false on HEAD. Publishing it would have left a known-bugs entry describing a bug that does not exist, which is worse than no entry. Also retracts the "production is affected" reading: with the flatten in place agpt_2b gives T=8192 and agpt_20b T=8192, both exact multiples of max_context_length. Production was never at risk on current code.
TP>1 has been broken since the pytorch#4121 port. MEASURED, smoke 8781623 arm 2 (2N, TP=2): AssertionError: XPUScaledDotProductAttention: local_map is set but in_dst_shardings is missing entries for: ['q_BLNH', 'k_BLNH', 'v_BLNH'] The local_map contract matches by positional-arg NAME (distributed/spmd_types.py:350 iterates in_src.keys() & in_dst.keys(), keyed on the wrapped function's parameters). pytorch#4121 itself (73aed7f) renamed the upstream keys to q_TNH/k_TNH/v_TNH in models/common/decoder_sharding.py:288 as part of the layout change. Our port 476d168 adapted this function's BODY for the flat [T, N, H] batches and left its PARAMETERS at _BLNH, so the two halves of the same change disagreed. It stayed hidden because TP=1 never wraps the attention local_map -- the exact blind spot sync_smoke.sh's TP=2 arm exists to cover, and the same failure mode the 57th sync's original q_BLNH rename was written to prevent, reintroduced from the other direction. Renamed in EzpzScaledDotProductAttention.forward only (20 occurrences), which XPUScaledDotProductAttention inherits. SoftcappedFlexAttention keeps _BLNH: it takes genuine 4D [B, L, N, H] and is not local_map'd, so its suffixes are accurate and its contract is a different one. Not yet re-smoked -- committing so the next 2N run picks it up. The other two arms of 8781623 fail for unrelated reasons and are separate: arm 1 is a complex64 RoPE view (65536 elements into [16384, 1, 8]) and arm 3 is --training.local-batch-size, a second flag name tyro does not recognize.
…o one row Two more findings from smoke 8781623, both measured. 1. Neither flag the script has ever passed exists. Dumping Training's dataclass fields on the cluster gives exactly three size knobs: num_tokens_per_microbatch_per_dp_rank, num_tokens_per_train_step, max_context_length. There is no seq_len and no local_batch_size, so --training.seq-len and --training.local-batch-size have BOTH been silently rejected by tyro on every run since b8c369f. The moe arm carried two dead flags, not one, and the shrink it was supposed to apply never applied. 2. Post-pytorch#4121 the arms must pin ntok_per_microbatch EQUAL to max_context_length. The loader now flattens [B, L] -> [T], so T = ntok_per_microbatch, and rope._reshape_for_broadcast does rope_cache[:T].view(T, 1, w) against a cache holding only max_context_length rows. T greater than that is a hard shape error: RuntimeError: shape '[16384, 1, 8]' is invalid for input of size 65536 MEASURED on arm 1 -- agpt_debugmodel defaults to ntok=16384 against max_context_length=8192, i.e. two rows. Production is unaffected but the margin is ZERO: agpt_2b and agpt_20b both run ntok == max_context_length == 8192, exactly one row. Any config that raises tokens-per-microbatch above the context length hits this, which is a real constraint that was not written down anywhere. Now it is, in the comment above DEFAULT_CONFIGS. Note emit_positions=True is NOT a workaround for (2). It would take the rope_cache[positions] branch, but it also puts a DeviceMesh into the saved-for-backward set, which AOT autograd rejects -- see its docstring in blendcorpus_builder.py. The two branches are mutually exclusive here.
Appends to the polaris entry rather than competing with it: everything here is downstream of 42f4edf. With the fold in place the smoke got past attention and found three unrelated bugs stacked behind the crash -- TP>1 broken since the pytorch#4121 port (arg names _BLNH vs upstream _TNH), both smoke flags fake since the script's first commit, and a post-fold constraint that tokens-per-microbatch must equal max_context_length, which production meets with zero margin. Also: frameworks/2026.1.0 is on the Aurora validation nodes only and needs LD_LIBRARY_PATH for libglog; eval scores never reached the dashboard for two independent reasons and had no chart even once fixed; and the cached backbone was understating both 20B chains by 910 and 1,431 steps. Four own-goals recorded together because they are one failure mode: trusting an exit code instead of the artifact.
moe/__init__.py carries a second copy of the same wrapper, with the same wrong parameter names and the same comment claiming they match set_gqa_inner_attention_local_map's keys. moe/sharding.py:156 calls that same upstream keyer, imported from the same models.common.decoder_sharding, so its in_dst_shardings are also q_TNH/k_TNH/v_TNH and this forward would assert under TP>1 exactly as the agpt twin did (MEASURED there, smoke 8781623 arm 2). Found by grepping for other `q_BLNH: torch.Tensor` signatures after fixing agpt -- I had verified the fix worked without checking whether it was complete. The 4D assert is deliberately NOT touched. Unlike agpt, this wrapper never got pytorch#4121 fold handling, so it genuinely still expects [B, L, N, H] and its error message ("if the fold-batch-dim token layout landed, this wrapper needs updating") is now a live warning rather than a hypothetical: agpt folds, moe does not. That is a separate piece of work from the naming contract.
…ld too moe's wrapper asserted 4D with the message "if the fold-batch-dim token layout landed, this wrapper needs updating". It landed. Established rather than assumed: moe_debugmodel uses BlendCorpusDataLoader (moe/config_registry.py:115), and 42f4edf folds [B, L] -> [T] unconditionally at the yield (blendcorpus_builder.py:457, no config gate). So moe receives exactly the 3D [T, N, H] tensors agpt does, and agpt has the unflatten while moe had zero -- grep for `num_tokens // seq_len` returns 2 in agpt/__init__.py and 0 here. Straight port of the agpt logic, including the divisibility check. Unflattening rather than transposing in place matters for the same reason it does there: on 3D input a bare transpose(1, 2) swaps N with H instead of L with N, SDPA ACCEPTS it, and the result is a degraded loss curve with no traceback. seq_len comes from agpt's module global via an in-function import, NOT a moe-local copy. trainer.py:443 only ever calls agpt.set_ezpz_max_context_length, so a second global would stay None forever and every moe step would raise the "must call set_ezpz_max_context_length" branch. Verified the binding semantics -- an in-function `from X import G` re-reads on each call, so it sees the value the trainer sets after import time. Imported inside the function because agpt pulls heavy model deps at module scope. NOT yet validated: moe has never reached attention in a smoke (it aborted at config.build on the cp kwarg until 5532e22). Job 8781776 is the first run that can get there.
…fold Smoke 8781776 got moe past config.build (the cp kwarg fix) and into the training loop, where it dies at moe/model.py:123: bsz, seqlen, _ = x.size() ValueError: not enough values to unpack (expected 3, got 2) Post-42f4edfaa the loader folds [B, L] -> [T] unconditionally, so x arrives 2D. agpt is unaffected because agpt/model.py is 50 lines and uses upstream's attention, which pytorch#4121 updated; moe/model.py is 330 lines with a forked MLA forward that upstream never touched, threading bsz/seqlen through four reshapes. Not attempted today, deliberately. Three fixes this session were verified working and turned out incomplete, and a four-reshape layout port written from a traceback rather than a measured shape is that mistake with a worse blast radius -- a wrong-but-plausible reshape has the right shape, SDPA accepts it, and the symptom is a degraded loss curve. Fix direction recorded: measure the real shape first, then port each reshape, with a torch.equal element-order test like the agpt precedent. No MoE production chain exists, so nothing in flight is at risk.
…s nothing Two incompatible fixes were written for the same post-pytorch#4121 error ('token count 1 is not a multiple of max_context_length 8192'): 5b4a818 unflattened attention as [B, L*N, H] and left blendcorpus emitting [B, L]; 42f4edf folded the dataloader to flat [T] to match core. The first is wrong in the worst possible way. Reading dim 0 as batch makes SDPA see a length-1 sequence with 131072 heads. Causal attention over a single token is softmax of one score = 1.0, so the output is exactly v -- the model degrades to a position-wise MLP that still trains and still descends. No traceback, no NaN, nothing to grep for. The obvious check does not catch it: the GQA ratio n_q/n_kv survives the wrong layout (both sides scale by L), so a ratio assertion CONFIRMS the bug. The load-bearing assertion is max|out - v| == 0. 9 tests, CPU-only, no corpus or GPU, 0.8s.
Summary
Fold the language-model batch dimension into the token dimension across the
TorchTitan training stack:
Tis the token budget local to one data-parallel rank (or one pipelinemicrobatch). Dataloaders produce
[T]directly; no[1, T]compatibilitydimension is retained.
Configuration
training.local_batch_sizetraining.num_tokens_per_microbatch_per_dp_ranktraining.global_batch_sizetraining.num_tokens_per_train_steptraining.seq_lentraining.max_context_lengthparallelism.pipeline_parallel_microbatch_sizeparallelism.num_pp_microbatchesThe token count is built bottom-up:
num_pp_microbatchesdefaults to1and is treated as1when PP isdisabled.
num_tokens_per_train_step=-1selects one gradient-accumulationstep; an explicit larger divisible value derives the number of gradient
accumulation steps.
Text dataloaders
Pretraining
fixed-size batches of
num_tokens_per_microbatch_per_dp_ranktokens withoutpadding. Interleaved pretraining concatenates fixed
[max_context_length]weighted draws into[T]instead of stacking[B, L].max_context_lengthboundaries.are dropped; infinite datasets carry residuals across reloops.
SFT
[T]; samples longer thanmax_context_lengthare dropped rather than truncated.fit, the current tail is padded and the complete sample starts in the next
batch.
IGNORE_INDEXlabels, and positions0..pad_len-1. Padding moves from every[L]row to the[T]boundary,generally reducing padding.
IGNORE_INDEX, as before. Prompt tokensremain model context; only their loss is masked.
[T]batch and uses the same packingbehavior.
Multimodal
[T]; only the unused batch tailis padded. Padding uses
pad_idinputs,IGNORE_INDEXlabels, and positionsstarting at zero, resetting every
max_context_lengthtokens.[total_patches, patch_dim]without visual padding;grid_thwpreservesper-item boundaries.
[T, 3]alongside flat[T]textpositions.
Checkpoint state and dataset tests are updated for flat buffers, residuals,
and pending samples.
Model, attention, and loss
[T, D]or
[T, V]throughout the language-model stack.[T, N, H]and[T]. SDPA transposes to itsnative
[N, T, H]layout internally; FlexAttention and external varlenkernels add any required singleton batch only at the kernel boundary.
position resets, preventing cross-document attention.
cu_seqlensfor the same packed boundaries, so itsconvolution and recurrent state reset between documents even when full
attention uses FlexAttention.
[T, V]/[T]and split dimension0.Flux retains
[B, L, D]because its independent diffusion samples rely on thebatch dimension for attention isolation. Its dataloader no longer exposes a
local batch size: it derives the sample count from the exact fixed
text-plus-image token cost and the configured token budget. CP explicitly
shards Flux's
Ldimension.Multimodal and vision
[total_patches, patch_dim]instead of padding them to[num_items, max_patches, patch_dim].grid_thwcarries each visual item's segment length. Block-diagonalFlexAttention masks prevent attention across image/video boundaries.
return packed visual embeddings; the embeddings are scattered directly into
the flat text sequence.
[T]; Qwen3.5 MRoPE positions are[T, 3].Distributed layouts
[T]token batch. Context parallelism thenshards that token dimension during input preparation.
[T]token stream and no longer depends on synthetic former-row boundaries.
spmd_typesannotations represent DP and CP jointly sharding theleading token dimension, e.g.
PartitionSpec(("dp", "cp"), ...).and model-specific sharding plans are updated for the new ranks.
Test plan
Distributed before/after validation
ddbcf97f2d5c5c4ecc0f6ab019a8fb903dca1340--debug.seed=42 --debug.deterministic(never--debug.deterministic_warn_only)Batch-size-1 control
These runs set the local batch size to 1, so before uses
[1, L]and afteruses
[L]. This removes boundaries between multiple rows in one batch, but itdoes not guarantee identical positions for documents longer than
max_context_length: before resets at each physical packed-row boundary,whereas after resets at document-relative
max_context_lengthboundaries. PPis disabled for the former PP configurations because PP=2 with 1F1B requires
at least two microbatches; those models instead use FSDP=4, TP=2, EP=4 on 8
GPUs.
Numerical interpretation
Flux and Qwen3.5 FLA varlen remain bitwise identical for all 10 steps. They
use multimodal/Flux-specific collators rather than the text
ConcatThenSplitpacking path whose position boundaries changed. Inaddition, the Qwen3.5 FLA run has batch size 1 and the old varlen attention
path already flattened
[1, L, ...]to[L, ...]before invoking thekernel, so its effective kernel inputs are unchanged.
The remaining text mismatches come from where positions reset, not from dropping
tokens or changing their order. For example, let
max_context_length=4andlet document
ABCDEFGHIJbegin after tokensXYin the packed stream.Before, physical rows define the contexts:
The boundaries are at the document start and physical-row starts, at
packed-stream offsets
0, 2, 4, 8. After folding, positions reset at thedocument start and every
max_context_lengthtokens relative to thatdocument:
The boundaries are instead at offsets
0, 2, 6, 10. Tokens and labels areunchanged, but RoPE positions and packed-document attention boundaries move,
so bitwise identity is not expected unless these boundaries happen to align.
30B-A3B run with FSDP=2, TP=2, PP=2, EP=4, local batch size 2, and
seq_len=512matches exactly for all 10 steps (loss diff = 0,grad_norm diff = 0).