Skip to content

feat: Create torchtitan/experiments/ezpz - #4

Merged
saforem2 merged 22 commits into
mainfrom
ezpz
Feb 23, 2026
Merged

saforem2 merged 22 commits into
mainfrom
ezpz

Conversation

@saforem2

@saforem2 saforem2 commented Feb 6, 2026 •

Copy link
Copy Markdown
Owner
Copilot Summary

This pull request introduces the foundational implementation for the Llama 3 model integration in the torchtitan/experiments/ezpz/models/llama3 directory. 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:

  • Added llama3 model configuration and argument presets in llama3/__init__.py, including support for different model sizes and attention types, and defined a get_train_spec function for training setup.
  • Introduced TransformerModelArgs and RoPEScalingArgs classes in llama3/model/args.py for flexible model configuration, including sequence length, attention, and RoPE scaling parameters.

Distributed training infrastructure:

  • Implemented parallelize_llama in llama3/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:

  • Added _supported_models set in models/__init__.py to 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:

  • Add an ezpz Trainer and train.py entrypoint that wires torchtitan components into a unified training loop with checkpointing, metrics, and validation.
  • Implement a Llama 3 Transformer model, arguments, and state dict adapter compatible with Hugging Face weights and multiple attention backends.
  • Provide ezpz-specific distributed utilities wrapping TorchTitan parallelism helpers for determinism, AMP, gradient clipping, and process group setup.
  • Add Llama 3 parallelization infrastructure to apply tensor/context parallelism, activation checkpointing, compilation, and FSDP/DDP based on config.
  • Register the ezpz Llama 3 experiment with TrainSpec plus TOML configs for debug and 8B/70B/405B training presets, and extend the ezpz model registry.

Enhancements:

  • Introduce ezpz-specific logging utilities to standardize experiment logging output.

@sourcery-ai

sourcery-ai Bot commented Feb 6, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds 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 loop

sequenceDiagram
    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()
Loading

Class diagram for Llama3 Transformer model and state dict adapter

classDiagram
    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
Loading

File-Level Changes

Change Details Files
Introduce an ezpz-backed Trainer and training entrypoint wired into torchtitan’s TrainSpec pipeline, handling distributed setup, gradient-accumulation, loss normalization, checkpointing, metrics, and optional validation.
  • Create Trainer stateful class that initializes device, distributed meshes (DP/TP/PP/CP), FT manager, tokenizer, dataloader, model via TrainSpec, optimizers, LR schedulers, validator, metrics processor, and checkpoint manager.
  • Implement batch_generator, post_dataloading_process, forward_backward_step, and train_step to support microbatching on CPU, context-parallel input preparation, attention mask construction, AMP, and loss scaling by a global valid-token count.
  • Wire checkpoint load/save, profiling/memory snapshot contexts, semi-sync FT training, validation hooks, PG timeout adjustment, and clean shutdown into Trainer.train and a main() entrypoint using ezpz.setup_torch().
torchtitan/experiments/ezpz/train.py
Add ezpz-specific distributed utilities that wrap/extend torchtitan’s parallel-dimension handling, deterministic seeding, AMP enablement, process-group setup, and gradient clipping with PP/EP awareness.
  • Implement dist_{sum,max,mean} on top of funcol and DTensor, plus TrainContext abstraction that conditionally enables loss_parallel.
  • Provide set_determinism to configure RNGs and flex-attention compilation based on ParallelDims and DebugConfig, including distinct seeds per mesh-dimension.
  • Implement init_distributed/init_fake_mode and set_pg_timeouts to initialize process groups (incl. fake/local_tensor modes) with NCCL flight recorder envs and per-group timeouts.
  • Extend clip_grad_norm_ to correctly aggregate norms across pipeline and expert parallel meshes, including DTensor and EP-aware handling.
torchtitan/experiments/ezpz/distributed/utils.py
Implement a Llama 3-style Transformer model with RoPE scaling, multiple attention backends (sdpa, flex, varlen), and protocol-compliant interfaces for attention masks and initialization.
  • Define RoPE helpers (precompute_freqs_cis, reshape_for_broadcast, apply_rotary_emb) with configurable scaling via RoPEScalingArgs.
  • Implement Attention module supporting GQA, RoPE, and pluggable wrappers (FlexAttentionWrapper, VarlenAttentionWrapper, ScaledDotProductAttentionWrapper) selected by attn_type and attention_masks type.
  • Implement FeedForward, TransformerBlock with depth-scaled init, and Transformer root that manages embeddings, layer stack, RoPE cache, RMSNorm and output head, including init_weights and attention mask helpers for flex/varlen.
  • Expose get_attention_masks that builds BlockMask or VarlenMetadata based on attn_type/attn_mask_type and tokenizer EOS ids, satisfying ModelProtocol expectations.
torchtitan/experiments/ezpz/models/llama3/model/model.py
torchtitan/experiments/ezpz/models/llama3/model/args.py
Add parallelization infrastructure for the Llama 3 model supporting TP, CP, AC, torch.compile, FSDP/HSDP, and DDP, including float8-tensorwise-TP optimizations and loss-normalization-friendly FSDP behavior.
  • Implement parallelize_llama that enforces seq_len divisibility, applies TP (including float8 tensorwise TP path and context-parallel-aware attention), optional AC, per-block torch.compile, and then FSDP/HSDP or DDP based on ParallelDims.
  • Apply TP via parallelize_module on embeddings, norm, output head, and each TransformerBlock (attention/FFN) using Rowwise/Colwise/SequenceParallel and PrepareModuleInput/Float8 variants, with loss-parallel-aware output layout.
  • Implement apply_fsdp/apply_ddp with MixedPrecisionPolicy, optional CPU offload, reshard_after_forward policy that considers PP, and a helper to disable FSDP’s internal gradient division to allow external loss-based scaling.
  • Define op-level SAC allowlist for selective activation checkpointing, plus apply_compile and FSDP gradient-division overrides to work with token-count normalized losses.
torchtitan/experiments/ezpz/models/llama3/infra/parallelize.py
Provide a state-dict adapter to convert between Hugging Face Llama 3 checkpoints and the internal Transformer layout, including RoPE-related Q/K permutations.
  • Define Llama3StateDictAdapter with from_hf_map and to_hf map to translate key patterns between HF and internal naming for embeddings, attention, MLP, norms, and head.
  • Implement HF-compatible _permute/_reverse_permute for Q/K weights to adjust for RoPE implementation differences and apply during state-dict conversion.
  • Handle n_heads/n_kv_heads/head_dim from TransformerModelArgs when permuting K projections for GQA setups.
torchtitan/experiments/ezpz/models/llama3/model/state_dict_adapter.py
Register the Llama 3 experiment in the ezpz experiments stack with model presets, train spec wiring, and preset TOML configs for multiple model sizes.
  • Expose llama3_args dict with debug and 8B/70B/405B variants (and flex/varlen attention options) via TransformerModelArgs, including RoPE scaling and attention mask config.
  • Implement get_train_spec that wires Transformer, llama3_args, parallelize_llama, pipeline_llm, optimizer/scheduler builders, text dataloader, HF tokenizer, CE loss, validator, and Llama3StateDictAdapter into a TrainSpec.
  • Add TOML configs for debug, 8B, 70B, and 405B that set job/metrics/profiling, model flavor and HF asset paths, optimizer/scheduler, training hyperparams, parallelism degrees, checkpointing, compile, AC, float8 options, and validation.
  • Register llama3 (and related names) in the ezpz model registry via _supported_models in models/init.py.
torchtitan/experiments/ezpz/models/llama3/__init__.py
torchtitan/experiments/ezpz/models/llama3/train_configs/debug_model.toml
torchtitan/experiments/ezpz/models/llama3/train_configs/llama3_8b.toml
torchtitan/experiments/ezpz/models/llama3/train_configs/llama3_70b.toml
torchtitan/experiments/ezpz/models/llama3/train_configs/llama3_405b.toml
torchtitan/experiments/ezpz/models/__init__.py
Introduce ezpz-specific logging utilities to standardize logging behavior in experiments and suppress noisy profiler logs.
  • Create init_logger that configures a root logger with rank-aware log level (only rank 0 logs INFO) and a torchtitan-style formatter, and turns down KINETO logging.
  • Add warn_once helper to emit de-duplicated warnings across the process lifetime.
torchtitan/experiments/ezpz/tools/logging.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@saforem2
saforem2 merged commit be78d51 into main Feb 23, 2026
1 of 2 checks passed
@saforem2 saforem2 mentioned this pull request Jun 11, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant