Repository navigation
Conversation
Reviewer's GuideAdds an ezpz-based training entrypoint and distributed utils, and integrates a configurable Llama 3 transformer model (with RoPE, multiple attention backends, FSDP/TP/CP/DP support, and HF state-dict adaptation) into the torchtitan experiments pipeline with preset training configs. Sequence diagram for ezpz Trainer training loopsequenceDiagram
actor User
participant Main as main
participant ConfigManager
participant Trainer
participant DataLoader
participant Model as model_parts
participant LossFn as loss_fn
participant Optimizer as optimizers
participant LR as lr_schedulers
participant CP as CheckpointManager
participant MP as metrics_processor
participant Val as validator
User->>Main: run_script
Main->>ConfigManager: parse_args
ConfigManager-->>Main: JobConfig
Main->>Trainer: __init__(JobConfig)
activate Trainer
Trainer->>Trainer: init_distributed
Trainer->>Trainer: build_tokenizer
Trainer->>Trainer: build_dataloader
Trainer->>Trainer: build model on meta
Trainer->>Trainer: parallelize_fn(model, parallel_dims, job_config)
Trainer->>Trainer: build_optimizers
Trainer->>Trainer: build_lr_schedulers
Trainer->>Trainer: build_metrics_processor
Trainer->>Trainer: build_validator
Trainer->>CP: create CheckpointManager
deactivate Trainer
Main->>Trainer: train()
activate Trainer
Trainer->>CP: load(load_step)
Trainer->>Trainer: batch_generator(dataloader)
loop while should_continue_training
Trainer->>Trainer: train_step(data_iterator)
activate Trainer
Trainer->>Optimizer: zero_grad()
Trainer->>Trainer: collect microbatches on CPU
Trainer->>Trainer: count local_valid_tokens
Trainer->>Trainer: all_reduce to global_valid_tokens
loop microbatches
Trainer->>Trainer: move inputs, labels to device
Trainer->>Trainer: forward_backward_step(..., global_valid_tokens)
activate Trainer
alt pp_enabled
Trainer->>Model: pp_schedule.step(...)
Model-->>Trainer: microbatch_losses
Trainer->>Trainer: aggregate losses
else non_pp
Trainer->>Model: forward(inputs, extra_inputs, extra_kwargs)
Model-->>Trainer: pred
Trainer->>LossFn: loss_fn(pred, labels)
LossFn-->>Trainer: loss_sum
Trainer->>Trainer: loss_sum / global_valid_tokens
Trainer->>Model: backward()
end
deactivate Trainer
end
Trainer->>Trainer: clip_grad_norm_(model_parts.params)
Trainer->>CP: maybe_wait_for_staging
Trainer->>Optimizer: step()
Trainer->>LR: step()
Trainer->>Trainer: aggregate loss over microbatches
Trainer->>Trainer: compute global_avg_loss, global_max_loss
Trainer->>MP: log(step, losses, grad_norm, extra_metrics)
deactivate Trainer
Trainer->>CP: save(step, last_step)
alt validation_enabled and validator.should_validate(step)
Trainer->>Val: validate(model_parts, step)
end
end
deactivate Trainer
Trainer-->>Main: training completed
Main->>Trainer: close()
Main->>dist: destroy_process_group()
Class diagram for Llama3 Transformer model and state dict adapterclassDiagram
class RoPEScalingArgs {
+float scaling_factor
+float low_freq_factor
+float high_freq_factor
+int original_max_position_embeddings
}
class TransformerModelArgs {
+int dim
+int n_layers
+int n_heads
+int~Optional~ n_kv_heads
+int vocab_size
+int multiple_of
+float~Optional~ ffn_dim_multiplier
+float norm_eps
+float rope_theta
+RoPEScalingArgs rope_scaling_args
+int max_seq_len
+bool depth_init
+str attn_type
+str attn_mask_type
+int eos_id
+update_from_config(job_config)
+get_nparams_and_flops(model, seq_len) int int
}
class Attention {
+int n_heads
+int n_kv_heads
+int n_rep
+int head_dim
+bool enable_gqa
+str attn_type
+wq: Linear
+wk: Linear
+wv: Linear
+wo: Linear
+inner_attention: Module
+init_weights(init_std)
+forward(x, freqs_cis, attention_masks, positions)
}
class FeedForward {
+w1: Linear
+w2: Linear
+w3: Linear
+forward(x)
+init_weights(init_std)
}
class TransformerBlock {
+int n_heads
+int dim
+Attention attention
+FeedForward feed_forward
+attention_norm: RMSNorm
+ffn_norm: RMSNorm
+float weight_init_std
+forward(x, freqs_cis, attention_masks, positions)
+init_weights()
}
class Transformer {
+TransformerModelArgs model_args
+int vocab_size
+int n_layers
+tok_embeddings: Embedding
+layers: ModuleDict
+norm: RMSNorm
+output: Linear
+freqs_cis: Tensor
+init_weights(buffer_device)
+_precompute_freqs_cis() Tensor
+_get_flex_attention_masks(input_batch, tokenizer, extra_inputs) AttentionMasksType
+get_attention_masks(input_batch, tokenizer, extra_inputs) AttentionMasksType
+forward(tokens, attention_masks, positions) Tensor
}
class StateDictAdapter {
<<interface>>
+to_hf(state_dict) dict
+from_hf(hf_state_dict) dict
}
class Llama3StateDictAdapter {
+TransformerModelArgs model_args
+str~Optional~ hf_assets_path
+dict from_hf_map
+_permute(w, n_heads_arg, dim1, dim2)
+_reverse_permute(w, n_heads_arg, dim1, dim2)
+to_hf(state_dict) dict
+from_hf(hf_state_dict) dict
}
class TrainSpec {
+model_cls
+model_args
+parallelize_fn
+pipelining_fn
+build_optimizers_fn
+build_lr_schedulers_fn
+build_dataloader_fn
+build_tokenizer_fn
+build_loss_fn
+build_validator_fn
+state_dict_adapter
}
RoPEScalingArgs <.. TransformerModelArgs : used_by
TransformerModelArgs <|-- Transformer : config
TransformerModelArgs <.. TransformerBlock : config
TransformerBlock *-- Attention
TransformerBlock *-- FeedForward
Transformer *-- TransformerBlock : layers
StateDictAdapter <|-- Llama3StateDictAdapter
TransformerModelArgs <.. Llama3StateDictAdapter : config
TrainSpec o-- Transformer : model_cls
TrainSpec o-- TransformerModelArgs : model_args
TrainSpec o-- Llama3StateDictAdapter : state_dict_adapter
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
…s/debug_model.toml`
Updated README.md to improve setup instructions and references.
**They're not wired together so no functionality yet**
Adds:
```bash
torchtitan/experiments/ezpz/{job_config.py,blendcorpus/}
```
Merged
saforem2
added a commit
to nscottnichols/torchtitan
that referenced
this pull request
Jun 11, 2026
The force_load_balance equal-A2A padding branch picked `equal_a2a_split_size = max(input_splits_list)` — a per-rank LOCAL max. With force_load_balance the per-rank input_splits are nearly uniform across ranks but per-rank totals can still differ slightly: rank A: local max = 128 -> pads to 128 * ep_size rows rank B: local max = 130 -> pads to 130 * ep_size rows Both call `all_to_all_single(input, None, None, group=ep_mesh)`, which demands `input.shape[0]` divides evenly by `ep_size`. The two ranks now hand different total row counts to the collective and it hangs (or errors with shape mismatch on a build that validates eagerly). The sibling normal-equal-padding branch already calls `self._global_equal_a2a_split_size(...)` which all-reduces the local max across the EP mesh. Mirror it here. Same helper, no new collective added (the helper does its own all_to_all internally). Cost: one extra mesh-scoped a2a per layer per microbatch, which the normal-padding branch already pays. Addresses review finding saforem2#4 on saforem2#14.
saforem2
added a commit
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
that referenced
this pull request
Aug 31, 2026
…es that were reversed Cleanup of the landing page, plus the auto-commit gate. The page opened well and then buried the reader in May-July per-chain history. Moved into <details>: the 20B-512 unfreeze story, the 20B-256 clone relocation, and six one-off 2026-05 jobs (1024N init crashes, gloo timeouts, the sqrt2-LR fork). The two 20B table rows now carry only current state plus a link. TWO KNOWN ISSUES WERE WRONG, not merely stale, and both would have misdirected someone acting on them: #4 said "SophiaG/Muon broken at 80B -- use AdamW only at 80B". The measured guidance is the opposite. Muon is broken (Newton-Schulz bf16 overflow at dim=9216), but SophiaG runs clean at the production GBS=6144; at that batch the ranking is mano or sophiag, and AdamW is the WORST of the three. #5 said "Pending v2 restart with LR=1e-6". At GBS=6144 the AdamW NaN onset is 1.36e-6 and the usable ceiling ~7e-7, so 1e-6 is PAST the last stable point -- the page was recommending the value that NaNs. Also marked the 2026-07-06 80B <details> as superseded: its "TEAM DECISION OPEN: SophiaG vs mano" is answered differently than it poses, since the blocker is now understood as an optimizer-independent grad-path overflow at dp > ~186. Its LR-finder data is still good, so it stays. Fixed a pre-existing dead in-page anchor (#post-training-stages-cpt--sft--rl; GitHub collapses ' / ' to one hyphen, not two). All 9 anchors now resolve. refresh_all.sh: charts_rc was computed and reported but never consulted by the commit gate, so a run with failing plotters still auto-committed whatever the survivors wrote. That shipped a chart with a data series silently dropped on 08-30 and committed in-progress script edits on 08-31. It now blocks the commit the same way fill_rc does. SKIPPED plotters (cluster-only data, absent off-cluster) deliberately do not block.
saforem2
added a commit
that referenced
this pull request
Sep 16, 2026
The native-DDP preflight could never run. Two independent defects, both on the same call path, both from f5f6ee6: 1. trainer.py passed 6 of the 9 required keyword-only args. Missing: fault_tolerance_enabled, create_seed_checkpoint, optimizer_has_param_groups -- none of which have defaults. Any run with enable_data_parallel_native_ddp=true died with TypeError at trainer construction, before anything else was reached. All three are available at the callsite and now passed: config.fault_tolerance.enable, config.checkpoint.create_seed_checkpoint, and whether config.optimizer declares param_groups. 2. Even fixed, the validator read three fields that do not exist here: parallelism.enable_fsdp_async_all_reduce, pipeline_parallel_fsdp_overlap and pipeline_parallel_fsdp_overlap_policy. Those are on the upstream Aurora MoE branch's CORE ParallelismConfig; ours is EzpzParallelismConfig, which deliberately ports only the five fields our code reads, and core torchtitan never had them. Reading them on a slotted dataclass raised AttributeError, and they sit two gates before the final check, so they were always reached. Now read via getattr with the upstream default. Keeping the checks rather than deleting them means the rejection still fires if those fields are ever added; deleting would silently accept a combination the author explicitly rejected. Verified by calling the validator against REAL objects -- a real ParallelDims built from its own dataclass fields, a real TrainingConfig, and a real EzpzParallelismConfig with the flag on. It now runs every gate and returns a policy ValueError ("native DDP currently requires standard CrossEntropyLoss") instead of TypeError or AttributeError. That is the validator working. Both found by /code-review on my own PR (#17), findings 1 and 2 of 15. I shipped f5f6ee6 saying the hooks were wired and 73824cf saying the flags made the path live. Neither was true, and no test I wrote would have caught it -- they all exercise the expert backends instead. Still open from that review: #3 (wrap_native_ddp runs on a meta-device model before to_empty), #4 (a helper imports _NativeDDPPipelineStage from core, where I moved it out of), and #15 (scale_native_ddp_loss defined but never called, leaving gradients dp_degree x off).
saforem2
added a commit
that referenced
this pull request
Sep 17, 2026
…(review #3, #4, #15) Three remaining findings from /code-review on #17. With b2deeb2 this closes all five blockers on the native-DDP path. #3 -- wrap_native_ddp ran on a META-DEVICE model. The model is built under torch.device("meta") and moved to the real device by to_empty(). The wrap sat BEFORE that, so DDP read next(model.parameters()).device, got device(type='meta') with .index None, computed device_ids=[None], and built reduction buckets over meta storage. to_empty() then reallocated every parameter, invalidating the bucket views DDP had just built with gradient_as_bucket_view=True. Moved after to_empty/init_states and before model.train(). Order is now to_empty -> init_states -> wrap -> train. #4 -- wrap_native_ddp_pipeline_stage imported _NativeDDPPipelineStage from torchtitan.distributed.pipeline_parallel, where it does not exist. ab24c5c moved that class into native_ddp.py as part of the dependency inversion -- it is defined at line 853 of the same file that was importing it from core. ImportError for any PP + native-DDP run, and the isinstance check three lines later could never have matched. Only unreached because the function has no callers. Import dropped; the class resolves from module scope. #15 -- scale_native_ddp_loss was defined and never called, leaving gradients dp_degree x too small. This is the one that would have TRAINED, not crashed. Core's forward_backward_step states it: "The returned loss here is local SUM loss / global_valid_tokens". global_valid_tokens is a cross-DP sum (dist_sum over batch_mesh), so gradients are already globally normalized before backward. DDP's reducer then divides by process_group.size() again. FSDP hits the same thing and solves it with disable_fsdp_gradient_division (agpt/parallelize.py); DDP exposes no equivalent switch, so the compensation has to happen on the loss -- which is precisely what scale_native_ddp_loss exists for. Wired at self.loss_fn construction, which ezpz owns, so it lands before every consumer without touching core's forward_backward_step. Guarded on the flag and on dp_degree > 1. Verified: gradient ratio exactly 4.0 at dp=4 and 8.0 at dp=8, loss VALUE unchanged in both (so reported loss stays comparable across paths), and dp=1 refuses rather than silently no-opping. Not yet run end-to-end with the flag enabled on hardware. These fixes are reasoned from the code plus unit-level verification of the scaling math; the path still needs a real run before anyone should trust it, and that is the next step rather than a claim this commit makes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Copilot Summary
This pull request introduces the foundational implementation for the Llama 3 model integration in the
torchtitan/experiments/ezpz/models/llama3directory. The changes add model configuration, parallelization infrastructure, and training specification for Llama 3, enabling support for multiple variants and advanced distributed training techniques.Llama 3 model integration:
llama3model configuration and argument presets inllama3/__init__.py, including support for different model sizes and attention types, and defined aget_train_specfunction for training setup.TransformerModelArgsandRoPEScalingArgsclasses inllama3/model/args.pyfor flexible model configuration, including sequence length, attention, and RoPE scaling parameters.Distributed training infrastructure:
parallelize_llamainllama3/infra/parallelize.py, which applies tensor parallelism, activation checkpointing, torch.compile, and data parallelism (FSDP/DDP) to the model, supporting advanced parallelism and optimization techniques.Model registry and compatibility:
_supported_modelsset inmodels/__init__.pyto register Llama 3 and other supported models for experiment management.Summary by Sourcery
Introduce an ezpz-based training entrypoint and Llama 3 experiment integration with configurable distributed parallelism and presets for multiple model sizes.
New Features:
Enhancements: