Skip to content

fold batch dim - #4121

Merged
acisseJZhong merged 3 commits into
mainfrom
gh/acisseJZhong/31/head
Aug 21, 2026
Merged

acisseJZhong merged 3 commits into
mainfrom
gh/acisseJZhong/31/head

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fold the language-model batch dimension into the token dimension across the
TorchTitan training stack:

tokens/labels/positions: [B, L]    -> [T]
hidden states:           [B, L, D] -> [T, D]
Q/K/V:                   [B, L, N, H] -> [T, N, H]
logits:                  [B, L, V] -> [T, V]

T is the token budget local to one data-parallel rank (or one pipeline
microbatch). Dataloaders produce [T] directly; no [1, T] compatibility
dimension is retained.

Configuration

Before After Meaning
training.local_batch_size training.num_tokens_per_microbatch_per_dp_rank Token slots processed by each DP rank in one model forward/PP microbatch
training.global_batch_size training.num_tokens_per_train_step Token slots processed globally per train step
training.seq_len training.max_context_length Maximum logical context length used for training
parallelism.pipeline_parallel_microbatch_size parallelism.num_pp_microbatches Number of PP microbatches

The token count is built bottom-up:

num_tokens_per_microbatch_per_dp_rank
    * num_pp_microbatches
    * data_parallel_degree
    * gradient_accumulation_steps
    = num_tokens_per_train_step

num_pp_microbatches defaults to 1 and is treated as 1 when PP is
disabled. num_tokens_per_train_step=-1 selects one gradient-accumulation
step; an explicit larger divisible value derives the number of gradient
accumulation steps.

Text dataloaders

Pretraining

  • Single-source pretraining concatenates document token streams and emits
    fixed-size batches of num_tokens_per_microbatch_per_dp_rank tokens without
    padding. Interleaved pretraining concatenates fixed
    [max_context_length] weighted draws into [T] instead of stacking
    [B, L].
  • Positions reset at document and max_context_length boundaries.
  • Padding behavior is unchanged: no padding is added. Finite residual tokens
    are dropped; infinite datasets carry residuals across reloops.

SFT

  • Chat datasets greedily pack complete samples into [T]; samples longer than
    max_context_length are dropped rather than truncated.
  • A sample never crosses a token-batch/PP-microbatch boundary. If it does not
    fit, the current tail is padded and the complete sample starts in the next
    batch.
  • Unused batch tails use EOS inputs, IGNORE_INDEX labels, and positions
    0..pad_len-1. Padding moves from every [L] row to the [T] boundary,
    generally reducing padding.
  • Prompt and padding labels both use IGNORE_INDEX, as before. Prompt tokens
    remain model context; only their loss is masked.
  • Interleaved SFT selects one source per [T] batch and uses the same packing
    behavior.

Multimodal

  • Complete text samples are concatenated into [T]; only the unused batch tail
    is padded. Padding uses pad_id inputs, IGNORE_INDEX labels, and positions
    starting at zero, resetting every max_context_length tokens.
  • Image/video patches are concatenated into
    [total_patches, patch_dim] without visual padding; grid_thw preserves
    per-item boundaries.
  • Qwen3.5 MRoPE positions are emitted as [T, 3] alongside flat [T] text
    positions.

Checkpoint state and dataset tests are updated for flat buffers, residuals,
and pending samples.

Model, attention, and loss

  • Decoder inputs, embeddings, residuals, MoE/MTP paths, and logits use [T, D]
    or [T, V] throughout the language-model stack.
  • Shared attention and RoPE use [T, N, H] and [T]. SDPA transposes to its
    native [N, T, H] layout internally; FlexAttention and external varlen
    kernels add any required singleton batch only at the kernel boundary.
  • Packed-document attention continues to derive document boundaries from
    position resets, preventing cross-document attention.
  • Qwen3.5 DeltaNet receives cu_seqlens for the same packed boundaries, so its
    convolution and recurrent state reset between documents even when full
    attention uses FlexAttention.
  • Cross entropy, log-probability computation, and chunked loss operate on
    [T, V]/[T] and split dimension 0.

Flux retains [B, L, D] because its independent diffusion samples rely on the
batch 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 L dimension.

Multimodal and vision

  • The multimodal collator concatenates visual patches into
    [total_patches, patch_dim] instead of padding them to
    [num_items, max_patches, patch_dim].
  • grid_thw carries each visual item's segment length. Block-diagonal
    FlexAttention masks prevent attention across image/video boundaries.
  • Qwen3.5, Kimi K2.5, and Muse Glimmer vision paths consume packed patches and
    return packed visual embeddings; the embeddings are scattered directly into
    the flat text sequence.
  • Text positions are [T]; Qwen3.5 MRoPE positions are [T, 3].

Distributed layouts

  • Each DP rank loads its own local [T] token batch. Context parallelism then
    shards that token dimension during input preparation.
  • Head-tail CP load balancing operates directly over the complete flat [T]
    token stream and no longer depends on synthetic former-row boundaries.
  • DTensor and spmd_types annotations represent DP and CP jointly sharding the
    leading token dimension, e.g. PartitionSpec(("dp", "cp"), ...).
  • TP continues to shard feature/head dimensions. MoE, RoPE, attention, loss,
    and model-specific sharding plans are updated for the new ranks.

Test plan

Distributed before/after validation

  • Before: ddbcf97f2d5c5c4ecc0f6ab019a8fb903dca1340
  • After: this PR
  • Hardware: up to 8x H100
  • 10 training steps per run
  • --debug.seed=42 --debug.deterministic (never
    --debug.deterministic_warn_only)
  • Full-precision loss and grad norm read from TensorBoard
  • MFU and tokens/s averaged over steps 3-10
Model Parallelism Local batch size Seq len Max loss / grad diff MFU before -> after Tokens/s before -> after
DeepSeek V3 debug FSDP=2, one loss chunk 8 2,048 3.00e-3 / 1.706e-2 10.7367% -> 10.5087% (-2.12%) 195,578 -> 191,424
GPT-OSS debug FSDP=2, TP=2, PP=2, EP=4, SP/CP off, standard CE 8 (PP microbatch=1) 2,048 3.309e-2 / 4.064e-1 0.62744% -> 0.62571% (-0.28%) 9,186 -> 9,161
Llama3 debug FSDP=2, TP=2, PP=2, SP/CP off, standard CE 8 (PP microbatch=1) 2,048 1.337e-3 / 2.557e-3 0.11799% -> 0.11021% (-6.59%) 16,302 -> 15,227
Llama3 debug DDP=4, CP=2, PTRR FlexAttention, one loss chunk 8 2,048 6.910e-3 / 8.880e-3 1.4891% -> 1.6682% (+12.03%) 205,730 -> 230,473
Llama3 debug FSDP=4, TP=2, SP, standard CE 8 2,048 4.684e-3 / 6.897e-3 1.5165% -> 1.6905% (+11.47%) 209,520 -> 233,560
Qwen3 30B-A3B FSDP=2, TP=2, PP=2, EP=4, SP/CP off, standard CE 2 (PP microbatch=1) 512 1.855 / 20.149 0.42561% -> 0.44176% (+3.79%) 216 -> 225
Qwen3.5 MoE debug FSDP=2, TP=2, PP=2, EP=4 2 (PP microbatch=1) 512 4.272e-3 / 4.900e-2 0.03346% -> 0.03567% (+6.61%) 820 -> 874
Qwen3.5 debug, FLA varlen FSDP=2, TP=2 1 512 0 / 0 0.03666% -> 0.03830% (+4.49%) 871 -> 910
Flux debug HSDP replicate=2, shard=2, CP=2 4 512 0 / 0 0.59687% -> 0.61103% (+2.37%) 7,600 -> 7,780

Batch-size-1 control

