Skip to content

Pull upstream main into ezpz branch - #5

Merged
saforem2 merged 6 commits into
ezpzfrom
main
Feb 26, 2026
Merged

saforem2 merged 6 commits into
ezpzfrom
main

Conversation

@saforem2

@saforem2 saforem2 commented Feb 23, 2026 •

Copy link
Copy Markdown
Owner

This pull request introduces a new mechanism for creating and managing extra NCCL process groups for FSDP (Fully Sharded Data Parallel) and adds a compiler pass to reassign all-gather operations to these extra process groups. This enables separation of communication streams for improved overlap and debugging. The changes also include new integration tests for this functionality, updates to test suites, and minor configuration adjustments.

FSDP Process Group Management and Compiler Passes

  • Added functions in common_utils.py to create extra FSDP NCCL process groups and map original group names to extra group names, allowing for separate CUDA streams for communication. (torchtitan/experiments/compiler_toolkit/common_utils.py)
  • Introduced reassign_to_pg_pass in passes.py, a compiler pass that rewrites all-gather nodes to use a new process group, enabling AG/RS overlap and stream separation. (torchtitan/experiments/compiler_toolkit/passes.py)
  • Updated graph_utils.py to call extra PG creation and reassign passes when "transformer_block_bucketing" is requested, and modified the interface for get_compiler_passes_from_config to accept parallel_dims. (torchtitan/experiments/compiler_toolkit/graph_utils.py) [1] [2]
  • Modified parallelize_llama and parallelize_deepseekv3 to pass parallel_dims to get_compiler_passes_from_config. (torchtitan/experiments/compiler_toolkit/llama3/parallelize.py, torchtitan/experiments/compiler_toolkit/deepseek_v3/parallelize.py) [1] [2]

Testing and Validation

  • Added a comprehensive test suite for the new reassign_to_pg_pass, including tests for rewriting, preservation of node count, no-op behavior, and integration with extra PG creation. (torchtitan/experiments/compiler_toolkit/tests/test_passes.py)

Integration and Configuration Changes

  • Added an experimental, non-blocking DeepSeekV3 auto-bucketing test to the H100 integration test suite. (tests/integration_tests/h100.py)
  • Updated distributed initialization to skip if already initialized, with a warning. (torchtitan/distributed/utils.py)
  • Changed default activation checkpoint RNG state preservation to True for deterministic output. (torchtitan/config/job_config.py)

Miscellaneous

  • Bumped version to 0.2.2. (assets/version.txt)
  • Minor fixes to test commands and dependencies in CI workflows and test scripts. [1] [2] [3] [4] [5]

These changes collectively improve the flexibility and debugging capabilities of FSDP communication in the compiler toolkit, and provide robust testing for the new features.

Summary by Sourcery

Introduce a fault-tolerant training entrypoint, extend the compiler toolkit for FSDP process-group management and all-gather reassignment, and update distributed utilities, RL/FT workflows, attention/activation behavior, and CI/tests to improve robustness and debugging.

New Features:

  • Add a dedicated FTTrainer entrypoint that integrates TorchFT fault-tolerant training with the existing Trainer lifecycle.
  • Introduce an FSDP compiler pass to reassign all-gather operations to separate process groups and supporting utilities to create and track extra FSDP NCCL process groups.
  • Add an experimental DeepSeekV3 SimpleFSDP auto-bucketing H100 integration test.
  • Support direct in-place weight updates for the vLLM-based RL generator without recreating the engine.
  • Enable automatic synthesis of tied output weights when loading unified Qwen3 models from checkpoints.

Bug Fixes:

  • Guard distributed initialization to skip re-init if torch.distributed is already initialized, avoiding configuration conflicts.
  • Correct the scaled dot-product attention interface to use the is_causal argument expected by PyTorch.
  • Ensure activation checkpointing for Flux and the global activation checkpoint config preserve RNG state for deterministic behavior.
  • Update activation checkpoint tests and simple FSDP allowlist to match the current torch_attn varlen attention op schema.
  • Improve profiler error handling by re-raising out-of-memory exceptions after closing the profiler context.

Enhancements:

  • Make the base Trainer tolerant of missing dataloaders in configs by treating the dataloader as optional and asserting at train time.
  • Refine loss synchronization paths to operate directly on the appropriate device meshes without fault-tolerance-specific process groups.
  • Wire parallel_dims into compiler-pass configuration and transformer bucketing flows, automatically inserting the new FSDP PG reassignment pass when requested.
  • Refresh RL unified README and FT TorchFT documentation to reflect the new training entrypoint, install instructions, defaults, and CLI usage.
  • Simplify autoparallel integration tests configuration by removing ROCm-specific skipping where no longer needed.
  • Adjust FT integration tests to use the new FTTrainer entrypoint and LLaMA3 FT model by default.

Build:

  • Pin the lint workflow to a newer revision of the changed-files GitHub Action.

CI:

  • Disable NCCL NVLS in H100 CI runs to mitigate instability and keep uploading artifacts for debugging.
  • Extend the H100 integration test suite configuration to include the new experimental DeepSeekV3 SimpleFSDP auto-bucketing scenario.

Documentation:

  • Update RL unified quick-start documentation for installing vLLM with PyTorch nightly and clarify Qwen3 checkpoint layout and default inference paths.
  • Revise TorchFT documentation to show how to launch multi-replica fault-tolerant jobs using the new FT training entrypoint and configuration flags.

Tests:

  • Add a comprehensive test suite for the new FSDP all-gather process-group reassignment pass, including integration with simple FSDP and activation checkpointing.
  • Update FT integration tests to invoke the FTTrainer-based training file and LLaMA3 FT model configuration.
  • Adjust activation checkpoint unit tests and simple FSDP tests to the latest attention operator signatures.

Chores:

  • Bump the project version number to 0.2.2.

@sourcery-ai

sourcery-ai Bot commented Feb 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces an FT-specific Trainer entrypoint that owns all TorchFT logic, extends the compiler toolkit to manage extra FSDP NCCL process groups and reassign all-gather ops to them, and updates RL/vLLM, distributed utils, activation checkpointing, profiling, and CI/testing to align with new behaviors.

Sequence diagram for transformer_block_bucketing compiler passes with extra FSDP process group

sequenceDiagram
    actor User
    participant JobConfig
    participant Model
    participant ParallelDims
    participant GraphUtils
    participant CommonUtils
    participant Dist
    participant Compiler
    participant fsdp_mesh

    User->>GraphUtils: get_compiler_passes_from_config(Model, JobConfig, ParallelDims)
    GraphUtils->>JobConfig: read compile.passes
    GraphUtils->>ParallelDims: get_mesh(fsdp)
    ParallelDims-->>GraphUtils: fsdp_mesh
    GraphUtils->>CommonUtils: create_extra_fsdp_pg(ParallelDims)
    CommonUtils->>ParallelDims: get_mesh(fsdp)
    ParallelDims-->>CommonUtils: fsdp_mesh
    CommonUtils->>fsdp_mesh: get_group()
    fsdp_mesh-->>CommonUtils: fsdp_pg
    CommonUtils->>Dist: get_process_group_ranks(fsdp_pg)
    Dist-->>CommonUtils: ranks
    CommonUtils->>Dist: new_group(ranks, group_desc=fsdp_extra, use_local_synchronization=True)
    Dist-->>CommonUtils: extra_fsdp_pg
    CommonUtils->>CommonUtils: register original_pg_name->extra_pg_name

    GraphUtils->>CommonUtils: get_extra_fsdp_pg_name(original_pg_name)
    CommonUtils-->>GraphUtils: extra_pg_name
    GraphUtils->>GraphUtils: append reassign_to_pg_pass(source_pg_name, target_pg_name)
    GraphUtils->>GraphUtils: append transformer_block_bucketing pass
    GraphUtils-->>User: compiler_passes

    User->>Compiler: make_compiler_with_passes(compiler_passes)
    Compiler->>Compiler: apply reassign_to_pg_pass
    Compiler->>Compiler: rewrite all_gather group_name fields
    Compiler->>Compiler: apply transformer_block_bucketing
    Compiler-->>User: compiled_model
Loading

Class diagram for FTTrainer and base Trainer refactor

classDiagram
    class Trainer {
        +JobConfig job_config
        +ParallelDims parallel_dims
        +BaseTokenizer tokenizer
        +BaseDataLoader dataloader
        +list~Module~ model_parts
        +Any loss_fn
        +Any optimizers
        +Any lr_schedulers
        +CheckpointManager checkpointer
        +Any metrics_processor
        +Any train_context
        +Any maybe_enable_amp
        +GarbageCollection gc_handler
        +torch.device device
        +int step
        +int ntokens_seen
        +int gradient_accumulation_steps
        +__init__(job_config: JobConfig)
        +init_distributed() ParallelDims
        +train_step(data_iterator: Iterator)
        +train()
        +should_continue_training() bool
        +batch_generator(dataloader: BaseDataLoader) Iterator
    }

    class FTTrainer {
        +FTManager ft_manager
        +ModelArgs model_args
        +__init__(job_config: JobConfig)
        +init_distributed() ParallelDims
        +train_step(data_iterator: Iterator)
        +train()
    }

    class FTManager {
        +bool enabled
        +int replica_id
        +get_dp_info(batch_degree: int, batch_rank: int) tuple
        +maybe_set_all_reduce_hook(model_parts: list~Module~)
        +Any loss_sync_pg
    }

    class CheckpointManager {
        +load(step: int)
        +save(step: int, last_step: bool)
        +maybe_wait_for_staging()
    }

    class ParallelDims {
        +bool dp_enabled
        +bool pp_enabled
        +bool tp_enabled
        +bool ep_enabled
        +bool dp_cp_enabled
        +bool fsdp_enabled
        +get_mesh(name: str) DeviceMesh
        +get_optional_mesh(name: str) DeviceMesh
    }

    class MetricsProcessor {
        +Any device_memory_monitor
        +float num_flops_per_token
        +Any color
        +Any optimizers
        +list~Module~ model_parts
        +should_log(step: int) bool
        +log(step: int, global_avg_loss: float, global_max_loss: float, grad_norm: float, extra_metrics: dict)
    }

    class GarbageCollection {
        +run(step: int)
    }

    Trainer <|-- FTTrainer
    Trainer --> ParallelDims
    Trainer --> CheckpointManager
    Trainer --> MetricsProcessor
    Trainer --> GarbageCollection

    FTTrainer --> FTManager
    FTTrainer ..> MetricsProcessor
    FTTrainer ..> CheckpointManager
Loading

Class diagram for compiler toolkit FSDP extra process groups and AG reassignment

classDiagram
    class GraphUtils {
        +get_compiler_passes_from_config(model: Module, job_config: JobConfig, parallel_dims: ParallelDims) list~Callable~
    }

    class CommonUtils {
        +create_extra_fsdp_pg(parallel_dims: ParallelDims) void
        +get_extra_fsdp_pg_name(original_pg_name: str) str
        -dict~str,str~ _EXTRA_FSDP_PG_REGISTRY
    }

    class ParallelDims {
        +bool fsdp_enabled
        +get_mesh(name: str) DeviceMesh
    }

    class DeviceMesh {
        +get_group() ProcessGroup
    }

    class ProcessGroup {
        +str group_name
    }

    class DistBackend {
        +get_process_group_ranks(pg: ProcessGroup) list~int~
        +new_group(ranks: list~int~, group_desc: str, use_local_synchronization: bool) ProcessGroup
    }

    class ReassignToPgPass {
        +reassign_to_pg_pass(gm: GraphModule, example_inputs, source_pg_name: str, target_pg_name: str) GraphModule
    }

    GraphUtils --> CommonUtils : uses
    GraphUtils --> ParallelDims : reads
    GraphUtils ..> ReassignToPgPass : configures

    CommonUtils --> ParallelDims
    CommonUtils --> DeviceMesh
    DeviceMesh --> ProcessGroup
    CommonUtils --> DistBackend
Loading

File-Level Changes

Change Details Files
Add FT-specific Trainer that encapsulates fault-tolerant training and decouple base Trainer from FT concerns.
  • Implement FTTrainer in experiments/ft/train.py with full init, training loop, TorchFT integration, and custom train_step that tracks global tokens and semi-synchronous training.
  • Remove FTManager and FT-specific logic from the core Trainer in torchtitan/train.py, making dataloader optional and asserting it in train().
  • Wire FT integration tests and docs to use the new FT training module and require model name and TRAIN_FILE overrides.
torchtitan/experiments/ft/train.py
torchtitan/train.py
tests/integration_tests/ft.py
torchtitan/experiments/ft/torchft.md
Extend compiler toolkit to create extra FSDP process groups and reassign all-gather ops to these groups, with tests and wiring for LLaMA3/DeepSeekV3 and H100 CI.
  • Add a reassign_to_pg_pass compiler pass that finds all-gather nodes and rewrites their process-group name, then recompiles the FX graph.
  • Introduce utilities to create extra FSDP NCCL process groups mirroring the FSDP mesh and to look up the extra group name.
  • Update compiler pass configuration to accept ParallelDims, create extra FSDP PGs when transformer_block_bucketing is requested, and insert the reassign pass before bucketing.
  • Wire new pass plumbing into LLaMA3, DeepSeekV3, and SimpleFSDP parallelize paths and add an experimental DeepSeekV3 auto-bucketing H100 integration test.
  • Add comprehensive tests for the reassign pass, including correctness, no-op behavior, and integration with extra process groups.
torchtitan/experiments/compiler_toolkit/passes.py
torchtitan/experiments/compiler_toolkit/common_utils.py
torchtitan/experiments/compiler_toolkit/graph_utils.py
torchtitan/experiments/compiler_toolkit/llama3/parallelize.py
torchtitan/experiments/compiler_toolkit/deepseek_v3/parallelize.py
torchtitan/experiments/simple_fsdp/llama3/parallelize.py
tests/integration_tests/h100.py
torchtitan/experiments/compiler_toolkit/tests/test_passes.py
Refine RL unified vLLM integration to support in-place weight updates and Qwen3 weight tying, and simplify installation/inference UX.
  • Change generator weight update to convert vLLM-compatible state dicts to TorchTitan format and copy tensors directly into the vLLM engine’s model parameters instead of recreating/reloading the engine.
  • Enable weight tying in Qwen3 model args based on HF config and synthesize output.weight from tok_embeddings.weight if missing in checkpoints.
  • Update RL unified README and inference defaults to assume a Qwen3-0.6B checkpoint path, install vLLM via nightly wheels, and remove source-build instructions.
  • Adjust default model-ckpt-path for unified inference to point at the example Qwen3 checkpoint directory.
torchtitan/experiments/rl/unified/actors/generator.py
torchtitan/experiments/rl/unified/models/utils.py
torchtitan/experiments/rl/unified/README.md
torchtitan/experiments/rl/unified/infer.py
Improve distributed, attention, activation checkpointing, profiling, and Flux/Trainer loss aggregation behavior.
  • Guard init_distributed to early-return (with a warning) if torch.distributed is already initialized, avoiding re-init errors.
  • Fix scaled dot-product attention to use the correct is_causal parameter name and pass arguments explicitly.
  • Default activation-checkpoint RNG preservation to True and update Flux activation checkpoint wrappers to preserve RNG state for deterministic outputs.
  • Remove FT process-group usage from loss aggregation paths in the base Trainer and Flux training, relying solely on mesh-based collectives.
  • Ensure profiler context cleans up on OutOfMemory by stepping with exit_ctx=True before re-raising the exception.
torchtitan/distributed/utils.py
torchtitan/models/attention.py
torchtitan/config/job_config.py
torchtitan/models/flux/infra/parallelize.py
torchtitan/models/flux/train.py
torchtitan/tools/profiling.py
Tighten CI/test behavior and small maintenance updates.
  • Add an experimental, non-blocking SimpleFSDP DeepSeekV3 auto-bucketing test to the H100 suite and disable NCCL NVLink Sharp (NVLS) for H100 runs for stability.
  • Allow autoparallel LLaMA3 FSDP+TP integration tests to run on ROCm by removing the skip flag.
  • Update activation checkpoint unit tests to reference the new torch_attn._varlen_attn.default operator signature and extend SimpleFSDP allowlist accordingly.
  • Bump the tj-actions/changed-files GitHub Action revision used in the lint workflow.
  • Adjust logging in Trainer.train() so the final 'Training completed' log only prints on rank 0, matching the FT trainer behavior.
tests/integration_tests/h100.py
.github/workflows/integration_test_8gpu_h100.yaml
torchtitan/experiments/autoparallel/tests/integration_tests.py
tests/unit_tests/test_activation_checkpoint.py
torchtitan/experiments/simple_fsdp/llama3/parallelize.py
.github/workflows/lint.yaml
torchtitan/train.py
assets/version.txt

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 marked this pull request as ready for review February 23, 2026 18:35
Copilot AI review requested due to automatic review settings February 23, 2026 18:35

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 2 issues, and left some high level feedback:

  • FTTrainer duplicates a large amount of initialization and training-loop logic from Trainer; consider factoring shared pieces (model/dataloader setup, optimizer/lr/metrics wiring, validation flow) into reusable helpers or a common base to avoid divergence and ease future changes.
  • In the compiler pass wiring for transformer_block_bucketing, extra_pg_name = get_extra_fsdp_pg_name(fsdp_pg_name) is used without checking for None, and reassign_to_pg_pass assumes node.args[2] exists and is a PG name; adding explicit validation/asserts for the extra PG lookup and the all-gather node argument structure would make failures easier to debug and avoid silently assigning an invalid group.
  • The new _direct_weight_update path in the RL unified generator silently skips unmatched parameter names and does not check for shape mismatches; adding sanity checks or logging for missing/mismatched params would help catch issues when the checkpoint layout or model definition changes.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- FTTrainer duplicates a large amount of initialization and training-loop logic from Trainer; consider factoring shared pieces (model/dataloader setup, optimizer/lr/metrics wiring, validation flow) into reusable helpers or a common base to avoid divergence and ease future changes.
- In the compiler pass wiring for transformer_block_bucketing, `extra_pg_name = get_extra_fsdp_pg_name(fsdp_pg_name)` is used without checking for `None`, and `reassign_to_pg_pass` assumes `node.args[2]` exists and is a PG name; adding explicit validation/asserts for the extra PG lookup and the all-gather node argument structure would make failures easier to debug and avoid silently assigning an invalid group.
- The new `_direct_weight_update` path in the RL unified generator silently skips unmatched parameter names and does not check for shape mismatches; adding sanity checks or logging for missing/mismatched params would help catch issues when the checkpoint layout or model definition changes.

## Individual Comments

### Comment 1
<location path="torchtitan/experiments/compiler_toolkit/graph_utils.py" line_range="435-444" />
<code_context>
                 f"Available compiler passes: {list(AVAILABLE_COMPILER_PASSES.keys())}"
             )
         if pass_name == "transformer_block_bucketing":
+            from torchtitan.experiments.compiler_toolkit.passes import (
+                reassign_to_pg_pass,
+            )
+
+            create_extra_fsdp_pg(parallel_dims)
+            fsdp_mesh = parallel_dims.get_mesh("fsdp")
+            fsdp_pg = fsdp_mesh.get_group()
+            fsdp_pg_name = fsdp_pg.group_name
+            extra_pg_name = get_extra_fsdp_pg_name(fsdp_pg_name)
+            compiler_passes.append(
+                functools.partial(
+                    reassign_to_pg_pass,
+                    source_pg_name=fsdp_pg_name,
+                    target_pg_name=extra_pg_name,
+                )
+            )
</code_context>
<issue_to_address>
**issue:** `extra_pg_name` may be `None`, which would reassign all-gathers to a `None` group name and likely break at runtime.

In the `transformer_block_bucketing` branch, `get_extra_fsdp_pg_name(fsdp_pg_name)` can return `None`, but we still pass `target_pg_name=extra_pg_name` into `reassign_to_pg_pass`. That would rewrite all-gather nodes to use `group_name=None`, likely failing at runtime. Please guard this (e.g., `assert extra_pg_name is not None` or fall back to `fsdp_pg_name` with a warning) to avoid hard-to-debug failures.
</issue_to_address>

### Comment 2
<location path="torchtitan/experiments/ft/train.py" line_range="41" />
<code_context>
 from torchtitan.train import main, Trainer


 class FTTrainer(Trainer):
+    ft_manager: FTManager | None = None
+
</code_context>
<issue_to_address>
**issue (complexity):** Consider refactoring the new FTTrainer into smaller, well-named helper methods so its initialization, training loop, and FT-specific logic are easier to read and maintain without changing behavior.

The new `FTTrainer` significantly increases complexity via a very large `__init__`, custom `train` and `train_step` that re-implement a lot of base `Trainer` behavior, and dense loss-sync/metrics logic. You can keep all behavior while making this much easier to follow by:

---

### 1. Split `__init__` into focused helpers

The ~300-line constructor mixes: device/distributed setup, FT wiring, dataloader/model/optim/checkpoint/validation setup, logging, and metrics. Extracting helpers will make it much easier to understand and test without changing behavior.

For example:

```python
class FTTrainer(Trainer):
    @record
    def __init__(self, job_config: JobConfig):
        torch._C._log_api_usage_once("torchtitan.train")
        self.job_config = job_config

        logger.info(f"Starting job: {job_config.job.description}")
        if job_config.experimental.custom_import:
            importlib.import_module(job_config.experimental.custom_import)

        self._init_device_and_distributed()
        self._init_ft_and_gc()
        self._build_train_spec_and_dataloader()
        self._build_model_and_parallelism()
        self._build_optim_and_schedulers()
        self._init_checkpointing()
        self._init_validation()
        self._log_init_summary()
```

Then lift existing logic into these methods in small, mostly-move-only chunks:

```python
def _init_device_and_distributed(self) -> None:
    device_module, device_type = utils.device_module, utils.device_type
    self.device = torch.device(f"{device_type}:{int(os.environ['LOCAL_RANK'])}")
    device_module.set_device(self.device)
    self.parallel_dims = parallel_dims = self.init_distributed()
    self.job_config.maybe_log()
    # determinism / meshes stay here

def _init_ft_and_gc(self) -> None:
    parallel_dims = self.parallel_dims
    job_config = self.job_config

    if parallel_dims.dp_enabled:
        batch_mesh = parallel_dims.get_mesh("batch")
        batch_degree, batch_rank = batch_mesh.size(), batch_mesh.get_local_rank()
    else:
        batch_degree, batch_rank = 1, 0

    self.ft_manager = FTManager(job_config.fault_tolerance)
    batch_degree, batch_rank = self.ft_manager.get_dp_info(batch_degree, batch_rank)
    self._batch_degree = batch_degree
    self._batch_rank = batch_rank

    self.gc_handler = utils.GarbageCollection(
        gc_freq=job_config.training.gc_freq,
        debug=job_config.training.gc_debug,
    )
```

Same pattern for:

- `_build_train_spec_and_dataloader` (train_spec, tokenizer, dataloader, loss_fn, metrics_processor, grad accumulation checks)
- `_build_model_and_parallelism` (meta init, converters, PP/TP/DP parallelization, init_weights, `self.model_parts`, `ensure_pp_loss_visible`, FT all-reduce hook, device memory logging)
- `_build_optim_and_schedulers` (optimizers, schedulers, post_optimizer_hook, wiring into metrics_processor)
- `_init_checkpointing` (step/ntokens_seen, CheckpointManager, train_context, maybe_enable_amp)
- `_init_validation` (validator construction if enabled)
- `_log_init_summary` (final training configuration log)

This keeps the functionality intact but makes `__init__` navigable and reduces cognitive load.

If the base `Trainer.__init__` already does some of this (e.g., generic model/dataloader/optimizer setup), consider calling `super().__init__(job_config)` and only overriding the FT-specific parts (FTManager wiring, loss sync, semi-sync context). If that’s not currently possible, the above extraction still makes future composition easier.

---

### 2. Decompose `train_step` into smaller operations

`train_step` currently mixes microbatch collection, DP token reductions, forward/backward, grad clipping/step, FT loss sync, and metrics logging in a single method. Breaking this out will make the FT-specific logic much clearer:

```python
def train_step(
    self,
    data_iterator: Iterator[tuple[dict[str, torch.Tensor], torch.Tensor]],
) -> None:
    self.optimizers.zero_grad()
    lr = self.lr_schedulers.schedulers[0].get_last_lr()[0]

    microbatches, local_valid_tokens = self._collect_microbatches(data_iterator)
    global_valid_tokens = self._compute_global_valid_tokens(local_valid_tokens)
    accumulated_losses, grad_norm = self._run_microbatches_and_step(
        microbatches, global_valid_tokens
    )

    if not self.metrics_processor.should_log(self.step):
        return

    global_avg_loss, global_max_loss, global_ntokens_seen = (
        self._compute_ft_loss_metrics(
            loss=torch.sum(torch.stack(accumulated_losses)),
            local_valid_tokens=local_valid_tokens,
            global_valid_tokens=global_valid_tokens,
        )
    )
    self._log_step_metrics(
        lr=lr,
        grad_norm=grad_norm,
        global_avg_loss=global_avg_loss,
        global_max_loss=global_max_loss,
        global_ntokens_seen=global_ntokens_seen,
    )
```

Example implementations moved directly from existing code:

```python
def _collect_microbatches(
    self,
    data_iterator: Iterator[tuple[dict[str, torch.Tensor], torch.Tensor]],
) -> tuple[list[tuple[dict[str, torch.Tensor], torch.Tensor]], torch.Tensor]:
    microbatches: list[tuple[dict[str, torch.Tensor], torch.Tensor]] = []
    local_valid_tokens = torch.tensor(0, dtype=torch.int64)
    for _ in range(self.gradient_accumulation_steps):
        input_dict, labels = next(data_iterator)
        local_valid_tokens += (labels != IGNORE_INDEX).sum()
        microbatches.append((input_dict, labels))
    return microbatches, local_valid_tokens

def _compute_global_valid_tokens(self, local_valid_tokens: torch.Tensor) -> torch.Tensor:
    local_valid_tokens = local_valid_tokens.to(self.device)
    if self.parallel_dims.dp_enabled:
        batch_mesh = self.parallel_dims.get_mesh("batch")
        return dist_utils.dist_sum(local_valid_tokens, batch_mesh)
    return local_valid_tokens.float()
```

And:

```python
def _run_microbatches_and_step(
    self,
    microbatches: list[tuple[dict[str, torch.Tensor], torch.Tensor]],
    global_valid_tokens: torch.Tensor,
) -> tuple[list[torch.Tensor], torch.Tensor]:
    accumulated_losses: list[torch.Tensor] = []
    for input_dict, labels in microbatches:
        for k, v in input_dict.items():
            if isinstance(v, torch.Tensor):
                input_dict[k] = v.to(self.device)
        labels = labels.to(self.device)
        loss = self.forward_backward_step(
            input_dict=input_dict,
            labels=labels,
            global_valid_tokens=global_valid_tokens,
        )
        accumulated_losses.append(loss.detach())

    grad_norm = dist_utils.clip_grad_norm_(
        [p for m in self.model_parts for p in m.parameters()],
        self.job_config.training.max_norm,
        foreach=True,
        pp_mesh=self.parallel_dims.get_optional_mesh("pp"),
        ep_enabled=self.parallel_dims.ep_enabled,
    )
    self.checkpointer.maybe_wait_for_staging()
    self.optimizers.step()
    self.lr_schedulers.step()
    return accumulated_losses, grad_norm
```

---

### 3. Move FT loss synchronization into a utility method

The `if parallel_dims.dp_cp_enabled:` block mixes loss math, distributed ops, and metric preparation. Moving it behind a helper keeps `train_step` readable and makes the FT logic explicit:

```python
def _compute_ft_loss_metrics(
    self,
    loss: torch.Tensor,
    local_valid_tokens: torch.Tensor,
    global_valid_tokens: torch.Tensor,
) -> tuple[float, float, int]:
    parallel_dims = self.parallel_dims

    if parallel_dims.dp_cp_enabled:
        loss = loss.detach()
        ft_pg = self.ft_manager.loss_sync_pg
        loss_mesh = parallel_dims.get_optional_mesh("loss")

        local_avg_loss = loss * global_valid_tokens / local_valid_tokens
        global_avg_loss = dist_utils.dist_sum(loss, loss_mesh, ft_pg)
        global_max_loss = dist_utils.dist_max(local_avg_loss, loss_mesh, ft_pg)
        global_ntokens_seen = dist_utils.dist_sum(
            torch.tensor(self.ntokens_seen, dtype=torch.int64, device=self.device),
            loss_mesh,
            ft_pg,
        )
        return (
            float(global_avg_loss),
            float(global_max_loss),
            int(global_ntokens_seen.item()),
        )

    return float(loss.detach().item()), float(loss.detach().item()), self.ntokens_seen
```

And a small logger helper:

```python
def _log_step_metrics(
    self,
    lr: float,
    grad_norm: torch.Tensor,
    global_avg_loss: float,
    global_max_loss: float,
    global_ntokens_seen: int,
) -> None:
    extra_metrics = {
        "n_tokens_seen": global_ntokens_seen,
        "lr": lr,
    }
    self.metrics_processor.log(
        self.step,
        global_avg_loss,
        global_max_loss,
        grad_norm.item(),
        extra_metrics=extra_metrics,
    )
```

---

### 4. Extract a training context helper for `train`

The `with` in `train` composes profiling, memory snapshots, and semi-sync in one expression. Extracting a context builder keeps `train` focused on the loop:

```python
def train(self):
    job_config = self.job_config
    self.checkpointer.load(step=job_config.checkpoint.load_step)
    logger.info(f"Training starts at step {self.step + 1}")

    with self._training_context() as (torch_profiler, memory_profiler):
        data_iterator = self.batch_generator(self.dataloader)
        while self.should_continue_training():
            self.step += 1
            self.gc_handler.run(self.step)
            try:
                self.train_step(data_iterator)
            except DataloaderExhaustedError:
                logger.warning("Ran out of data; last step was canceled.")
                break

            self.checkpointer.save(
                self.step, last_step=(self.step == job_config.training.steps)
            )
            self._maybe_validate()
            self._step_profilers(torch_profiler, memory_profiler)
            self._maybe_set_train_pg_timeout()
    self._finalize_training()
```

With small extractions:

```python
@contextlib.contextmanager
def _training_context(self):
    job_config = self.job_config
    leaf_folder = (
        "" if not self.ft_manager.enabled else f"replica_{self.ft_manager.replica_id}"
    )
    with (
        maybe_enable_profiling(
            job_config.profiling,
            global_step=self.step,
            base_folder=job_config.job.dump_folder,
            leaf_folder=leaf_folder,
        ) as torch_profiler,
        maybe_enable_memory_snapshot(
            job_config.profiling,
            global_step=self.step,
            base_folder=job_config.job.dump_folder,
            leaf_folder=leaf_folder,
        ) as memory_profiler,
        maybe_semi_sync_training(
            job_config.fault_tolerance,
            ft_manager=self.ft_manager,
            model=self.model_parts[0],
            n_layers=getattr(self.model_args, "n_layers", 0),
            optimizer=self.optimizers,
            fragment_fn=getattr(self.train_spec, "fragment_fn", None),
        ),
    ):
        yield torch_profiler, memory_profiler
```

And helper methods for validation, profiler stepping, timeout adjustment, and final sleep/logging, reusing your existing logic.

---

These changes are all refactors (no behavior changes required) and should materially reduce cognitive load:

- `__init__` becomes a high-level sequence of well-named steps.
- `train_step` becomes a composition of clear operations.
- FT-specific loss sync and semi-sync contexts are encapsulated behind helpers, making it easier to evolve the FT feature without touching the entire training loop.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 435 to +444
if pass_name == "transformer_block_bucketing":
from torchtitan.experiments.compiler_toolkit.passes import (
reassign_to_pg_pass,
)

create_extra_fsdp_pg(parallel_dims)
fsdp_mesh = parallel_dims.get_mesh("fsdp")
fsdp_pg = fsdp_mesh.get_group()
fsdp_pg_name = fsdp_pg.group_name
extra_pg_name = get_extra_fsdp_pg_name(fsdp_pg_name)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue: extra_pg_name may be None, which would reassign all-gathers to a None group name and likely break at runtime.

In the transformer_block_bucketing branch, get_extra_fsdp_pg_name(fsdp_pg_name) can return None, but we still pass target_pg_name=extra_pg_name into reassign_to_pg_pass. That would rewrite all-gather nodes to use group_name=None, likely failing at runtime. Please guard this (e.g., assert extra_pg_name is not None or fall back to fsdp_pg_name with a warning) to avoid hard-to-debug failures.

Comment thread torchtitan/experiments/ft/train.py Outdated
from torchtitan.train import main, Trainer


class FTTrainer(Trainer):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (complexity): Consider refactoring the new FTTrainer into smaller, well-named helper methods so its initialization, training loop, and FT-specific logic are easier to read and maintain without changing behavior.

The new FTTrainer significantly increases complexity via a very large __init__, custom train and train_step that re-implement a lot of base Trainer behavior, and dense loss-sync/metrics logic. You can keep all behavior while making this much easier to follow by:


1. Split __init__ into focused helpers

The ~300-line constructor mixes: device/distributed setup, FT wiring, dataloader/model/optim/checkpoint/validation setup, logging, and metrics. Extracting helpers will make it much easier to understand and test without changing behavior.

For example:

class FTTrainer(Trainer):
    @record
    def __init__(self, job_config: JobConfig):
        torch._C._log_api_usage_once("torchtitan.train")
        self.job_config = job_config

        logger.info(f"Starting job: {job_config.job.description}")
        if job_config.experimental.custom_import:
            importlib.import_module(job_config.experimental.custom_import)

        self._init_device_and_distributed()
        self._init_ft_and_gc()
        self._build_train_spec_and_dataloader()
        self._build_model_and_parallelism()
        self._build_optim_and_schedulers()
        self._init_checkpointing()
        self._init_validation()
        self._log_init_summary()

Then lift existing logic into these methods in small, mostly-move-only chunks:

def _init_device_and_distributed(self) -> None:
    device_module, device_type = utils.device_module, utils.device_type
    self.device = torch.device(f"{device_type}:{int(os.environ['LOCAL_RANK'])}")
    device_module.set_device(self.device)
    self.parallel_dims = parallel_dims = self.init_distributed()
    self.job_config.maybe_log()
    # determinism / meshes stay here

def _init_ft_and_gc(self) -> None:
    parallel_dims = self.parallel_dims
    job_config = self.job_config

    if parallel_dims.dp_enabled:
        batch_mesh = parallel_dims.get_mesh("batch")
        batch_degree, batch_rank = batch_mesh.size(), batch_mesh.get_local_rank()
    else:
        batch_degree, batch_rank = 1, 0

    self.ft_manager = FTManager(job_config.fault_tolerance)
    batch_degree, batch_rank = self.ft_manager.get_dp_info(batch_degree, batch_rank)
    self._batch_degree = batch_degree
    self._batch_rank = batch_rank

    self.gc_handler = utils.GarbageCollection(
        gc_freq=job_config.training.gc_freq,
        debug=job_config.training.gc_debug,
    )

Same pattern for:

  • _build_train_spec_and_dataloader (train_spec, tokenizer, dataloader, loss_fn, metrics_processor, grad accumulation checks)
  • _build_model_and_parallelism (meta init, converters, PP/TP/DP parallelization, init_weights, self.model_parts, ensure_pp_loss_visible, FT all-reduce hook, device memory logging)
  • _build_optim_and_schedulers (optimizers, schedulers, post_optimizer_hook, wiring into metrics_processor)
  • _init_checkpointing (step/ntokens_seen, CheckpointManager, train_context, maybe_enable_amp)
  • _init_validation (validator construction if enabled)
  • _log_init_summary (final training configuration log)

This keeps the functionality intact but makes __init__ navigable and reduces cognitive load.

If the base Trainer.__init__ already does some of this (e.g., generic model/dataloader/optimizer setup), consider calling super().__init__(job_config) and only overriding the FT-specific parts (FTManager wiring, loss sync, semi-sync context). If that’s not currently possible, the above extraction still makes future composition easier.


2. Decompose train_step into smaller operations

train_step currently mixes microbatch collection, DP token reductions, forward/backward, grad clipping/step, FT loss sync, and metrics logging in a single method. Breaking this out will make the FT-specific logic much clearer:

def train_step(
    self,
    data_iterator: Iterator[tuple[dict[str, torch.Tensor], torch.Tensor]],
) -> None:
    self.optimizers.zero_grad()
    lr = self.lr_schedulers.schedulers[0].get_last_lr()[0]

    microbatches, local_valid_tokens = self._collect_microbatches(data_iterator)
    global_valid_tokens = self._compute_global_valid_tokens(local_valid_tokens)
    accumulated_losses, grad_norm = self._run_microbatches_and_step(
        microbatches, global_valid_tokens
    )

    if not self.metrics_processor.should_log(self.step):
        return

    global_avg_loss, global_max_loss, global_ntokens_seen = (
        self._compute_ft_loss_metrics(
            loss=torch.sum(torch.stack(accumulated_losses)),
            local_valid_tokens=local_valid_tokens,
            global_valid_tokens=global_valid_tokens,
        )
    )
    self._log_step_metrics(
        lr=lr,
        grad_norm=grad_norm,
        global_avg_loss=global_avg_loss,
        global_max_loss=global_max_loss,
        global_ntokens_seen=global_ntokens_seen,
    )

Example implementations moved directly from existing code:

def _collect_microbatches(
    self,
    data_iterator: Iterator[tuple[dict[str, torch.Tensor], torch.Tensor]],
) -> tuple[list[tuple[dict[str, torch.Tensor], torch.Tensor]], torch.Tensor]:
    microbatches: list[tuple[dict[str, torch.Tensor], torch.Tensor]] = []
    local_valid_tokens = torch.tensor(0, dtype=torch.int64)
    for _ in range(self.gradient_accumulation_steps):
        input_dict, labels = next(data_iterator)
        local_valid_tokens += (labels != IGNORE_INDEX).sum()
        microbatches.append((input_dict, labels))
    return microbatches, local_valid_tokens

def _compute_global_valid_tokens(self, local_valid_tokens: torch.Tensor) -> torch.Tensor:
    local_valid_tokens = local_valid_tokens.to(self.device)
    if self.parallel_dims.dp_enabled:
        batch_mesh = self.parallel_dims.get_mesh("batch")
        return dist_utils.dist_sum(local_valid_tokens, batch_mesh)
    return local_valid_tokens.float()

And:

def _run_microbatches_and_step(
    self,
    microbatches: list[tuple[dict[str, torch.Tensor], torch.Tensor]],
    global_valid_tokens: torch.Tensor,
) -> tuple[list[torch.Tensor], torch.Tensor]:
    accumulated_losses: list[torch.Tensor] = []
    for input_dict, labels in microbatches:
        for k, v in input_dict.items():
            if isinstance(v, torch.Tensor):
                input_dict[k] = v.to(self.device)
        labels = labels.to(self.device)
        loss = self.forward_backward_step(
            input_dict=input_dict,
            labels=labels,
            global_valid_tokens=global_valid_tokens,
        )
        accumulated_losses.append(loss.detach())

    grad_norm = dist_utils.clip_grad_norm_(
        [p for m in self.model_parts for p in m.parameters()],
        self.job_config.training.max_norm,
        foreach=True,
        pp_mesh=self.parallel_dims.get_optional_mesh("pp"),
        ep_enabled=self.parallel_dims.ep_enabled,
    )
    self.checkpointer.maybe_wait_for_staging()
    self.optimizers.step()
    self.lr_schedulers.step()
    return accumulated_losses, grad_norm

3. Move FT loss synchronization into a utility method

The if parallel_dims.dp_cp_enabled: block mixes loss math, distributed ops, and metric preparation. Moving it behind a helper keeps train_step readable and makes the FT logic explicit:

def _compute_ft_loss_metrics(
    self,
    loss: torch.Tensor,
    local_valid_tokens: torch.Tensor,
    global_valid_tokens: torch.Tensor,
) -> tuple[float, float, int]:
    parallel_dims = self.parallel_dims

    if parallel_dims.dp_cp_enabled:
        loss = loss.detach()
        ft_pg = self.ft_manager.loss_sync_pg
        loss_mesh = parallel_dims.get_optional_mesh("loss")

        local_avg_loss = loss * global_valid_tokens / local_valid_tokens
        global_avg_loss = dist_utils.dist_sum(loss, loss_mesh, ft_pg)
        global_max_loss = dist_utils.dist_max(local_avg_loss, loss_mesh, ft_pg)
        global_ntokens_seen = dist_utils.dist_sum(
            torch.tensor(self.ntokens_seen, dtype=torch.int64, device=self.device),
            loss_mesh,
            ft_pg,
        )
        return (
            float(global_avg_loss),
            float(global_max_loss),
            int(global_ntokens_seen.item()),
        )

    return float(loss.detach().item()), float(loss.detach().item()), self.ntokens_seen

And a small logger helper:

def _log_step_metrics(
    self,
    lr: float,
    grad_norm: torch.Tensor,
    global_avg_loss: float,
    global_max_loss: float,
    global_ntokens_seen: int,
) -> None:
    extra_metrics = {
        "n_tokens_seen": global_ntokens_seen,
        "lr": lr,
    }
    self.metrics_processor.log(
        self.step,
        global_avg_loss,
        global_max_loss,
        grad_norm.item(),
        extra_metrics=extra_metrics,
    )

4. Extract a training context helper for train

The with in train composes profiling, memory snapshots, and semi-sync in one expression. Extracting a context builder keeps train focused on the loop:

def train(self):
    job_config = self.job_config
    self.checkpointer.load(step=job_config.checkpoint.load_step)
    logger.info(f"Training starts at step {self.step + 1}")

    with self._training_context() as (torch_profiler, memory_profiler):
        data_iterator = self.batch_generator(self.dataloader)
        while self.should_continue_training():
            self.step += 1
            self.gc_handler.run(self.step)
            try:
                self.train_step(data_iterator)
            except DataloaderExhaustedError:
                logger.warning("Ran out of data; last step was canceled.")
                break

            self.checkpointer.save(
                self.step, last_step=(self.step == job_config.training.steps)
            )
            self._maybe_validate()
            self._step_profilers(torch_profiler, memory_profiler)
            self._maybe_set_train_pg_timeout()
    self._finalize_training()

With small extractions:

@contextlib.contextmanager
def _training_context(self):
    job_config = self.job_config
    leaf_folder = (
        "" if not self.ft_manager.enabled else f"replica_{self.ft_manager.replica_id}"
    )
    with (
        maybe_enable_profiling(
            job_config.profiling,
            global_step=self.step,
            base_folder=job_config.job.dump_folder,
            leaf_folder=leaf_folder,
        ) as torch_profiler,
        maybe_enable_memory_snapshot(
            job_config.profiling,
            global_step=self.step,
            base_folder=job_config.job.dump_folder,
            leaf_folder=leaf_folder,
        ) as memory_profiler,
        maybe_semi_sync_training(
            job_config.fault_tolerance,
            ft_manager=self.ft_manager,
            model=self.model_parts[0],
            n_layers=getattr(self.model_args, "n_layers", 0),
            optimizer=self.optimizers,
            fragment_fn=getattr(self.train_spec, "fragment_fn", None),
        ),
    ):
        yield torch_profiler, memory_profiler

And helper methods for validation, profiler stepping, timeout adjustment, and final sleep/logging, reusing your existing logic.


These changes are all refactors (no behavior changes required) and should materially reduce cognitive load:

  • __init__ becomes a high-level sequence of well-named steps.
  • train_step becomes a composition of clear operations.
  • FT-specific loss sync and semi-sync contexts are encapsulated behind helpers, making it easier to evolve the FT feature without touching the entire training loop.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This pull request refactors fault-tolerance (FT) support by extracting it from the base Trainer class into a dedicated FTTrainer subclass, introduces a new compiler pass for FSDP process group management to enable AG/RS stream separation, and includes various bug fixes and improvements across RL integration, attention operations, and testing infrastructure.

Changes:

  • Decoupled fault-tolerance logic from base Trainer by creating FTTrainer in experiments/ft/train.py, making the base Trainer more generic and optional-dataloader-aware
  • Added reassign_to_pg_pass compiler pass with extra FSDP process group creation utilities to enable separate CUDA streams for all-gather operations
  • Fixed attention parameter naming (is_casual → is_causal), operator names for varlen_attn, and improved RL unified vLLM weight update mechanism with direct parameter copying

Reviewed changes

Copilot reviewed 27 out of 27 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
torchtitan/train.py Removed FT manager dependencies; made dataloader optional with runtime assertion
torchtitan/tools/profiling.py Added raise statement to re-raise OOM errors after profiler cleanup
torchtitan/models/flux/train.py Removed ft_pg parameter from loss aggregation calls
torchtitan/models/flux/infra/parallelize.py Changed preserve_rng_state to True for deterministic activation checkpointing
torchtitan/models/attention.py Fixed parameter name from is_casual to is_causal
torchtitan/experiments/simple_fsdp/llama3/parallelize.py Updated operator name to include .default suffix
torchtitan/experiments/rl/unified/models/utils.py Added weight tying support for Qwen3 checkpoints
torchtitan/experiments/rl/unified/infer.py Updated default checkpoint path to include model subfolder
torchtitan/experiments/rl/unified/actors/generator.py Replaced reload_weights with direct parameter copy for vLLM engine
torchtitan/experiments/rl/unified/README.md Updated installation instructions to use pre-built vLLM wheels
torchtitan/experiments/ft/train.py New FTTrainer implementation with FT-specific logic
torchtitan/experiments/ft/torchft.md Updated documentation to reference new FT training entrypoint
torchtitan/experiments/compiler_toolkit/tests/test_passes.py Added comprehensive test suite for reassign_to_pg_pass
torchtitan/experiments/compiler_toolkit/passes.py Implemented reassign_to_pg_pass for all-gather PG reassignment
torchtitan/experiments/compiler_toolkit/llama3/parallelize.py Added parallel_dims parameter to get_compiler_passes_from_config call
torchtitan/experiments/compiler_toolkit/graph_utils.py Added extra PG creation and reassign pass injection for transformer_block_bucketing
torchtitan/experiments/compiler_toolkit/deepseek_v3/parallelize.py Added parallel_dims parameter to get_compiler_passes_from_config call
torchtitan/experiments/compiler_toolkit/common_utils.py Added utilities to create and track extra FSDP NCCL process groups
torchtitan/experiments/autoparallel/tests/integration_tests.py Removed skip_rocm_test flag for autoparallel FSDP+TP test
torchtitan/distributed/utils.py Added check to skip distributed initialization if already initialized
torchtitan/config/job_config.py Changed default preserve_rng_state to True
tests/unit_tests/test_activation_checkpoint.py Updated operator name to include .default suffix
tests/integration_tests/h100.py Added experimental non-blocking DeepSeekV3 auto-bucketing test
tests/integration_tests/ft.py Added TRAIN_FILE and model name to FT integration tests
assets/version.txt Bumped version to 0.2.2
.github/workflows/lint.yaml Updated tj-actions/changed-files version
.github/workflows/integration_test_8gpu_h100.yaml Disabled NCCL NVLS and enabled CPP stacktraces

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread torchtitan/train.py Outdated
Comment on lines 126 to 135
self.dataloader = (
self.train_spec.build_dataloader_fn(
dp_world_size=batch_degree,
dp_rank=batch_rank,
tokenizer=self.tokenizer,
job_config=job_config,
)
if self.train_spec.build_dataloader_fn is not None
else None
)

Copilot AI Feb 23, 2026

Copy link

Choose a reason for hiding this comment

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

The dataloader is now optional in the Trainer class, but the TrainSpec.build_dataloader_fn field is not marked as optional (DataLoaderBuilder | None). This could cause type checking issues when a TrainSpec is created with build_dataloader_fn set to None, even though the runtime code checks for None. Consider updating the TrainSpec dataclass to make build_dataloader_fn optional: build_dataloader_fn: DataLoaderBuilder | None

Copilot uses AI. Check for mistakes.
@saforem2
saforem2 merged commit b167df0 into ezpz Feb 26, 2026
1 check 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
Two distributed-hang risks fixed by making both per-rank decisions
agree globally across the EP mesh:

(1) `_can_use_equal_a2a_splits` returned a local-only min!=max bool.
    Different ranks could decide differently (rank A's splits
    uniform -> False -> takes explicit-splits a2a path; rank B's
    splits uneven -> True -> takes equal-padding a2a path with
    None/None). The two ranks then hand `all_to_all_single`
    different argument shapes -> hang.

    Fix: new `_can_use_equal_a2a_splits_global` helper does an
    all_reduce(MAX) of the local bool across `ep_mesh`. Any rank
    voting "True" forces all peers to also pad, keeping branch
    decisions in lockstep.

(2) `TT_MOE_NORMAL_EQUAL_A2A_PADDING` env var was read on every
    `dispatch()` call via `_normal_equal_a2a_padding_enabled()` /
    `_normal_equal_a2a_padding_policy()`. PBS env propagation across
    Sunspot/Aurora hosts isn't uniformly guaranteed (per-host
    .bashrc differences, partial `-v` broadcast), so rank 0 could
    see "force" while rank 7 saw "" - and the two would take
    different branches.

    Fix: read the env var ONCE at `wire_meshes()` time and
    all_reduce(MAX) across `ep_mesh` into
    `self._normal_equal_a2a_policy`. Encode policy as
    int (off=0, adaptive=1, force=2) so the strongest policy wins
    - this biases toward enabling the optimization when any rank
    asked for it (consistent with the failure mode where a user
    only exports the env var on rank 0's host). Telemetry flag
    cached similarly into `self._normal_equal_a2a_telemetry`.

    The dispatch hot path now references the cached attributes
    directly; no per-step env-var read.

Both reductions are tiny (1 int over ep_mesh.size() ranks) and
happen at construction time (the env-var one) or once per dispatch
(the splits one). The latter could be folded into the existing
`_global_equal_a2a_split_size` collective in a follow-up if perf
matters, but the simple separate all_reduce keeps the code clear.

Addresses review findings saforem2#3 + saforem2#5 on saforem2#14.
saforem2 added a commit that referenced this pull request Jun 28, 2026
Reproduced the 80B LR-ceiling-vs-GBS trend at 2B (16N, TP=1 -> dp=192, the
same dp as the 80B GBS=6144 headline, so curves overlay directly). AdamW
swept at GBS 192..24576 (jobs 12469769-776).

Result: 2B AdamW usable LR is FLAT at ~1e-2 across the whole 128x batch range
(192..24576), every point a clean U-min with 0 NaN -- including 12288 (2B
production) and 24576 (2x production). No collapse, no NaN cliff.

This makes the 80B finding precise: the batch-dependent usable-LR collapse +
U-min -> NaN-cliff transition is a LARGE-MODEL (dim=9216 bf16) phenomenon, not
a universal scaling law. Likely the same width-driven bf16 fragility that
breaks muon/sophiag at 80B; 2B (dim=2048) never reaches that regime.

- agpt/2b/README.md: replace the in-progress placeholder with the results
  table (adamw/mano/sophiag per GBS) + 2B-vs-80B overlay figure + the
  contrast table and conclusion.
- agpt/README.md: key-finding #5 updated from "being checked at 2B" to the
  resolved large-model-specific conclusion; 2B reports-row updated.
- muon dropped from the sweep (crashes every job via a oneCCL collective
  abort ~7min in; the script recovers to sophiag). Noted in the page.

GBS=24576 mano/sophiag still finishing; AdamW (headline) complete. The 80B
trend gap-fill (1152 done, 2304 bad-data resubmitted as 12469778, 4608
running) refreshes the 80B figure separately when those land.
saforem2 added a commit that referenced this pull request Aug 17, 2026
Recommendation #5 from the concurrent-job-ckpt-collision writeup. Episode 2 was
found 18 days late by hand-counting files; this detector would have caught it
the same day.

The discriminator is INDEX ALIGNMENT, not just an mtime gap. A collided dir has
two mtime clusters where the split falls exactly on a shard index -- a 192-rank
job wrote shards 0-191 over the top of a 3072-rank job's, hours apart and at a
different file size. Straggler ranks also produce a gap (three dirs in the same
tree gapped 108-121s and are benign), but their late files are a handful
scattered anywhere, not a contiguous prefix. So a non-aligned split is reported
as stragglers and only an aligned one is called MIXED.

Also covers recommendation #3 (shard count differing from the tree's mode is a
scale change and should never be silent), plus out-of-order mtimes and
empty/metadata-less dirs.

Read-only, and deliberately so: reclaiming 906 GB of orphan shards is a human
decision, and each mixed dir may still hold a coherent checkpoint for its step.
Exits 1 on any MIXED dir so it can gate a resume.
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.
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.

2 participants