Repository navigation
[trainer][torchft] Log training metrics without waiting for the device - #6468
Conversation
## 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
|
@claude review this PR |
|
Claude finished @fegin's task in 2m 25s —— View job Needs discussion: the API cleanup looks fine, but step N's |
There was a problem hiding this comment.
Verdict: Needs discussion -- the API cleanup is fine, but the change also moves step N's ft_pg logging all-reduces past step N+1's start_quorum(), and nobody has checked whether that is safe when membership changes.
What this PR does. It switches the torchft trainer from the blocking MetricsProcessor.log() with float reductions to log_async() with tensor reductions (dist_sum_tensor/dist_max_tensor over ft_pg), plus flush() calls in the same places as the core trainer. It then deletes log() and narrows the loss and grad_norm parameters of log_async to tensors only. log() had no other caller: the RL metrics_processor.log belongs to a different class.
Example. Logged step N with async quorum, a replica rejoins before step N+1:
before: optim_step(N) -> all_reduce(loss, ft_pg) -> .item() waits -> step N+1: zero_grad -> start_quorum (reconfigures replicate_pg)
after: optim_step(N) -> all_reduce(loss, ft_pg) -> log_async (no wait) -> step N+1: zero_grad -> start_quorum (reconfigures replicate_pg) -> ... -> flush() waits on step N's all_reduce
Questions
torchtitan/experiments/torchft/trainer.py:428-- Is it safe for an in-flight collective onreplicate_pgto overlap a quorum reconfiguration? If not, or if nobody knows, flushing at the top oftrain_stepis a one-line move that keeps the cleanup. Details are inline.- The 8-GPU torchft integration test didn't run locally. Does any CI torchft test kill or restart a replica? A plain run wouldn't exercise this ordering.
Should consider
- Description, "Why":
TorchFTOptim._updatealready waits for the device on every step (step_is_finite.item(),optimizer.py:166), and so doesshould_commit(). The torchft step therefore gains little overlap from this change. The real motivation is the API cleanup that the human-written summary gives. Saying so would make the flush placement an easier call.
Details
- Checked the in-place ops on tensors that are now reduced:
global_avg_loss /= ft_pg.size()andmean_num_flops /= ...only run when a reduction produced a fresh tensor. They never modifyaccumulated_loss. - Semi-sync (
ft_pg is None) and the path without DP/CP behave the same as the core trainer. dist_sum/dist_max(float versions) still have callers (components/validator.py,models/flux/validator.py,rl/trainer/trainer.py), so they are not dead code.- Overlap search:
gh pr list --search "log_async"and"torchft trainer metrics"found only this PR and its base #6132.
Not verified: torchft ManagedProcessGroup reconfigure/abort behavior with a pending funcol all-reduce (torchft isn't installed here).
| ) | ||
| # 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() |
There was a problem hiding this comment.
This flush now runs after engine.forward_backward() of step N+1, and that call runs optim.zero_grad(), which calls TorchFTOptimizersContainer.zero_grad -> _quorum_manager.start_quorum() (optimizer.py:107-110). So step N's logging all-reduces on ft_pg (replicate_pg) can still be pending when the quorum for N+1 starts. Before this PR, the .item() in dist_sum/dist_max drained them inside step N.
If the quorum changes membership (a replica leaves or rejoins), torchft reconfigures replicate_pg while that collective may still be in flight. I couldn't check torchft's configure/abort behavior here, so this is unverified. It could show up as an error raised from flush() in the middle of step N+1, or as a corrupted loss value. The description's known issue covers ft_pg errors but not this ordering against the quorum.
If that ordering isn't known to be safe: flush at the top of train_step, before forward_backward. That keeps all of the API cleanup. The overlap you lose is small, because TorchFTOptim._update already calls step_is_finite.item() on every step (optimizer.py:166).
There was a problem hiding this comment.
[CLAUDE on behalf of fegin] Moved the flush to just before forward_backward, after the next step's data is on the device. zero_grad in forward_backward starts the quorum, so the previous step's ft_pg logging all-reduces now finish before any reconfigure, as they did before this PR. The unit test checks the order. I also rewrote "Why": torchft already waits for the device every step (step_is_finite.item(), should_commit), so this PR is mainly the API cleanup.
…6132) Stacked PRs: * #6252 * #5746 * #6135 * #6134 * #6133 * #6468 * __->__#6132 * #5882 (landed) * #5881 (landed) --- --- --- ### [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=...)`. ```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).
## 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
|
@claude re-review the updated PR and responses. |
|
Claude finished @fegin's task in 1m 27s —— View job Approve: the flush now runs before |
There was a problem hiding this comment.
Verdict: Approve -- the flush now runs before forward_backward, so step N's ft_pg logging all-reduces finish before step N+1's start_quorum() again, and nothing else is left to fix.
What this PR does. The torchft trainer used the blocking MetricsProcessor.log() with float reductions. It now calls log_async() with tensor reductions (dist_sum_tensor/dist_max_tensor over ft_pg) and flushes before forward_backward, before validation, and when training ends. With its last caller gone, log() is deleted, and log_async takes the loss and grad_norm as tensors only.
Example. Logged step N with async quorum, and a replica rejoins before step N+1:
main: optim_step(N) -> all_reduce(loss, ft_pg) -> .item() waits -> step N+1: zero_grad -> start_quorum
HEAD: optim_step(N) -> all_reduce(loss, ft_pg) -> log_async -> step N+1: load data, dp token all_reduce
-> flush() waits on step N's ft_pg all_reduce -> forward_backward: zero_grad -> start_quorum
Earlier review
- Resolved:
trainer.py:424-- the flush now comes beforeengine.forward_backward(), andforward_backwardcallsoptim.zero_grad()first (training_engine.py:702), which callsstart_quorum()(optimizer.py:107-110). The test checks theflush->forward_backwardorder. - Resolved: the "Why" section now says the main value is the API cleanup.
- Moot: the question about a torchft CI test that kills a replica. The order against the quorum is the same as on
main, so no new interaction needs coverage.
Details
step_last_logis set inlog_async, not inflush, so thereset()check at the top oftrain_stepstill fires right after a logged step, even though the flush comes later.DataloaderExhaustedErroris raised innext(data_iterator)before the flush. The loop then breaks, and the flush after the loop emits the pending step while still insidemaybe_semi_sync_training.- Semi-sync:
loss_sync_pgreturnsNonewhenuse_async_quorumis off (manager.py:189), so no logging collective runs on an FT-managed group in that mode. - Step N's
ft_pgall-reduces are now still pending duringengine.save_checkpoint()of step N. A recovering replica reads the state dict while the quorum heals, and that now happens after the flush. Saving to disk doesn't reconfigurereplicate_pg. - Test mock:
dist_sum_tensor(value, mesh, *ft_pg)treats a passedft_pg=Noneas a logged sum ((None,)is truthy), so theuse_ft_pg=Falsecases count correctly. - Overlap search:
gh pr list --search "log_async"and"torchft trainer"found no other open PR that changes this code.
Not verified: the 8-GPU torchft integration run (torchft isn't installed here).
Before merge: fill in the human-written summary.
Stacked PRs:
[torchft] Log training metrics without waiting for the device
Summary (human-written)
Why
#6132 makes the core trainer log through
MetricsProcessor.log_async. The torchft trainer has its owntrain_stepand still calls the blockingMetricsProcessor.log()with floats read bydist_sum,dist_max, and.item(). It is the only caller oflog(), and the only reasonlog_asyncaccepts floats for the loss and grad_norm. Moving it tolog_asyncleaves one logging API with tensor-only loss and grad_norm.The speedup for torchft is small:
TorchFTOptimalready waits for the device every step (step_is_finite.item()), and so doesshould_commit(). The main value is the API cleanup.What changed
FaultTolerantTrainer.train_stepreduces the logged values withdist_sum_tensoranddist_max_tensor(withft_pg, as before), keeps grad_norm and the loss on the device, and callslog_async. It flushes the previous logged step after the next step's data is on the device and beforeforward_backward. The core trainer flushes afterforward_backward, but herezero_gradinforward_backwardstarts the next quorum, which may reconfigureft_pg, so the previous step's logging all-reduces onft_pgmust finish first, as they did before this change.train()flushes before validation and when training ends, so log lines keep their order.non_blocking=True, as in the core trainer.MetricsProcessor.log()is deleted.log_asynctakesglobal_avg_loss,global_max_loss, andgrad_normas tensors only.num_flopsstaysfloat | torch.Tensor, because the trainers pass a Python float when DP is off.User-facing changes
MetricsProcessor.log()log_async()andflush()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_countmocks the tensor reductions, and checks the values passed tolog_async, that the logged sums go throughft_pg, and that the step flushes beforeforward_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.This change was written with an AI assistant (Claude).