These runs set the local batch size to 1, so before uses [1, L] and after
uses [L]. This removes boundaries between multiple rows in one batch, but it
does 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_length boundaries. PP
is 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.

Model Parallelism Local batch size Seq len Max loss / grad diff First differing step MFU before -> after Tokens/s before -> after
DeepSeek V3 debug FSDP=2, one loss chunk 1 2,048 2.584e-4 / 1.029e-3 3 4.8493% -> 4.9618% (+2.32%) 88,334 -> 90,382
GPT-OSS debug FSDP=4, TP=2, EP=4, SP off 1 2,048 8.421e-4 / 1.050e-2 3 0.68245% -> 0.71348% (+4.55%) 9,991 -> 10,446
Llama3 debug DDP=4, CP=2, PTRR FlexAttention, one loss chunk 1 2,048 1.860e-3 / 1.492e-3 3 0.44792% -> 0.49602% (+10.74%) 61,883 -> 68,529
Llama3 debug FSDP=4, TP=2, SP, standard CE 1 2,048 1.655e-3 / 1.505e-3 3 0.49401% -> 0.52393% (+6.06%) 68,250 -> 72,385
Qwen3 30B-A3B FSDP=4, TP=2, EP=4, SP off 1 512 1.601e1 / 1.182e2 2 0.49413% -> 0.51047% (+3.31%) 251 -> 259
Qwen3.5 MoE debug FSDP=4, TP=2, EP=4 1 512 4.511e-4 / 9.885e-4 9 0.04088% -> 0.04566% (+11.70%) 1,002 -> 1,119
Qwen3.5 debug, FLA varlen FSDP=2, TP=2 1 512 0 / 0 None 0.03725% -> 0.03906% (+4.86%) 885 -> 928
Flux debug HSDP replicate=2, shard=2, CP=2 1 512 0 / 0 None 0.19007% -> 0.18634% (-1.96%) 2,420 -> 2,373

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
    ConcatThenSplit packing path whose position boundaries changed. In
    addition, the Qwen3.5 FLA run has batch size 1 and the old varlen attention
    path already flattened [1, L, ...] to [L, ...] before invoking the
    kernel, 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=4 and
    let document ABCDEFGHIJ begin after tokens XY in the packed stream.

    Before, physical rows define the contexts:

    tokens:    [X Y A B] [C D E F] [G H I J]
    positions:  0 1 0 1   0 1 2 3   0 1 2 3
    

    The boundaries are at the document start and physical-row starts, at
    packed-stream offsets 0, 2, 4, 8. After folding, positions reset at the
    document start and every max_context_length tokens relative to that
    document:

    tokens:    X Y | A B C D | E F G H | I J
    positions: 0 1   0 1 2 3   0 1 2 3   0 1
    

    The boundaries are instead at offsets 0, 2, 6, 10. Tokens and labels are
    unchanged, but RoPE positions and packed-document attention boundaries move,
    so bitwise identity is not expected unless these boundaries happen to align.

    • After restoring the old physical-row position boundaries, the Qwen3
      30B-A3B run with FSDP=2, TP=2, PP=2, EP=4, local batch size 2, and
      seq_len=512 matches exactly for all 10 steps (loss diff = 0,
      grad_norm diff = 0).

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 12, 2026
@acisseJZhong
acisseJZhong marked this pull request as draft August 12, 2026 06:10
acisseJZhong added a commit that referenced this pull request Aug 12, 2026
ghstack-source-id: 41ef442
Pull-Request: #4121
acisseJZhong added a commit that referenced this pull request Aug 14, 2026
ghstack-source-id: 65c1f94
Pull-Request: #4121
acisseJZhong added a commit that referenced this pull request Aug 14, 2026
ghstack-source-id: 6847059
Pull-Request: #4121
acisseJZhong added a commit that referenced this pull request Aug 15, 2026
ghstack-source-id: f6549a9
Pull-Request: #4121
acisseJZhong added a commit that referenced this pull request Aug 15, 2026
ghstack-source-id: 6e4ab86
Pull-Request: #4121
acisseJZhong added a commit that referenced this pull request Aug 16, 2026
ghstack-source-id: b79182c
Pull-Request: #4121
acisseJZhong added a commit that referenced this pull request Aug 17, 2026
ghstack-source-id: 9bebf53
Pull-Request: #4121
acisseJZhong added a commit that referenced this pull request Aug 17, 2026
ghstack-source-id: f53ddea
Pull-Request: #4121
@acisseJZhong
acisseJZhong marked this pull request as ready for review August 17, 2026 06:22
@acisseJZhong acisseJZhong changed the title [do not reivew]fold batch dim fold batch dim Aug 17, 2026
acisseJZhong added a commit that referenced this pull request Aug 17, 2026
ghstack-source-id: a2fba00
Pull-Request: #4121
--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 \

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 command was run on old commit, so shouldn't change?

*,
parallelism: ParallelismConfig,
local_batch_size: int,
n_microbatches: int,

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.

Suggested change
n_microbatches: int,
num_microbatches: int,

Comment thread torchtitan/models/deepseek_v3/model.py Outdated
@@ -108,11 +108,12 @@ def forward(

# TODO(pianpwk): same QKV:S(2) unflatten case handled by even sharding

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.

adapt?

Comment thread torchtitan/models/flux/model/layers.py Outdated
from torchtitan.protocols.module import Module, Sequential


class FluxScaledDotProductAttention(ScaledDotProductAttention):

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.

why we need this? SDPA is only used by Flux anyway.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

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.

Can we not change core SDPA? It's not used for any LLM / VLM, but only used for FLUX

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's only used by FLUX and graph trainer

layer.attention.inner_attention = ScaledDotProductAttention.Config()

let me restore core SDPA and let flux uses core SDPA, graph trainer can use a SDPA wrapper that supports flattened input.

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 PR shouldn't change input layout for flux, for which we need full bidirectional attention for each row, so it shouldn't be folded

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread torchtitan/config/configs.py Outdated
@dataclass(kw_only=True, slots=True)
class TrainingConfig:
local_batch_size: int = 8
num_tokens_per_dp_rank: int = 16384

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.

see comment in trainer.py, I wonder if we can put this into dataloader config, just like RL batcher

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sounds good, i will update after @felipemello1 landed his grain PR tonight.

Comment on lines 55 to 61
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)."""

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.

no longer need this BatchConfig, just need a num_tokens

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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].

Comment thread torchtitan/experiments/rl/controller.py Outdated
# 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

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.

we need to improve the original logic

  • trainer.training.max_seq_len is about model capability and rope cache allocation
  • batch_config.seq_len is 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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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.

is this field used?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

used in token dispatcher to calculate required_num_max_tokens_per_rank

Comment thread torchtitan/config/configs.py Outdated
# and the required RoPE cache length.
seq_len: int = 2048
"""Sequence length"""
max_seq_len: int = 2048

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 found this to be confusing, how about

Suggested change
max_seq_len: int = 2048
max_context_length: int = 2048

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this aligns with rope.config's max_seq_len, do we want to update rope as well?

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.

yes

Comment thread torchtitan/models/muse_glimmer/model.py Outdated

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

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 think this function and _inject_vision can be replaced by the common function in common/multimodal.py?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed, please help double check!

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 good. Thank you!

acisseJZhong added a commit that referenced this pull request Aug 18, 2026
ghstack-source-id: ca0c1bf
Pull-Request: #4121
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 22, 2026
…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.
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Aug 22, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 24, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 24, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 24, 2026
…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).
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 24, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 24, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 24, 2026
… 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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
…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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/graph-trainer Run GraphTrainer CI ciflow/h100.8 Trigger H100.8 CI ciflow/rl ciflow/rocm ciflow/rocm-mi300 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.

6 participants