Skip to content

[trainer][perf] Log training metrics without waiting for the device - #6132

Merged
fegin merged 1 commit into
mainfrom
fegin/stack/39
Dec 1, 2026
Merged

fegin merged 1 commit into
mainfrom
fegin/stack/39

Conversation

@fegin

@fegin fegin commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


[trainer][perf] Log training metrics without waiting for the device

Summary (human-written)

TorchTitan's logging currently waits for the device. But it can actually be overlapped with the next step.

Right now we have to adjust the logging frequency to avoid logging being the bottleneck. This is very annoying. With this PR, we can set logging frequency to 1 which is very useful when the cluster resource is busy and we don't have luxury to run many iterations.

Follows the design of #2728 and fixes some issues.

Why

Each logged step reads its metrics right after optim_step(). The first read, int(global_main_loss_token_count), and the .item() calls after it wait until the device finishes the optimizer update. Only then does the host fetch, preprocess, and copy the next step's inputs, so the device sits idle before the next step's first kernel or CUDA graph. With log_freq=1 this happens every step.

Blocking host-to-device copies wait for the update too: the global token count before the next forward, and the token and FLOP counts that the logged reductions create with torch.tensor(..., device=...).

before: optim_step | .item() waits for the update | fetch, preprocess, H2D | device idle | forward
after:  optim_step | queue metric copies | fetch, preprocess, H2D, queue forward | print the previous step

#2728 deferred the same reads by one step. It was closed without merging: the review asked to wait for #4202 (distributed tensor logging), so metrics could handle device and host values together. #4202 is still open, and it adds per-tensor statistics; it does not remove these per-step reads. This change is small and self-contained, so it can land now and move onto #4202's mechanism when that lands.

What changed

  • MetricsProcessor.log_async takes the logged values as tensors or floats. It starts a non-blocking host copy of each tensor and returns. flush() waits for those copies and emits the metrics. log() is log_async() plus flush(), so other callers keep their behavior.
  • The global token count, and the token and FLOP counts reduced for logging, are copied to the device with non_blocking=True. A blocking copy from pageable memory waits for the previous optimizer update.
  • Trainer.train_step calls log_async and flushes the previous logged step after queuing its own forward and backward. train() also flushes before validation and when training ends, so log lines keep their order.
  • The throughput window ends when the device reaches the log_async call. It is timed with device events recorded at reset() and at log_async. A checkpoint saved after the step is not in its window, as before. Validation throughput is timed with the same events. Runs without an accelerator (torch.accelerator.is_available() is false) use the host clock. Token count, data loading time, and peak memory are read at log_async, so data the next step fetches before the flush is not counted.
  • The logged reductions keep their results on the device: dist_sum_tensor, a new dist_max_tensor, and dist_mean_tensor (renamed from dist_mean to match the other two). collect_aux_loss_metrics returns device scalars, divided in float64 as before, and the RL trainer converts them where it needs floats.
  • The global_valid_tokens trace record is passed to log_async apart from the metrics and emitted at the flush. log_trace_scalar takes optional step and relative_step, so the record keeps the step it belongs to. Its step tags come from the step that flushes it.

User-facing changes

Before After
Training log line of step N printed during step N printed during step N+1, after its work is queued
dist_mean returns a float renamed dist_mean_tensor, returns a device tensor
collect_aux_loss_metrics returns floats returns device scalars

The order of log lines (training before validation of the same step), metric keys, and values are unchanged.

Numerics / performance

Loss and grad_norm are unchanged; only when they are read changes. llama3 debug model, 2 GPUs, seed 42, deterministic, 12 steps with log_freq=5, validation, and a checkpoint at step 10: loss, grad_norm, and validation loss match the parent commit at every logged step.

Peak reserved memory of step 1 is 0.89 GiB vs 0.78 GiB on the parent; later steps match (0.80 GiB). Freed blocks used by other streams go back to the allocator later when the host runs ahead.

64 real GB300 GPUs, muse_spark_816b_a42b_dist_moe_bf16_spmd_64 (DP8/CP8/EP64, 32K, pinned-host Adam moments, log_freq=1), 100 steps from random init: 2,122.2 -> 2,158.7 tps over steps 71-90 (+1.7%). Step-1 peak allocated memory is unchanged (257.82 GiB).

FakePG run of the same recipe (_fake), one GPU, NUMA-bound, arms alternated on the same GPU, median tps of steps 5-10 (log_freq=1) or the steps 11-20 window (log_freq=10), relative to the parent commit:

log_freq=1 log_freq=10
parent 1.000 1.000
this commit 1.028, 1.029, 1.027 1.009, 1.009

Logging every step costs the parent 1.8%; this commit removes that cost. Host wall time per step agrees with the event-timed tps (-2.9%). Peak memory is unchanged. Copying each value separately costs at most 0.1% compared with one stacked copy. An earlier version without the non-blocking count copies gave no gain at log_freq=1. With debug.seed=42, losses match the parent within the parent's own run-to-run noise on this recipe.

Testing

  • test_async_log_uses_the_window_at_log_time: data fetched before the flush must not count in the logged step's throughput window, and the emitted values must match the logged tensors. The deferred trace record must carry the logged step and relative step. The loss is (1,)-shaped, like the loss on PP ranks without the last stage, while grad_norm is 0-dim.
  • test_trainer_accumulates_reused_accelerator_graph_losses checks the values passed to log_async and that each step flushes.
  • pytest tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/observability tests/unit_tests/cpu/components/test_invalid_loss.py tests/unit_tests/cpu/components/test_validator.py tests/unit_tests/cpu/models/common/test_aux_loss.py: 244 passed, 1 skipped, with GPUs visible and with CUDA_VISIBLE_DEVICES= (no accelerator).
  • llama3 debug model, 2 GPUs, seed 42, deterministic: loss and grad_norm in TensorBoard are bitwise equal to the parent commit at every logged step for FSDP 2 with 20 steps at log_freq=1 and log_freq=10, and for PP 2 with 1F1B (llama3_debugmodel_pp2_1f1b) with 10 steps at log_freq=1. The PP run checks that the rank without the last stage can log its (1,)-shaped loss sentinel.
  • test_trainer_keeps_scheduled_eval_during_warmup: its fake trainer gets a metrics_processor, since train() flushes before validation.

Known issues / follow-ups

  • An error raised after a step is logged but before the flush, for example an NCCL timeout, loses that step's log line.
  • Add distributed tensor logging #4202 (distributed tensor logging) is a separate mechanism for per-tensor statistics; it does not remove these reads.

This change was written with an AI assistant (Claude).

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 16, 2026
fegin added a commit that referenced this pull request Nov 17, 2026
…r graph capture (#6131)

Stacked PRs:
 * #6136
 * #6135
 * #6134
 * #6133
 * #6132
 * #5882
 * #5881
 * __->__#6131


--- --- ---

### [cudagraph] Remove the unsynchronized empty_cache() before
accelerator graph capture


## Summary (human-written)
There is a race condition if users do not call a sync after step() and
call empty_cache() before the next step().

For the current TorchTitan main, we do call sync in the end of each
iteration to gather the log. However, if we change the logging to async,
this race condition will be exposed.

The race condition happens like this:
```text
step 2 (eager): FSDP2 allocates the sharded grads on its reduce-scatter stream
                AdamW reading those grads is queued on the default stream
step 3:         zero_grad(set_to_none=True) frees the grads on the host
                -> the blocks return to the reduce-scatter stream's free pool
                empty_cache() unmaps free blocks of expandable segments, after
                syncing only the reduce-scatter stream
                -> the queued AdamW reads unmapped memory: illegal memory access
```

This PR fixes the issue by removing the wrapper's empty_cache(). The
graph
capture context (torch.cuda.graph / torch.accelerator.Graph) already
calls
synchronize() and then empty_cache() when it starts, so the extra call
is
not needed and the race is gone.

## Why
`AcceleratorGraphWrapper` calls `torch.accelerator.empty_cache()` right
before it captures a graph, without a sync. If the host runs ahead of
the device, this can unmap memory that a queued kernel still reads:

```text
step 2 (eager): FSDP2 allocates the sharded grads on its reduce-scatter stream
                AdamW reading those grads is queued on the default stream
step 3:         zero_grad(set_to_none=True) frees the grads on the host
                -> the blocks return to the reduce-scatter stream's free pool
                empty_cache() unmaps free blocks of expandable segments, after
                syncing only the reduce-scatter stream
                -> the queued AdamW reads unmapped memory: illegal memory access
```

On main, a blocking host-to-device copy of the token counts in
`Trainer.train_step` waits for the previous optimizer step before
`zero_grad`, so the host never gets this far ahead. "[trainer] Log
training metrics without waiting for the device", later in this stack,
removes that copy and exposes the crash: llama3 debug model, FSDP2 on 2
GPUs, `expandable_segments:True` (set by `run_train.sh`), crashes in
step 2-3 with varlen, flex, and CP2.

The call is not needed. The capture context that runs right after it,
`torch.cuda.graph` or `torch.accelerator.Graph`, already calls
`synchronize()` and then `empty_cache()` in `__enter__`.

## What changed
- Remove the wrapper's `empty_cache()` and its `before_empty_cache` /
`after_empty_cache` memory logs. The capture context releases the same
cache, after a device sync.
- `ACCELERATOR_GRAPH.md` says the capture context empties the cache.
- `test_preparation_runs_only_before_first_capture` (renamed) expects no
`empty_cache()` call from the wrapper.

The underlying gap is in PyTorch. FSDP2 orders the reuse of gradient
blocks with stream events, which covers normal allocations but not
`empty_cache()`. The expandable-segment unmap waits only for the stream
that allocated the block, while a plain `cudaFree` syncs the device. A
single-GPU repro without torchtitan crashes with expandable segments,
and passes with a `record_stream` before the free or a sync before
`empty_cache()`. The optimizer's first-step `empty_cache()` already
syncs first (#5019). The other call runs at startup.

## Testing
- With the host running ahead ("[trainer] Log training metrics without
waiting for the device"), llama3 debug model on 2 GPUs, `log_freq=10`,
20 steps: with the wrapper's unsynchronized call, varlen, flex, and CP2
each crash 3 of 3 runs; with it removed all pass 3 of 3. A GPU coredump
puts the fault in the fused AdamW kernel, on gradients in segments owned
by FSDP2's reduce-scatter stream.
- On another 4-GPU host the debug model does not get far enough ahead to
crash. With an ~80 ms GPU sleep added before each AdamW step, the
wrapper's unsynchronized call crashes 8 of 9 runs (varlen, flex, CP2)
and this change passes 9 of 9.
- Losses and grad_norm match a `CUDA_LAUNCH_BLOCKING=1` run of the same
config (varlen with `debug.deterministic=True`).

This change was written with an AI assistant (Claude).
@fegin
fegin changed the base branch from fegin/stack/11 to main November 18, 2026 08:46
@fegin
fegin force-pushed the fegin/stack/39 branch 2 times, most recently from 7847322 to 5b24f39 Compare November 18, 2026 08:47
@fegin
fegin changed the base branch from main to fegin/stack/11 November 18, 2026 08:47
@fegin
fegin changed the base branch from fegin/stack/11 to main November 19, 2026 21:12
@fegin
fegin changed the base branch from main to fegin/stack/11 November 19, 2026 21:13
@fegin
fegin changed the base branch from fegin/stack/11 to main November 19, 2026 22:16
@fegin
fegin changed the base branch from main to fegin/stack/11 November 19, 2026 22:17
@fegin
fegin changed the base branch from fegin/stack/11 to main November 20, 2026 00:20
@fegin
fegin changed the base branch from main to fegin/stack/11 November 20, 2026 00:20
@fegin
fegin changed the base branch from fegin/stack/11 to main November 20, 2026 18:01
@fegin
fegin changed the base branch from main to fegin/stack/11 November 20, 2026 18:02
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Nov 20, 2026
## Summary (human-written)
TorchTitan's logging currently waits for the device. But it can actually be overlapped with the next step.

Follows the design of pytorch/torchtitan#2728 and fixes some issues.

## Why
Each logged step reads its metrics right after `optim_step()`. The first read, `int(global_main_loss_token_count)`, and the `.item()` calls after it wait until the device finishes the optimizer update. Only then does the host fetch, preprocess, and copy the next step's inputs, so the device sits idle before the next step's first kernel or CUDA graph. With `log_freq=1` this happens every step.

Blocking host-to-device copies wait for the update too: the global token count before the next forward, and the token and FLOP counts that the logged reductions create with `torch.tensor(..., device=...)`.

```text
before: optim_step | .item() waits for the update | fetch, preprocess, H2D | device idle | forward
after:  optim_step | queue metric copies | fetch, preprocess, H2D, queue forward | print the previous step
```

#2728 deferred the same reads by one step. It was closed without merging: the review asked to wait for #4202 (distributed tensor logging), so metrics could handle device and host values together. #4202 is still open, and it adds per-tensor statistics; it does not remove these per-step reads. This change is small and self-contained, so it can land now and move onto #4202's mechanism when that lands.

## What changed
- `MetricsProcessor.log_async` takes the logged values as tensors or floats. It starts a non-blocking host copy of each tensor and returns. `flush()` waits for those copies and emits the metrics. `log()` is `log_async()` plus `flush()`, so other callers keep their behavior.
- The global token count, and the token and FLOP counts reduced for logging, are copied to the device with `non_blocking=True`. A blocking copy from pageable memory waits for the previous optimizer update.
- `Trainer.train_step` calls `log_async` and flushes the previous logged step after queuing its own forward and backward. `train()` also flushes before validation and when training ends, so log lines keep their order.
- The throughput window ends when the device reaches the `log_async` call. It is timed with device events recorded at `reset()` and at `log_async`. A checkpoint saved after the step is not in its window, as before. Validation throughput is timed with the same events. CPU runs use the host clock. Token count, data loading time, and peak memory are read at `log_async`, so data the next step fetches before the flush is not counted.
- The logged reductions keep their results on the device: `dist_sum_tensor`, a new `dist_max_tensor`, and `dist_mean`, which returns a tensor. `collect_aux_loss_metrics` returns device scalars, divided in float64 as before, and the RL trainer converts them where it needs floats.
- The `global_valid_tokens` trace record is passed to `log_async` apart from the metrics and emitted at the flush. `log_trace_scalar` takes an optional `step`, so the record keeps the step it belongs to.

## User-facing changes
| | Before | After |
|---|---|---|
| Training log line of step N | printed during step N | printed during step N+1, after its work is queued |
| `dist_mean` | returns a float | returns a device tensor |
| `collect_aux_loss_metrics` | returns floats | returns device scalars |

The order of log lines (training before validation of the same step), metric keys, and values are unchanged.

## Numerics / performance
Loss and grad_norm are unchanged; only when they are read changes. llama3 debug model, 2 GPUs, seed 42, deterministic, 12 steps with `log_freq=5`, validation, and a checkpoint at step 10: loss, grad_norm, and validation loss match the parent commit at every logged step.

Peak reserved memory of step 1 is 0.89 GiB vs 0.78 GiB on the parent; later steps match (0.80 GiB). Freed blocks used by other streams go back to the allocator later when the host runs ahead.

64 real GB300 GPUs, `muse_spark_816b_a42b_dist_moe_bf16_spmd_64` (DP8/CP8/EP64, 32K, pinned-host Adam moments, log_freq=1), 100 steps from random init: 2,122.2 -> 2,158.7 tps over steps 71-90 (+1.7%). Step-1 peak allocated memory is unchanged (257.82 GiB).

FakePG run of the same recipe (`_fake`), one GPU, NUMA-bound, arms alternated on the same GPU, median tps of steps 5-10 (log_freq=1) or the steps 11-20 window (log_freq=10), relative to the parent commit:

| | log_freq=1 | log_freq=10 |
|---|---|---|
| parent | 1.000 | 1.000 |
| this commit | 1.028, 1.029, 1.027 | 1.009, 1.009 |

Logging every step costs the parent 1.8%; this commit removes that cost. Host wall time per step agrees with the event-timed tps (-2.9%). Peak memory is unchanged. Copying each value separately costs at most 0.1% compared with one stacked copy. An earlier version without the non-blocking count copies gave no gain at log_freq=1. With `debug.seed=42`, losses match the parent within the parent's own run-to-run noise on this recipe.

## Testing
- `test_async_log_uses_the_window_at_log_time`: data fetched before the flush must not count in the logged step's throughput window, and the emitted values must match the logged tensors. The loss is (1,)-shaped, like the loss on PP ranks without the last stage, while grad_norm is 0-dim.
- `test_trainer_accumulates_reused_accelerator_graph_losses` checks the values passed to `log_async` and that each step flushes.
- `pytest tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/observability tests/unit_tests/cpu/components/test_invalid_loss.py tests/unit_tests/cpu/components/test_validator.py tests/unit_tests/cpu/models/common/test_aux_loss.py`: 244 passed, 1 skipped.
- llama3 debug model, 2 GPUs, seed 42, deterministic: loss and grad_norm in TensorBoard are bitwise equal to the parent commit at every logged step for FSDP 2 with 20 steps at `log_freq=1` and `log_freq=10`, and for PP 2 with 1F1B (`llama3_debugmodel_pp2_1f1b`) with 10 steps at `log_freq=1`. The PP run checks that the rank without the last stage can log its (1,)-shaped loss sentinel.
- `test_trainer_keeps_scheduled_eval_during_warmup`: its fake trainer gets a `metrics_processor`, since `train()` flushes before validation.

## Known issues / follow-ups
- An error raised after a step is logged but before the flush, for example an NCCL timeout, loses that step's log line.
- #4202 (distributed tensor logging) is a separate mechanism for per-tensor statistics; it does not remove these reads.

This change was written with an AI assistant (Claude).

stack-info: PR: pytorch/torchtitan#6132, branch: fegin/stack/39
@fegin
fegin changed the base branch from main to fegin/stack/11 November 30, 2026 22:54
@fegin
fegin marked this pull request as ready for review November 30, 2026 22:55
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 30, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 30, 2026 22:55
@fegin fegin changed the title [trainer] Log training metrics without waiting for the device [trainer][perf] Log training metrics without waiting for the device Nov 30, 2026
@fegin

fegin commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @fegin's task in 4m 33s —— View job


Approve -- please address the items below before merging: review. (Ignore the review's last line about the human-written summary; the summary is already filled in.)

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging -- The cause is real and the PR removes it at the right layer: logged values are read on the host after optim_step(), so the device sits idle before the next step. The PR defers those reads by one step and doesn't touch numerics. The only remaining must-fix is a rename.

What this PR does. MetricsProcessor.log_async starts non-blocking device-to-host copies of the logged tensors. It also records a device event as the end of the throughput window, then returns. flush() waits for that event and emits the metrics. Trainer.train_step flushes the previous logged step after it has queued its own forward/backward. The token and FLOP counts the step sends to the device now use non_blocking=True, so they no longer wait for the previous update.

Example. log_freq=1, two steps:

before: step N: optim_step -> int(global_count)/.item() wait for the device -> print N
        step N+1: fetch + H2D (device idle) -> forward
after:  step N: optim_step -> queue D2H copies + window_end event -> return
        step N+1: fetch + H2D + queue fwd/bwd -> flush(): wait for N's event, print N -> optim_step

The values, metric keys and log order (train before validation of the same step) stay the same. The step-N line now prints during step N+1.

Must fix

  1. torchtitan/distributed/utils.py:125 -- dist_mean now returns a tensor while its siblings dist_sum/dist_max return floats. Rename it dist_mean_tensor to match dist_sum_tensor/dist_max_tensor (see inline).

Should consider

  • torchtitan/observability/metrics.py:665 -- the deferred global_valid_tokens trace record gets step=N, but its relative_step and step_tags come from step N+1 (see inline).
Details

Gate. Problem: on main, int(global_main_loss_token_count) and the .item() calls in train_step wait for the device on every logged step. Blocking H2D copies from pageable memory also wait for the stream (trainer.py token counts, torch.tensor(..., device=...) for ntokens/FLOPs). The fix belongs to the trainer/metrics layer, and nothing upstream needs to change. Value: +1.7% e2e at 64 GB300 GPUs with log_freq=1, and +2.8% on FakePG over three repeats. That is above noise, and there's a mechanism to explain it. No new config knob.

Overlap search. I searched log_async, metrics logging sync, MetricsProcessor and dist_mean. The only overlap is #4202 (distributed tensor logging, draft since 2026-08). The description explains why this PR doesn't wait for it, and the existing TODO(#4202) comments stay.

Correctness checks done:

  • Window ordering. reset() at step N+1 records a new _window_start event, but _PendingLog already holds N's start and end events plus copies of data_loading_times, the token count and the peak stats. The flush therefore uses only N's window. A checkpoint saved between log_async and the next reset() is still outside the window. Validation: train() flushes before validate(), and validator.reset() doesn't touch the pending entry.
  • Graph-reused loss buffers. Under a whole-step accelerator graph, the D2H copy is queued on the current stream before the next replay overwrites the static output. On CPU, _copy_to_host aliases the tensor, but the CPU path has no graphs, and accumulated_loss / combine_loss_metrics / aux-loss values are new tensors every step.
  • PP. The (1,)-shaped loss sentinel on non-last stages reads fine through .item().
  • dist_mean / aux-loss numerics. float64 total/count and float64 total / count on the device are the same IEEE operations as the previous Python-float division.
  • Callers of the changed APIs. torchft (experiments/torchft/trainer.py) overrides train/train_step and still calls the synchronous log(). log() accepts the tensor-valued collect_aux_loss_metrics there through _read. The RL trainer calls .item() where it needs floats. No other subclass overrides train(), so the final flush() covers flux and the base trainer.
  • Exception path. Not flushing in except is defensible, since event.synchronize() could hang on a stuck device. The description lists this as a known issue.

Smaller nits, not blocking. dist_max_tensor has an extra_pg parameter that no caller uses. It mirrors dist_sum_tensor, so I'm only noting it. The new window test lives in test_validation_metrics_window.py, although it tests the training window.

Not verified: the GPU numerics and throughput numbers in the description. Also unverified: whether non_blocking=True copies from pageable memory and D2H without pinned memory behave safely on non-CUDA backends (XPU/NPU). A maintainer still needs to review, since this touches trainer.py.

Before merge: fill in the human-written summary.

Comment thread torchtitan/distributed/utils.py Outdated

def dist_mean(x: torch.Tensor, mesh: DeviceMesh) -> float:
"""Average a scalar over the mesh.
def dist_mean(x: torch.Tensor, mesh: DeviceMesh) -> torch.Tensor:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

After this PR the module's naming convention is dist_sum / dist_max -> float and dist_sum_tensor / dist_max_tensor -> device tensor. dist_mean now returns a device tensor but has the float-style name. A reader who knows the siblings will assume it syncs and returns a float, which is what it did before this PR. Rename it to dist_mean_tensor and update both callers (torchtitan/trainer.py, torchtitan/rl/trainer/trainer.py). That keeps sibling names symmetric (CLAUDE.md, Naming).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should this be renamed

Suggested change
def dist_mean(x: torch.Tensor, mesh: DeviceMesh) -> torch.Tensor:
def dist_mean_tensor(x: torch.Tensor, mesh: DeviceMesh) -> torch.Tensor:

Comment on lines +665 to +667
sl.log_trace_scalar(
{k: _read(v) for k, v in pending.trace_scalars.items()}, step=pending.step
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The deferred global_valid_tokens record now gets step=N from this override. But jsonl_handler.py (around lines 100-127) still fills relative_step and step_tags from the global step state, and at this point that state belongs to step N+1: train() already called sl.set_step(N+1, relative_step=...), and flush() runs inside train_step(N+1). So the record says step=N, relative_step=N+1-loaded_step, and it carries step N+1's tags (for example gc). The fields of one record disagree with each other.

Smallest fix: in log_async, capture sl.get_relative_step() next to step. Then add a relative_step parameter to log_trace_scalar and pass it to event_extra, which already accepts it. Step tags can't be overridden per record. If that matters, say so in the docstring of the new step argument.

Comment thread torchtitan/distributed/utils.py Outdated

def dist_mean(x: torch.Tensor, mesh: DeviceMesh) -> float:
"""Average a scalar over the mesh.
def dist_mean(x: torch.Tensor, mesh: DeviceMesh) -> torch.Tensor:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should this be renamed

Suggested change
def dist_mean(x: torch.Tensor, mesh: DeviceMesh) -> torch.Tensor:
def dist_mean_tensor(x: torch.Tensor, mesh: DeviceMesh) -> torch.Tensor:

Comment on lines +315 to +316
step: Step to stamp on the records, for values emitted after their
step ended. Defaults to the step from ``set_step()``.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I didn't check all the ordering, but is this optionality needed? Can we require step?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

There are other callers which just rely only get_step() as they don't have the step information, like DCP.

Comment thread torchtitan/trainer.py
Comment on lines +402 to +404
# Emit the previous logged step after this step is queued, so waiting
# for its values overlaps with this step on the device.
self.metrics_processor.flush()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

what if we don't flush? what if we only flush if should_log is true on this step?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Then it can be too late, like if the frequency is 10 steps, then the Nth log will only be flushed after N+10 instead of N+1. In most cases, that should be fine, but it if a crash happens during N and N+10, then we lose the log. Also the flush() should be pretty cheap and can mostly overlap with fwd/bwd. So calling it in when should_log is True doesn't buy us anything.

Comment thread torchtitan/trainer.py Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

can we make it async in RL trainer as well?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right now RL trainer doesn't use this Metric object. And according to Claude, it doesn't buy us anything due to the current RL trainer flow. So I would not do this in this PR.

Comment on lines +583 to +588
global_avg_loss: float | torch.Tensor,
global_max_loss: float | torch.Tensor,
grad_norm: float | torch.Tensor,
extra_metrics: dict[str, Any] | None = None,
*,
num_flops: float,
num_flops: float | torch.Tensor,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why still accepting float?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I opened a new PR to migrate TorchFT trainer as well. This way we don't need to accept float.

Comment on lines +617 to +619
global_avg_loss: float | torch.Tensor,
global_max_loss: float | torch.Tensor,
grad_norm: float | torch.Tensor,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

similar

@tianyu-l

tianyu-l commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@claude review my review

@claude

claude Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 28s —— View job


Of tianyu-l's six comments, the dist_mean_tensor rename is correct, the "why still accept float" question is partly correct, and the other four can stay as they are: review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of @tianyu-l's comments, one by one. All line numbers are at HEAD (3ea90bb).

  1. distributed/utils.py:125, rename to dist_mean_tensor: correct. The siblings are dist_sum/dist_max -> float and dist_sum_tensor/dist_max_tensor -> tensor, and dist_mean now returns a tensor. Apply the suggestion and update the only two callers, trainer.py:468 and rl/trainer/trainer.py:395.

  2. structured_logging.py:316, make step required: mistaken. Three other callers rely on the default: trainer.py:379, rl/controller/work_buffer.py:232 and components/checkpointer/dcp.py:507. Making step required means each of them passes step=sl.get_step(), which is what the default already does. Only the deferred record in MetricsProcessor.flush needs to override it. Keep it optional. The real gap is the one from my earlier review: jsonl_handler.py:100-127 still fills relative_step and step_tags from step N+1. Fix that by capturing relative_step along with step.

  3. trainer.py:404, don't flush, or flush only when should_log: mistaken. Both options mean the same thing, because log_async already calls flush() first (metrics.py:632). Either way, step N's line would print at the next logged step, log_freq steps late. With log_freq=100, step 100 would print around step 200. A crash would also lose that much more output (the PR's known issue). Throughput gains nothing from this. On steps with nothing pending, flush() returns right away. On step N+1 it waits on step N's window_end event only after step N+1's forward/backward is queued, so the event has almost always been reached. Keep the flush where it is.

  4. trainer.py:529, flush before validation: mistaken. Without this flush, validator.validate -> log_validation (components/validator.py:420) prints step N's validation line before step N's training line, which would print during step N+1. That breaks the description's claim that log order is unchanged. The flush costs nothing here, because validation waits for the device anyway.

  5. rl/trainer/trainer.py, make the RL trainer async too: not worth it today. After optim_step returns, the controller runs push_model_state_dict before the next forward/backward (rl/controller/controller.py:1515-1528), and the push has to wait for the optimizer update. The comment at rl/trainer/trainer.py:204-207 says "optim_step syncs the host before the push starts". So the device can't run ahead of the .item() calls, and deferring them hides nothing. The metrics also go back in the RPC reply for controller-side aggregation, so an async version would need a protocol change that returns step N-1's metrics in step N's reply. This becomes worthwhile together with the TODO at controller.py:1517 that overlaps the push with forward/backward.

  6. metrics.py:588 / :619, why still accept float: partly correct. Floats are still passed: num_flops is a Python float on runs without DP (trainer.py:422), and the torchft experiment calls log() with floats (experiments/torchft/trainer.py:499). extra_metrics also mixes in ints and floats (n_tokens_seen without DP, lr). For global_avg_loss, global_max_loss and grad_norm, core always passes tensors now, and only torchft needs the float half. num_flops must stay float | torch.Tensor. The three loss/norm parameters can be narrowed to torch.Tensor only if torchft switches to tensor reductions (dist_sum_tensor(..., extra_pg=ft_pg) already exists). Accepting floats costs nothing at runtime, so I'd leave them unless torchft is converted in this PR.

Nothing new that the two reviews missed. The relative_step / step_tags mismatch from my earlier review is still open.

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

please fix the dist_mean_tensor naming

fegin added a commit that referenced this pull request Dec 1, 2026
Stacked PRs:
 * #6252
 * #5746
 * #6135
 * #6134
 * #6133
 * #6132
 * __->__#5882
 * #5881 (landed)


--- --- ---

### [muse_spark] Add a 64-GPU Dist-MoE recipe with varlen attention


## Summary (human-written)
With the CPU-offloading optimizer, we can run Muse Spark with 64 GPUs.
This
PR adds a recipe to demonstrate it.

## Why
The Dist-MoE scale recipes run only on 256 or 512 GPUs, and they use
FlexAttention only. #5706 added `attn_backend` to `muse_spark_816b_a42b`
and listed three blockers for varlen in these recipes: their loader sets
no `max_num_documents`, varlen K/V all-gather is untested on Muse, and
`use_flex_flash_attention` raises on non-flex layers. This change
removes those blockers and adds a 64-GPU recipe. It covers the #5706
follow-up "Varlen K/V all-gather CP for the Dist-MoE scale recipes".

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_bf16_spmd_256 / _512 only, FlexAttention
after:  muse_spark_816b_a42b_dist_moe_bf16_spmd_64 (and _64_fake):
        Muse Spark 816B, BF16 Dist-MoE, DP8 / CP8 (K/V all-gather) / EP64, TP1,
        32K sequence length, global batch 64, varlen attention with max_num_documents=128,
        Adam moments in pinned host memory
```

## What changed
**Recipe helpers**
- `_muse_spark_816b_dist_moe_bf16_spmd` takes `attn_backend:
Literal["flex", "varlen"]` and `max_num_documents`. It passes
`attn_backend` to `muse_spark_816b_a42b`.
- It sets the data loader's `max_num_documents` before `_with_dist_moe`
enables CUDA graphs, because `Trainer.Config` validation checks varlen
against CUDA graphs.
- The FakePG data loader keeps `max_num_documents`. It replaces only the
dataset and shuffle fields of the data loader config.
- The K/V all-gather CP transform also maps `VarlenInnerAttention` and
`SlidingWindowVarlenInnerAttention`.
- Flex-Flash block-mask tuning applies only with FlexAttention.

**New recipes**
- `muse_spark_816b_a42b_dist_moe_bf16_spmd_64` and
`muse_spark_816b_a42b_dist_moe_bf16_spmd_64_fake`. Remat also saves all
attention regions (`attention.*`).
- The 64-GPU recipe sets `fsdp_reshard_after_forward = "default"`
instead of the helper's `"always"`. With PP off, only the last [norm,
lm_head] FSDP unit changes: it stays unsharded after forward, so the
loss does not all-gather the 3 GiB lm_head weight again.
- `max_num_documents=128` is one slot per 256 tokens. The packer never
drops documents: a row that reaches the cap ends early and is padded,
and the rest of the document starts the next row. On C4 with the Muse
Spark tokenizer (600 rows on each of 8 DP ranks), documents average 460
tokens. 64 slots pad 10.7% of the tokens, and 80% of the rows reach the
cap. 128 slots pad none.
- The data loader and AdamW configs are updated with
`dataclasses.replace`, so their `__post_init__` checks run
(`max_num_documents > 0`; `moment_cpu_offload_fraction > 0` needs
`fused=True` and rejects accelerators other than CUDA, including ROCm).

**README** (`torchtitan/models/muse_spark/README.md`)
- Context parallelism: varlen attention supports both Ulysses and K/V
all-gather.
- CP load balancing: head-tail works with K/V all-gather varlen.
- K/V all-gather CP needs tokens per microbatch divisible by the CP
degree, or by 2 x the CP degree with head-tail. The query block size
rule applies only with FlexAttention.
- Varlen attention with CUDA graphs requires
`dataloader.max_num_documents`. Without it, set
`training.disable_accelerator_graphs`.
- A table lists the Dist-MoE scale recipes.

## Numerics
The 256- and 512-GPU and UltraData recipe configs are unchanged (0 field
diffs).

## Testing
- `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_fake` (NGPU=64,
NUMA-bound) runs and fits on one GPU of the fake-PG layout for 10 steps.
- Varlen K/V all-gather also runs with head-tail load balancing on the
same layout.
- Muse Spark recipe and model CPU unit tests.
- Both 64-GPU recipes build and pass `Trainer.Config` validation.
-
`test_fake_scale_recipe_tokenizer[muse_spark_816b_a42b_dist_moe_bf16_spmd_64_fake]`
builds the 64-GPU fake recipe. It catches a broken build, including a
varlen layer type that the K/V all-gather CP map misses (the build
raises "No CP inner attention configured").

## Known issues / follow-ups
- The real recipe ran on 64 GPUs for 20 steps at an earlier rebase of
this stack, with the same save regions, real routing, and
`max_num_documents=64`. Peak memory was 267.4 GiB (trainer) and 272.7
GiB (NVML) of 276.6 GiB, so only about 4 GiB is free. tps was about 2%
higher than with the default save regions (1,716 vs 1,683).
- On 64 real GPUs with the same setup, `fsdp_reshard_after_forward =
"default"` lowered peak memory by 1.9 GiB (265.5 vs 267.4 GiB trainer,
270.8 vs 272.7 GiB NVML), and tps did not change (1,725 vs 1,716). The
256- and 512-GPU recipes keep `"always"`.
- `max_num_documents=128` was run on 64 real GPUs only with the whole
recipe stack, which also shards the vocab over CP and frees memory.
There, peak allocated memory was the same as with 64 slots. It is not
run at this commit alone, where only about 4 GiB is free.
- tps counts padding tokens, and padding rows skip the routed experts.
So 128 slots lower the reported tps but raise the real tokens trained
per second.
- `test_debug_recipe_tokenizer[muse_spark_debugmodel_mm]` also fails on
main.
## Summary (human-written)
TorchTitan's logging currently waits for the device. But it can actually be overlapped with the next step.

Right now we have to adjust the logging frequency to avoid logging being the bottleneck. This is very annoying. With this PR, we can set logging frequency to 1 which is very useful when the cluster resource is busy and we don't have luxury to run many iterations.

Follows the design of #2728 and fixes some issues.

## Why
Each logged step reads its metrics right after `optim_step()`. The first read, `int(global_main_loss_token_count)`, and the `.item()` calls after it wait until the device finishes the optimizer update. Only then does the host fetch, preprocess, and copy the next step's inputs, so the device sits idle before the next step's first kernel or CUDA graph. With `log_freq=1` this happens every step.

Blocking host-to-device copies wait for the update too: the global token count before the next forward, and the token and FLOP counts that the logged reductions create with `torch.tensor(..., device=...)`.

```text
before: optim_step | .item() waits for the update | fetch, preprocess, H2D | device idle | forward
after:  optim_step | queue metric copies | fetch, preprocess, H2D, queue forward | print the previous step
```

#2728 deferred the same reads by one step. It was closed without merging: the review asked to wait for #4202 (distributed tensor logging), so metrics could handle device and host values together. #4202 is still open, and it adds per-tensor statistics; it does not remove these per-step reads. This change is small and self-contained, so it can land now and move onto #4202's mechanism when that lands.

## What changed
- `MetricsProcessor.log_async` takes the logged values as tensors or floats. It starts a non-blocking host copy of each tensor and returns. `flush()` waits for those copies and emits the metrics. `log()` is `log_async()` plus `flush()`, so other callers keep their behavior.
- The global token count, and the token and FLOP counts reduced for logging, are copied to the device with `non_blocking=True`. A blocking copy from pageable memory waits for the previous optimizer update.
- `Trainer.train_step` calls `log_async` and flushes the previous logged step after queuing its own forward and backward. `train()` also flushes before validation and when training ends, so log lines keep their order.
- The throughput window ends when the device reaches the `log_async` call. It is timed with device events recorded at `reset()` and at `log_async`. A checkpoint saved after the step is not in its window, as before. Validation throughput is timed with the same events. Runs without an accelerator (`torch.accelerator.is_available()` is false) use the host clock. Token count, data loading time, and peak memory are read at `log_async`, so data the next step fetches before the flush is not counted.
- The logged reductions keep their results on the device: `dist_sum_tensor`, a new `dist_max_tensor`, and `dist_mean_tensor` (renamed from `dist_mean` to match the other two). `collect_aux_loss_metrics` returns device scalars, divided in float64 as before, and the RL trainer converts them where it needs floats.
- The `global_valid_tokens` trace record is passed to `log_async` apart from the metrics and emitted at the flush. `log_trace_scalar` takes optional `step` and `relative_step`, so the record keeps the step it belongs to. Its step tags come from the step that flushes it.

## User-facing changes
| | Before | After |
|---|---|---|
| Training log line of step N | printed during step N | printed during step N+1, after its work is queued |
| `dist_mean` | returns a float | renamed `dist_mean_tensor`, returns a device tensor |
| `collect_aux_loss_metrics` | returns floats | returns device scalars |

The order of log lines (training before validation of the same step), metric keys, and values are unchanged.

## Numerics / performance
Loss and grad_norm are unchanged; only when they are read changes. llama3 debug model, 2 GPUs, seed 42, deterministic, 12 steps with `log_freq=5`, validation, and a checkpoint at step 10: loss, grad_norm, and validation loss match the parent commit at every logged step.

Peak reserved memory of step 1 is 0.89 GiB vs 0.78 GiB on the parent; later steps match (0.80 GiB). Freed blocks used by other streams go back to the allocator later when the host runs ahead.

64 real GB300 GPUs, `muse_spark_816b_a42b_dist_moe_bf16_spmd_64` (DP8/CP8/EP64, 32K, pinned-host Adam moments, log_freq=1), 100 steps from random init: 2,122.2 -> 2,158.7 tps over steps 71-90 (+1.7%). Step-1 peak allocated memory is unchanged (257.82 GiB).

FakePG run of the same recipe (`_fake`), one GPU, NUMA-bound, arms alternated on the same GPU, median tps of steps 5-10 (log_freq=1) or the steps 11-20 window (log_freq=10), relative to the parent commit:

| | log_freq=1 | log_freq=10 |
|---|---|---|
| parent | 1.000 | 1.000 |
| this commit | 1.028, 1.029, 1.027 | 1.009, 1.009 |

Logging every step costs the parent 1.8%; this commit removes that cost. Host wall time per step agrees with the event-timed tps (-2.9%). Peak memory is unchanged. Copying each value separately costs at most 0.1% compared with one stacked copy. An earlier version without the non-blocking count copies gave no gain at log_freq=1. With `debug.seed=42`, losses match the parent within the parent's own run-to-run noise on this recipe.

## Testing
- `test_async_log_uses_the_window_at_log_time`: data fetched before the flush must not count in the logged step's throughput window, and the emitted values must match the logged tensors. The deferred trace record must carry the logged step and relative step. The loss is (1,)-shaped, like the loss on PP ranks without the last stage, while grad_norm is 0-dim.
- `test_trainer_accumulates_reused_accelerator_graph_losses` checks the values passed to `log_async` and that each step flushes.
- `pytest tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/observability tests/unit_tests/cpu/components/test_invalid_loss.py tests/unit_tests/cpu/components/test_validator.py tests/unit_tests/cpu/models/common/test_aux_loss.py`: 244 passed, 1 skipped, with GPUs visible and with `CUDA_VISIBLE_DEVICES=` (no accelerator).
- llama3 debug model, 2 GPUs, seed 42, deterministic: loss and grad_norm in TensorBoard are bitwise equal to the parent commit at every logged step for FSDP 2 with 20 steps at `log_freq=1` and `log_freq=10`, and for PP 2 with 1F1B (`llama3_debugmodel_pp2_1f1b`) with 10 steps at `log_freq=1`. The PP run checks that the rank without the last stage can log its (1,)-shaped loss sentinel.
- `test_trainer_keeps_scheduled_eval_during_warmup`: its fake trainer gets a `metrics_processor`, since `train()` flushes before validation.

## Known issues / follow-ups
- An error raised after a step is logged but before the flush, for example an NCCL timeout, loses that step's log line.
- #4202 (distributed tensor logging) is a separate mechanism for per-tensor statistics; it does not remove these reads.

This change was written with an AI assistant (Claude).

stack-info: PR: #6132, branch: fegin/stack/39
@fegin
fegin changed the base branch from fegin/stack/11 to main December 1, 2026 16:37
fegin added a commit that referenced this pull request Dec 1, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
#6132 makes the core trainer log through `MetricsProcessor.log_async`, so the host does not wait for the optimizer update before it queues the next step. The torchft trainer has its own `train_step` and still calls the blocking `MetricsProcessor.log()` with values read by `dist_sum`, `dist_max`, and `.item()`. Each of them waits for the device on every logged step. It is also the only caller of `log()`, and the only reason `log_async` accepts floats for the loss and grad_norm.

## What changed
- `FaultTolerantTrainer.train_step` reduces the logged values with `dist_sum_tensor` and `dist_max_tensor` (with `ft_pg`, as before), keeps grad_norm and the loss on the device, and calls `log_async`. It flushes the previous logged step after queuing its forward and backward, the same place as the core trainer.
- `train()` flushes before validation and when training ends, so log lines keep their order.
- Host-to-device copies of the token counts and FLOPs use `non_blocking=True`, as in the core trainer.
- `MetricsProcessor.log()` is deleted. `log_async` takes `global_avg_loss`, `global_max_loss`, and `grad_norm` as tensors only. `num_flops` stays `float | torch.Tensor`, because the trainers pass a Python float when DP is off.

## User-facing changes
| | Before | After |
|---|---|---|
| torchft training log line of step N | printed during step N | printed during step N+1, after its work is queued |
| `MetricsProcessor.log()` | blocking log | deleted; use `log_async()` and `flush()` |

## Numerics / performance
Loss and grad_norm are unchanged; only when they are read changes. The divisions by the replica count are the same, applied to tensors instead of floats.

## Testing
- `test_ft_averages_logged_loss_and_flops_by_active_replica_count` mocks the tensor reductions, and checks the values passed to `log_async`, that the logged sums go through `ft_pg`, and that the step flushes.
- `pytest torchtitan/experiments/torchft/tests/test_torchft_trainer.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/observability tests/unit_tests/cpu/components/test_invalid_loss.py tests/unit_tests/cpu/components/test_validator.py tests/unit_tests/cpu/models/common/test_aux_loss.py`: 256 passed, 1 skipped.
- Not run: the 8-GPU torchft integration test (torchft is not installable here). CI runs it.

## Known issues / follow-ups
- An `ft_pg` collective error in the logged reductions now surfaces at the flush, during the next step, not at the logged step.

This change was written with an AI assistant (Claude).

stack-info: PR: #6468, branch: fegin/stack/49
@fegin
fegin merged commit 9a03490 into main Dec 1, 2026
28 checks passed
fegin added a commit that referenced this pull request Dec 1, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
#6132 makes the core trainer log through `MetricsProcessor.log_async`. The torchft trainer has its own `train_step` and still calls the blocking `MetricsProcessor.log()` with floats read by `dist_sum`, `dist_max`, and `.item()`. It is the only caller of `log()`, and the only reason `log_async` accepts floats for the loss and grad_norm. Moving it to `log_async` leaves one logging API with tensor-only loss and grad_norm.

The speedup for torchft is small: `TorchFTOptim` already waits for the device every step (`step_is_finite.item()`), and so does `should_commit()`. The main value is the API cleanup.

## What changed
- `FaultTolerantTrainer.train_step` reduces the logged values with `dist_sum_tensor` and `dist_max_tensor` (with `ft_pg`, as before), keeps grad_norm and the loss on the device, and calls `log_async`. It flushes the previous logged step after the next step's data is on the device and before `forward_backward`. The core trainer flushes after `forward_backward`, but here `zero_grad` in `forward_backward` starts the next quorum, which may reconfigure `ft_pg`, so the previous step's logging all-reduces on `ft_pg` must finish first, as they did before this change.
- `train()` flushes before validation and when training ends, so log lines keep their order.
- Host-to-device copies of the token counts and FLOPs use `non_blocking=True`, as in the core trainer.
- `MetricsProcessor.log()` is deleted. `log_async` takes `global_avg_loss`, `global_max_loss`, and `grad_norm` as tensors only. `num_flops` stays `float | torch.Tensor`, because the trainers pass a Python float when DP is off.

## User-facing changes
| | Before | After |
|---|---|---|
| torchft training log line of step N | printed during step N | printed during step N+1, before its forward |
| `MetricsProcessor.log()` | blocking log | deleted; use `log_async()` and `flush()` |

## Numerics / performance
Loss and grad_norm are unchanged; only when they are read changes. The divisions by the replica count are the same, applied to tensors instead of floats.

## Testing
- `test_ft_averages_logged_loss_and_flops_by_active_replica_count` mocks the tensor reductions, and checks the values passed to `log_async`, that the logged sums go through `ft_pg`, and that the step flushes before `forward_backward`.
- `pytest torchtitan/experiments/torchft/tests/test_torchft_trainer.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/observability tests/unit_tests/cpu/components/test_invalid_loss.py tests/unit_tests/cpu/components/test_validator.py tests/unit_tests/cpu/models/common/test_aux_loss.py`: 256 passed, 1 skipped.
- Not run: the 8-GPU torchft integration test (torchft is not installable here). CI runs it.

This change was written with an AI assistant (Claude).

stack-info: PR: #6468, branch: fegin/stack/49
fegin added a commit that referenced this pull request Dec 1, 2026
#6468)

Stacked PRs:
 * #6252
 * #5746
 * #6135
 * #6134
 * #6133
 * __->__#6468
 * #6132 (landed)
 * #5882 (landed)
 * #5881 (landed)


--- --- ---

### [torchft] Log training metrics without waiting for the device


## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
#6132 makes the core trainer log through `MetricsProcessor.log_async`.
The torchft trainer has its own `train_step` and still calls the
blocking `MetricsProcessor.log()` with floats read by `dist_sum`,
`dist_max`, and `.item()`. It is the only caller of `log()`, and the
only reason `log_async` accepts floats for the loss and grad_norm.
Moving it to `log_async` leaves one logging API with tensor-only loss
and grad_norm.

The speedup for torchft is small: `TorchFTOptim` already waits for the
device every step (`step_is_finite.item()`), and so does
`should_commit()`. The main value is the API cleanup.

## What changed
- `FaultTolerantTrainer.train_step` reduces the logged values with
`dist_sum_tensor` and `dist_max_tensor` (with `ft_pg`, as before), keeps
grad_norm and the loss on the device, and calls `log_async`. It flushes
the previous logged step after the next step's data is on the device and
before `forward_backward`. The core trainer flushes after
`forward_backward`, but here `zero_grad` in `forward_backward` starts
the next quorum, which may reconfigure `ft_pg`, so the previous step's
logging all-reduces on `ft_pg` must finish first, as they did before
this change.
- `train()` flushes before validation and when training ends, so log
lines keep their order.
- Host-to-device copies of the token counts and FLOPs use
`non_blocking=True`, as in the core trainer.
- `MetricsProcessor.log()` is deleted. `log_async` takes
`global_avg_loss`, `global_max_loss`, and `grad_norm` as tensors only.
`num_flops` stays `float | torch.Tensor`, because the trainers pass a
Python float when DP is off.

## User-facing changes
| | Before | After |
|---|---|---|
| torchft training log line of step N | printed during step N | printed
during step N+1, before its forward |
| `MetricsProcessor.log()` | blocking log | deleted; use `log_async()`
and `flush()` |

## Numerics / performance
Loss and grad_norm are unchanged; only when they are read changes. The
divisions by the replica count are the same, applied to tensors instead
of floats.

## Testing
- `test_ft_averages_logged_loss_and_flops_by_active_replica_count` mocks
the tensor reductions, and checks the values passed to `log_async`, that
the logged sums go through `ft_pg`, and that the step flushes before
`forward_backward`.
- `pytest torchtitan/experiments/torchft/tests/test_torchft_trainer.py
tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/observability
tests/unit_tests/cpu/components/test_invalid_loss.py
tests/unit_tests/cpu/components/test_validator.py
tests/unit_tests/cpu/models/common/test_aux_loss.py`: 256 passed, 1
skipped.
- Not run: the 8-GPU torchft integration test (torchft is not
installable here). CI runs it.

This change was written with an AI assistant (Claude).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants