Repository navigation
[trainer][perf] Log training metrics without waiting for the device - #6132
Conversation
d9ae8c1 to
d94e184
Compare
…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).
7847322 to
5b24f39
Compare
5b24f39 to
8177823
Compare
8177823 to
04f0605
Compare
04f0605 to
936f911
Compare
## 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
ee45e11 to
7c4ecc4
Compare
7c4ecc4 to
3ea90bb
Compare
|
@claude review this PR |
There was a problem hiding this comment.
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
torchtitan/distributed/utils.py:125--dist_meannow returns a tensor while its siblingsdist_sum/dist_maxreturn floats. Rename itdist_mean_tensorto matchdist_sum_tensor/dist_max_tensor(see inline).
Should consider
torchtitan/observability/metrics.py:665-- the deferredglobal_valid_tokenstrace record getsstep=N, but itsrelative_stepandstep_tagscome 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_startevent, but_PendingLogalready holds N's start and end events plus copies ofdata_loading_times, the token count and the peak stats. The flush therefore uses only N's window. A checkpoint saved betweenlog_asyncand the nextreset()is still outside the window. Validation:train()flushes beforevalidate(), andvalidator.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_hostaliases the tensor, but the CPU path has no graphs, andaccumulated_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 float64total / counton the device are the same IEEE operations as the previous Python-float division.- Callers of the changed APIs. torchft (
experiments/torchft/trainer.py) overridestrain/train_stepand still calls the synchronouslog().log()accepts the tensor-valuedcollect_aux_loss_metricsthere through_read. The RL trainer calls.item()where it needs floats. No other subclass overridestrain(), so the finalflush()covers flux and the base trainer. - Exception path. Not flushing in
exceptis defensible, sinceevent.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.
|
|
||
| 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: |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
should this be renamed
| def dist_mean(x: torch.Tensor, mesh: DeviceMesh) -> torch.Tensor: | |
| def dist_mean_tensor(x: torch.Tensor, mesh: DeviceMesh) -> torch.Tensor: |
| sl.log_trace_scalar( | ||
| {k: _read(v) for k, v in pending.trace_scalars.items()}, step=pending.step | ||
| ) |
There was a problem hiding this comment.
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.
|
|
||
| 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: |
There was a problem hiding this comment.
should this be renamed
| def dist_mean(x: torch.Tensor, mesh: DeviceMesh) -> torch.Tensor: | |
| def dist_mean_tensor(x: torch.Tensor, mesh: DeviceMesh) -> torch.Tensor: |
| step: Step to stamp on the records, for values emitted after their | ||
| step ended. Defaults to the step from ``set_step()``. |
There was a problem hiding this comment.
I didn't check all the ordering, but is this optionality needed? Can we require step?
There was a problem hiding this comment.
There are other callers which just rely only get_step() as they don't have the step information, like DCP.
| # 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.
what if we don't flush? what if we only flush if should_log is true on this step?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
can we make it async in RL trainer as well?
There was a problem hiding this comment.
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.
| 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, |
There was a problem hiding this comment.
why still accepting float?
There was a problem hiding this comment.
I opened a new PR to migrate TorchFT trainer as well. This way we don't need to accept float.
| global_avg_loss: float | torch.Tensor, | ||
| global_max_loss: float | torch.Tensor, | ||
| grad_norm: float | torch.Tensor, |
|
@claude review my review |
There was a problem hiding this comment.
Review of @tianyu-l's comments, one by one. All line numbers are at HEAD (3ea90bb).
-
distributed/utils.py:125, rename todist_mean_tensor: correct. The siblings aredist_sum/dist_max-> float anddist_sum_tensor/dist_max_tensor-> tensor, anddist_meannow returns a tensor. Apply the suggestion and update the only two callers,trainer.py:468andrl/trainer/trainer.py:395. -
structured_logging.py:316, makesteprequired: mistaken. Three other callers rely on the default:trainer.py:379,rl/controller/work_buffer.py:232andcomponents/checkpointer/dcp.py:507. Makingsteprequired means each of them passesstep=sl.get_step(), which is what the default already does. Only the deferred record inMetricsProcessor.flushneeds to override it. Keep it optional. The real gap is the one from my earlier review:jsonl_handler.py:100-127still fillsrelative_stepandstep_tagsfrom step N+1. Fix that by capturingrelative_stepalong withstep. -
trainer.py:404, don't flush, or flush only whenshould_log: mistaken. Both options mean the same thing, becauselog_asyncalready callsflush()first (metrics.py:632). Either way, step N's line would print at the next logged step,log_freqsteps late. Withlog_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'swindow_endevent only after step N+1's forward/backward is queued, so the event has almost always been reached. Keep the flush where it is. -
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. -
rl/trainer/trainer.py, make the RL trainer async too: not worth it today. Afteroptim_stepreturns, the controller runspush_model_state_dictbefore the next forward/backward (rl/controller/controller.py:1515-1528), and the push has to wait for the optimizer update. The comment atrl/trainer/trainer.py:204-207says "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 atcontroller.py:1517that overlaps the push with forward/backward. -
metrics.py:588/:619, why still acceptfloat: partly correct. Floats are still passed:num_flopsis a Python float on runs without DP (trainer.py:422), and the torchft experiment callslog()with floats (experiments/torchft/trainer.py:499).extra_metricsalso mixes in ints and floats (n_tokens_seenwithout DP, lr). Forglobal_avg_loss,global_max_lossandgrad_norm, core always passes tensors now, and only torchft needs thefloathalf.num_flopsmust stayfloat | torch.Tensor. The three loss/norm parameters can be narrowed totorch.Tensoronly 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
left a comment
There was a problem hiding this comment.
please fix the dist_mean_tensor naming
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
## 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
## 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
#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).
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. Withlog_freq=1this 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=...).#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_asynctakes 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()islog_async()plusflush(), so other callers keep their behavior.non_blocking=True. A blocking copy from pageable memory waits for the previous optimizer update.Trainer.train_stepcallslog_asyncand 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.log_asynccall. It is timed with device events recorded atreset()and atlog_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 atlog_async, so data the next step fetches before the flush is not counted.dist_sum_tensor, a newdist_max_tensor, anddist_mean_tensor(renamed fromdist_meanto match the other two).collect_aux_loss_metricsreturns device scalars, divided in float64 as before, and the RL trainer converts them where it needs floats.global_valid_tokenstrace record is passed tolog_asyncapart from the metrics and emitted at the flush.log_trace_scalartakes optionalstepandrelative_step, so the record keeps the step it belongs to. Its step tags come from the step that flushes it.User-facing changes
dist_meandist_mean_tensor, returns a device tensorcollect_aux_loss_metricsThe 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: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_losseschecks the values passed tolog_asyncand 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 withCUDA_VISIBLE_DEVICES=(no accelerator).log_freq=1andlog_freq=10, and for PP 2 with 1F1B (llama3_debugmodel_pp2_1f1b) with 10 steps atlog_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 ametrics_processor, sincetrain()flushes before validation.Known issues / follow-ups
This change was written with an AI assistant (Claude).