Skip to content

Add async logging - #2728

Closed
drisspg wants to merge 1 commit into
drisspg/stack/4from
drisspg/stack/5
Closed

drisspg wants to merge 1 commit into
drisspg/stack/4from
drisspg/stack/5

Conversation

@drisspg

@drisspg drisspg commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


Add async logging

I set this by default but curious if there is interest

~/.venvs/nightly/bin/torchrun --nproc-per-node=1 -m torchtitan.train \
    --module llama3 --config llama3_debugmodel \
    --training.steps 200 \
    --training.local-batch-size 64 \
    --training.seq-len 8192 \
    --metrics.log_freq 5

Running before after on my b200 gives me non trivial speedups:
image
However in real workloads you can do other things ( log less frequently)

drisspg added a commit that referenced this pull request Mar 27, 2026
stack-info: PR: #2728, branch: drisspg/stack/5
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 27, 2026
@wwwjn

wwwjn commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

@felipemello1 has a stack of PR working on observability, it might also be covered

Update: After reading this PR and I realize this PR and @felipemello1 are doing different level of "Async". This PR is doing non-blocking D2H copy, but @felipemello1 's is async file aggregation. Maybe can consider consolidating? Both are interesting

@drisspg
drisspg marked this pull request as draft March 27, 2026 02:00
@drisspg
drisspg changed the base branch from drisspg/stack/4 to main March 27, 2026 02:00
drisspg added a commit that referenced this pull request Mar 27, 2026
stack-info: PR: #2728, branch: drisspg/stack/5
@drisspg
drisspg changed the base branch from main to drisspg/stack/4 March 27, 2026 02:00
@drisspg
drisspg marked this pull request as ready for review March 27, 2026 02:00
stack-info: PR: #2728, branch: drisspg/stack/5
@drisspg
drisspg marked this pull request as draft March 27, 2026 02:34
@drisspg
drisspg changed the base branch from drisspg/stack/4 to main March 27, 2026 02:34
@drisspg
drisspg changed the base branch from main to drisspg/stack/4 March 27, 2026 02:35
@drisspg
drisspg marked this pull request as ready for review March 27, 2026 02:35
@tianyu-l

Copy link
Copy Markdown
Contributor

Agreed that we should merge with @felipemello1 's work. In particular, the metrics logger should be able to handle both GPU metrics and CPU metrics.

@felipemello1

felipemello1 commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

SixLib has something like this, but for dtensors. They use a context manager to store references to the dtensor, so you can just call "add_summary(key, tensor)" from anywhere. At the end of training, they call "replicate_to_host", that groups and does all_reduce only once.

The key difference is that since its a dtensor, they dont have to pass the mesh.

I had a PR for this, but realized that our activations are not dtensor as in sixlib, so their APIs didnt work quite well. I put it on hold until the dtensor changes in Titan are finalized.

I am going to come back to this soon, and the idea is to enable computing metrics more deep into titan stack, so we can have more visibility into tensor related metrics, e.g. in MoE paths, like llama4x has.

If we can wait a bit more, I would prefer to share an RFC and we can think about it, otherwise, I am happy to review this PR and can land it in between.

@tianyu-l

Copy link
Copy Markdown
Contributor

@felipemello1
IMO we can and should wait.

One thing I didn't understand from your comment:

At the end of training, they call "replicate_to_host", that groups and does all_reduce only once.

Is this happening every iteration, or only once per training job? If it's the former, that's exactly what this PR is trying to avoid? i.e. the sync between GPU and CPU due to per-iteration logging.

fegin added a commit that referenced this pull request Jul 7, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ #3873

#3863 introduces a good
feature to raise if loss is NaN but also introduces per-micro-batch D2H
sync. This PR fixes the issue with the penalty that the actual batch
that causes the NaN is unkown (within a certain range).

#2728 is a potential solution
to remove the penalty.

Another mitigation from @mlazos: you could also copy N loss values on
GPU to keep a record of which of the N steps had the NaN.
@drisspg drisspg closed this Jul 10, 2026
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Jul 10, 2026
jemitche1 pushed a commit to jemitche1/torchtitan that referenced this pull request Jul 15, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ pytorch#3873

pytorch#3863 introduces a good
feature to raise if loss is NaN but also introduces per-micro-batch D2H
sync. This PR fixes the issue with the penalty that the actual batch
that causes the NaN is unkown (within a certain range).

pytorch#2728 is a potential solution
to remove the penalty.

Another mitigation from @mlazos: you could also copy N loss values on
GPU to keep a record of which of the N steps had the NaN.
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
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Nov 23, 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 added a commit that referenced this pull request Dec 1, 2026
## 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 added a commit that referenced this pull request Dec 1, 2026
…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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants