Repository navigation
Conversation
Reviewer's GuideIntroduces 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 groupsequenceDiagram
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
Class diagram for FTTrainer and base Trainer refactorclassDiagram
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
Class diagram for compiler toolkit FSDP extra process groups and AG reassignmentclassDiagram
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
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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 forNone, andreassign_to_pg_passassumesnode.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_updatepath 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>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| 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) |
There was a problem hiding this comment.
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.
| from torchtitan.train import main, Trainer | ||
|
|
||
|
|
||
| class FTTrainer(Trainer): |
There was a problem hiding this comment.
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_norm3. 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_seenAnd 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_profilerAnd 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_stepbecomes 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.
There was a problem hiding this comment.
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.
| 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 | ||
| ) |
There was a problem hiding this comment.
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
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.
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.
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.
…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.
…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.
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
common_utils.pyto 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)reassign_to_pg_passinpasses.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)graph_utils.pyto call extra PG creation and reassign passes when "transformer_block_bucketing" is requested, and modified the interface forget_compiler_passes_from_configto acceptparallel_dims. (torchtitan/experiments/compiler_toolkit/graph_utils.py) [1] [2]parallelize_llamaandparallelize_deepseekv3to passparallel_dimstoget_compiler_passes_from_config. (torchtitan/experiments/compiler_toolkit/llama3/parallelize.py,torchtitan/experiments/compiler_toolkit/deepseek_v3/parallelize.py) [1] [2]Testing and Validation
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
tests/integration_tests/h100.py)torchtitan/distributed/utils.py)Truefor deterministic output. (torchtitan/config/job_config.py)Miscellaneous
0.2.2. (assets/version.txt)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:
Bug Fixes:
Enhancements:
Build:
CI:
Documentation:
Tests:
Chores: