Skip to content

Add distributed tensor logging - #4202

Draft
felipemello1 wants to merge 7 commits into
pytorch:mainfrom
felipemello1:codex/69-tensor-logging-v4-pr1-core
Draft

felipemello1 wants to merge 7 commits into
pytorch:mainfrom
felipemello1:codex/69-tensor-logging-v4-pr1-core

Conversation

@felipemello1

@felipemello1 felipemello1 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: A recipe that sets Trainer.Config.tensor_logger gets 8 statistics (rms, abs_max, kurtosis, ...) of each tensor the model code logs, and of its gradient, every log_freq steps. Each statistic covers the whole tensor over all ranks, under FSDP, TP, CP, PP and EP. Unset (the default), loss and grad_norm stay bitwise equal to main wherever main repeats itself bitwise. On llama3 8B (FSDP 4, 4 GB300), a recorded step is 3.7% slower than main, and the other steps are as fast as main.

main:     one value per step for the whole model (loss, grad_norm, lr, aux-loss means)
this PR:  + 8 fields per logged tensor, every log_freq steps, e.g.
            tensor_logger/layers.3.attention.xq.fwd.rms   0.92    forward value
            tensor_logger/layers.3.attention.xq.bwd.rms   1e-05   its gradient

on a recorded step:
  forward    log_fwd_bwd(self, xq=xq_THK): a kernel adds xq's 7 sums + 1 max into its row
  backward   a gradient hook runs the same kernel on xq's gradient
  after      collect(): one SUM and one MAX all-reduce over all ranks -> the published fields
# recipe
config.tensor_logger = TensorLogger.Config(log_freq=10)
# GQAttention.__init__
tensor_logger.register_fwd_bwd(self, "xq", "xk", "xv", "head_out")
# GQAttention.forward (head_out is logged after attention)
tensor_logger.log_fwd_bwd(self, xq=xq_THK, xk=xk_THK, xv=xv_THV)

A recorded step is a step that is a multiple of log_freq. Every other step is an off step.

Why

  1. Today. Main publishes one value per step for the whole model: loss, grad_norm, lr and each aux loss's mean. None is per layer.
  2. The gap. When one layer's activations spike or die, loss and grad_norm move late, and they do not say which layer.
  3. Shards. A local hook sees only part of a tensor. FSDP and DP split the batch, CP the sequence, TP the heads or hidden size, EP the tokens. Under PP, only one rank (the first rank of the last stage) publishes metrics.
  4. Main already waits for it. models/common/aux_loss.py has a TODO to move its metric reduction onto this logger.
  5. This PR. Each logged tensor gets a row: 7 sums and 1 max in a buffer built at init. Each rank adds its shard into the row. After backward, a SUM and a MAX all-reduce merge the rows, so each row describes the whole tensor.

What changed

  • torchtitan/observability/tensor_logger/ (new):
    • statistics.py: the custom op torchtitan::accumulate_tensor_statistics and its CPU reference kernel.
    • statistics_triton.py: the GPU kernel. A device flag makes it exit at once on off steps.
    • api.py: TensorLogger and its Config(log_freq), plus register_fwd, register_fwd_bwd, log_fwd, log_fwd_bwd.
    • README.md: how to enable it, the callsite rules, the fields, cost and limits.
  • trainer.py: the field tensor_logger: TensorLogger.Config | None = None, config checks, maybe_record(step) around forward and backward, collect() into the step's metrics, close().
  • Model callsites, a few lines each: the shared Decoder, GQAttention, DenseFeedForward and MoE. Models that override those forwards make the same calls: deepseek_v3 (MTP), deepseek_v4, kimi_k2_7, kimi_k3, muse_glimmer, muse_spark, qwen3_5.
  • Callsite rules (README): stay outside local_compile regions, and never log a partial sum (log_fwd_bwd takes no replicated tensor, whose gradient is a partial sum).
  • These raise ValueError at config time: PP schedules that split the backward (and schedule CSV files), sdc_replayer, GraphTrainer, FaultTolerantTrainer, and a log_freq that is not a multiple of metrics.log_freq.

You may ask:

  • Why calls in forward, not module hooks? A hook sees only a module's inputs and outputs, so the logger would depend on each model's submodule names and output tuples (qkv_linear returns xq, xk and xv together). A call in forward names the tensor where it is made, the same way in every model.
  • Why not full_tensor() and torch stats on one rank? That gathers every logged activation, MBs per tensor per step. Here each row all-reduces 32 B.
  • Why a Triton kernel, not torch ops? A captured graph replays every call on every step. A flag read inside the kernel skips the work with no host sync and no second graph.
  • Why register rows in __init__? Graph capture needs the buffer at a fixed address, and the all-reduces need the same row order on every rank, before step 1.
  • Why float32 sums? Half the memory and all-reduce bytes of float64. numel stays exact up to 2^24 elements per row and step, and keeps about 7 significant digits above that.

Numerics / performance

Numerics: with the logger off or on, loss and grad_norm are bitwise equal to main in every cell where main repeats itself bitwise. The cells that differ are the 4 where two main runs also differ.

Runs compared: main; off = this PR, field unset; on = log_freq=2; probe = a test-only logger that logs known tensors and raises on any wrong statistic. A cell is one model x layout x mode. Most cells use flex attention, which repeats bitwise on main. Four cells use varlen attention: one llama3 and one deepseek_v3 cell on purpose, and muse_glimmer multimodal and kimi_k3 by their recipe default.

this PR c6267a626 vs main 6a2292d00 (= base 828961319 except .claude/CLAUDE.md), GB300
10 steps per run (step-time cells 30-40), 61 cells, 236 runs (212 + 24 oracle)
check                                     cells   result
logger off vs main: loss, grad_norm       43      bitwise equal in 39; 4 within main's own noise (1)
logger off vs main: peak memory           43      equal in 38; +512 B in 4 (2); gpt_oss -35 KB, while two
                                                  main runs differ by up to 0.95 GiB on some steps
logger on vs logger off: loss, grad_norm  42      bitwise equal in 40; 2 within noise (1)
probe vs logger off: loss, grad_norm      51      bitwise equal in 48; 3 within noise (1)
logger on: extra peak memory              43      = its 3 buffers, each rounded up to 512 B: 3072 B for
                                                  73 rows (llama3 debug), 2048 B for 35 rows (deepseek_v3
                                                  debug); +512 B more on 2 cells (2); llama3 8B +16 KB for
                                                  13.5 KB of buffers (3)
probe: exact statistics                   55      exact on every recorded step of all 55 runs
1-GPU oracle                              20      8336 step-1 statistics agree with the 1-GPU run (4)

(1) llama3 and deepseek_v3 with varlen attention, gpt_oss, flux: two main runs differ within 10 steps
    (gpt_oss: loss up to 1.2e-3, grad_norm up to 2.3e-2 relative). This PR stays within 2x main's own
    difference, and step-1 loss is bitwise equal.
(2) One allocator block. Two main runs differ by the same 512 B, and the same main commit run from
    another directory is also +512 B.
(3) TensorBoard stores memory as float32 GiB, so near 74 GiB a difference is known to 8 KB.
(4) fp32, same seed weights, and every DP rank gets the 1-GPU batch, so forward fields equal the 1-GPU
    run and gradients are 1/DP of it. Counts exact; abs_mean, rms, abs_max within 1e-3 relative;
    kurtosis within 1e-2 of (kurtosis + 3); zero_frac within 1e-6 (forward) or 1e-4 (gradient).

models:  llama3, deepseek_v3 (+MTP), deepseek_v4, qwen3, qwen3 MoE, qwen3_5, qwen3_6, gpt_oss,
         kimi_k2_7, kimi_k3, muse_glimmer multimodal, muse_spark, flux (logger off only)
layouts: 1 GPU, FSDP 2/4, HSDP 2x2, TP 2 (with and without SP), CP 2, EP 2 (with FSDP or TP),
         PP 2 (1F1B, Interleaved1F1B, GPipe, LoopedBFS), TP2xCP2, TP2xCP2xEP2, PP2xTP2, PP2xTP2xEP2,
         FSDP4xEP2
modes:   default (accelerator graphs, local compile, default remat), eager, full remat, gradient
         accumulation 2/4, graphs per microbatch group, SPMD type checking, validation every 2 steps
         (also with PP)
llama3 8B, FSDP 4 on 4 GB300, accelerator graphs on, flex, W&B + TensorBoard on, one run per arm
median step time over steps 4-30          main       this PR
logger off, all steps                     650.3 ms   646.7 ms   -0.6%
logger on (log_freq 2), off steps         649.0 ms   649.5 ms   +0.1%   (odd steps)
logger on (log_freq 2), recorded steps    651.8 ms   676.0 ms   +3.7%   (even steps)
logger on: 385 rows, 3080 extra scalars per recorded step

NOTE: In a CPU-bound run, the metric loggers pay for the extra scalars. Example: llama3 debug, eager, FSDP 2, log_freq=2, TensorBoard writing 584 extra scalars. Recorded steps took 103.0 vs 85.1 ms on main, and the off step after each took 118.6 vs 86.9 ms. With no metric logger (times from the console tokens/s), recorded steps took 97.7 vs 96.0 ms, and off steps matched main (89.7 vs 89.8 ms).
NOTE: Not run: 8-GPU 3D/4D layouts (the test machine has 4 GPUs, and no CI entry enables the logger on 8 GPUs), multi-node, ROCm. All runs used GB300 GPUs.

Testing

  • pytest tests/unit_tests/cpu/observability/test_tensor_logger.py: each forward counts once under Full and Default remat; cadence and derived fields; a parameter passed to log_fwd_bwd raises; split-backward and CSV PP schedules, sdc_replayer and a bad log_freq raise.
  • pytest tests/unit_tests/gpu/observability/test_tensor_logger.py: the Triton kernel matches the CPU kernel (fp32, bf16); a graph captured on an off step records on replay; every callsite runs once per microbatch for llama3, deepseek_v3, kimi_k3 and muse_glimmer.
  • Integration pp_looped_1f1b: llama3_debugmodel_pp4_interleaved_1f1b now always runs with the probe (real process groups, log_freq=1). It fails on a wrong row order across stages, double counts from PP metadata inference, or a wrong MAX.
  • Integration 2d_eager_no_sp: llama3_debugmodel_tp2_no_sp now always runs with the logger on (log_freq=2) under SPMD type checking. It fails if a logging call or gradient hook breaks SPMD type checking (register_hook has no sharding rule).
  • test_ft_rejects_tensor_logger: FaultTolerantTrainer with tensor_logger raises at config time. GraphTrainer raises too, checked by hand (no unit test).
  • Stress matrix: the Numerics block above.

Follow-ups

  • A public sanity-check switch (the probe above, outside tests).
  • Let a run log a subset of rows by name (TODO in tensor_logger/api.py).
  • Move aux-loss metrics onto the tensor logger (TODO in models/common/aux_loss.py).
  • GraphTrainer support.
  • PP schedules that split the backward.
  • The RL trainer.
  • An lm_head output row, and a tok_embeddings.output gradient row where its layout allows it.
  • Step time on a multi-node production run.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 18, 2026
Comment thread torchtitan/models/common/decoder.py Outdated
self.norm = config.norm.build()
self.lm_head = config.lm_head.build()
tensor_logging.register_fwd_bwd(self, ["input"])
tensor_logging.register_fwd_bwd(self.lm_head, ["output"])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Later on some PP stage, PP constructor will delete lm_head. In that case, what happens?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: This PR no longer logs lm_head. That row is left for a follow-up. The embedding output is a forward-only row on tok_embeddings, and each layer output is a row on its layer.
When the PP split drops a module (_split_module sets tok_embeddings to None and deletes other stages' layers), its rows go with it. Every rank uses the sorted union of all ranks' row names, so the owning stage writes the row and the others add 0 (max: -inf).
In CI, the PP4 Interleaved1F1B test runs a probe that checks every row is observed exactly once per microbatch.
Commit: 6d9949e

Comment thread torchtitan/trainer.py Outdated
Comment on lines +71 to +74
_SUPPORTED_TENSOR_LOGGING_PP_SCHEDULES = {
"1F1B",
"Interleaved1F1B",
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

putting this as the top line of torchtitan looks weird, let's just hard code them inline for now

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done. The allowed schedules (1F1B, GPipe, Interleaved1F1B, LoopedBFS) are an inline tuple in Trainer.Config.__post_init__, with a TODO for split-backward schedules. The module-level constant is gone.
Commit: 7c05147

Comment thread torchtitan/trainer.py Outdated
# logging operations in the CUDA graph. The existing
# `set_enabled()` scope still decides whether this step writes
# statistics.
self.fwd_bwd_fn = _wrap_fwd_bwd_for_tensor_logging_capture(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

do this within wrap_with_cuda_graph -- you can pass a boolean of whether doing tensor logging

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: The wrapper is gone. The boolean (engine._forward_backward_accelerator_graph_enabled) goes to TensorLogger at build, not to wrap_fwd_bwd_with_accelerator_graph. The logger decides whether its calls run, so the graph helper needs no logger code.
With graphs on, the log calls run on every step, and the device flag enabled decides whether the kernel writes. So a capture on a non-recording step still records on later recording steps.
test_graph_capture_on_a_non_recording_step_keeps_logging captures on step 3 (not recorded) and checks that steps 4 and 6 record.
Commit: 7c05147

Comment thread torchtitan/trainer.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

just realized that we should rename this to

Suggested change
with self.foward_backward_context():

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Main no longer has train_context. Forward and backward now run under parallelism_context.activate_spmd(...) in TrainingEngine, so there is nothing to rename in this PR.

Comment thread torchtitan/trainer.py Outdated
is_tensor_logging_step = (
self.tensor_logging is not None
and self.metrics_processor.should_log(self.step)
and self.step % config.metrics.tensor_logging.freq == 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

tensor log step should always align with metrics processor log step, any exception?

@felipemello1 felipemello1 Aug 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

we enforce least common multiple. But you may want to log every step and tensor log every 10, for example, give that there is a perf hit.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Then tensor log step should divide metrics log step

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done. tensor_logger.log_freq must be a multiple of metrics.log_freq, or Trainer.Config.__post_init__ raises ValueError. So every tensor step is a metrics step.
Example: metrics every step and tensors every 10 steps is valid. Metrics every 6 steps and tensors every 10 raises.
Commit: 7c05147

return value.to_local() if isinstance(value, DTensor) else value


def register(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'd prefer we have

  • register_fwd as public API
  • both register_fwd and register_fwd_bwd call into another _register

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done. register_fwd and register_fwd_bwd both go through _register. register_fwd_bwd calls register_fwd and then adds the gradient rows.
Both take one or more names, e.g. register_fwd_bwd(self, "xq", "xk", "xv", "head_out") in GQAttention.
Commit: 7c05147

Comment thread torchtitan/trainer.py Outdated
)

# Model buffers and parallel wrappers are final before slots are assigned.
self.tensor_logging = tensor_logging.init(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

OK here's another confusion I have:

  • on one hand, we really want tensor_logger to be a "global" module, because we would like to do structured_logger type of "ad hoc" usage, without passing the tensor logger into each model
  • on the other hand you have this object tensor_logging.TensorLoggingState -- but this could be global as well? Just change everything starting with self.tensor_logging.xyz to observability.tensor_logging.xyz. So I wonder what's the consideration here.
  • Now even if we stick with current design, we should rename TensorLoggingState to TensorLogger and do TensorLogger.Config.build() instead of a module level init(). And move it out of config.metrics.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done as in your last point, and the callsites stay global. Model code calls module functions (tensor_logger.log_fwd_bwd(self, ...)) and never receives a logger, like structured_logger.
The state is an object because it depends on the built, parallelized model: buffers sized by the row count, the process group, the PP cleanup hook, and close().
It is TensorLogger, built by Trainer.Config.tensor_logger.build(...). The field moved out of config.metrics.
Commit: 7c05147

# Prevent FullAC replay from double-counting tensor statistics.
return ptd_checkpoint_wrapper(
module,
context_fn=_full_ac_contexts,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is using SAC api to "pretend" Full AC -- not sure if there's any caveat @soulitzer

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

hey @soulitzer , your previous comment was on my local branch, sorry -.-`

image

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@felipemello1 whoops! thanks for copying it over lol

@tianyu-l should be fine, but probably no longer necessary to do anyway since context_fn should be sufficient for eager and compile shouldn't replay side effects even w/o the SAC annotations

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: This code is gone. Main replaced FullAC/SAC with torch_remat, and the logger sets no checkpoint policy.
Your point held in a CPU probe: a compiled checkpoint did not replay a buffer-mutating stats op. Eager torch_remat does replay the forward, so the log calls return while remat.is_recomputing() is true.
Log calls inside compiled regions are not supported in this PR. The README says to keep callsites outside local_compile regions.
Commit: 7c05147

from torchtitan.tools.logging import logger


_FORWARD_MUTATION_OPS = {accumulate_tensor_statistics._opoverload}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

just call it "tensor logger ops"?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: The constant went away with activation_checkpoint.py on main. The logger adds no op list to any remat policy.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@soulitzer @pianpwk please help review

@anijain2305 with torch_remat we need to support tensor logger as well

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

deferring to Jeffrey lol

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done for torch_remat. While remat.is_recomputing() is true, the log calls return at once. So a replay records nothing and adds no gradient hook.
test_remat_records_each_observation_once runs Full and Default remat, in gradient-accumulation order and in PP order. The published stats equal a run without remat exactly.
Commit: 7c05147

# Full-graph compile needs mutation ops preserved in its selective cache.
from torchtitan.observability.tensor_logging.runtime import _is_installed

if torch.compiler.is_compiling():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The other way to do it would be do this branching outside of the full_ac context. This means we can also avoid registering context at all to the compile, non-logging case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Obsolete now. Main deleted the FullAC checkpoint contexts, and the logger registers no checkpoint context, compiled or not.

lambda _context, _op, *args, **kwargs: CheckpointPolicy.PREFER_RECOMPUTE
)

# Eager FullAC can suppress replay directly. Keeping this a plain context is

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What do you mean be suppress replay directly?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: It meant this: eager FullAC used a plain context that set a Python flag around the recompute, and the log calls returned while it was set. No selective-checkpoint policy was involved.
On main, torch_remat.is_recomputing() gives the same signal, so that context is deleted.

# A compiled checkpoint context must return TorchDispatchModes even
# when tensor logging is disabled. This policy is the no-save form.
return create_selective_checkpoint_contexts(
lambda _context, _op, *args, **kwargs: CheckpointPolicy.PREFER_RECOMPUTE

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is it fine to not save top-k here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: That branch is deleted. On main, MoE expert choice is the routing_decision region with recompute=False. So top-k is never replayed, with or without the logger.

"""Save nondeterministic routing and metric mutations during recomputation."""

# `topk` can choose different experts during recompute. Reuse the choices
# made by the original forward.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is this because of the router mm computing different results during replay and saving that would be the same, or because of top-k itself being not deterministic?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: The old code did not depend on which one. It only made the recompute reuse the expert choice of the original forward.
On main, the routing_decision region (recompute=False) gives that for every remat policy, so the logger saves nothing.


# Eager FullAC can suppress replay directly. Keeping this a plain context is
# important for CP, whose FlexAttention operator is itself compiled and
# cannot be replayed through selective-checkpoint storage.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hmm it shouldn't actually go through SAC storage if everything is marked recompute.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Agreed. That comment and code path are gone with main's move to torch_remat, and the logger adds no checkpoint context.


create_contexts.assert_not_called()
with forward_context, recompute_context:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I might be missing something, but what is this one testing haha

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: It only asserted on a mock. The code it tested is gone on main, so the test is not ported.
The new test_remat_records_each_observation_once applies real torch_remat policies and compares counts and stats with a run without remat.
Commit: 7c05147

|a| sum of absolute values
x2 sum of squared values
x4 sum of fourth powers
```

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

i was wondering about if someone wanted to log an extra stat, but then the computation is all a single kernel, so extensibility vs. performance is hard anyways?

@felipemello1 felipemello1 Aug 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We need to preallocate the buffer. But once we do, it is not opinionated if its calculating 5 or 10 metrics. I think that the stats are pretty extensive though. Is there any stat you think is missing?

The extensibility portion seems more related to custom ops, e.g. "for MoE metric X first reduce on mesh M, then take the mean on dim D and compute the max."

But we would need to think a bit more careful about it, if we design a general solution or a per module solution.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is there any stat you think is missing?

nothing in particular, just curious :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Right. One kernel reads the tensor once and fills 7 fixed sum columns plus one max per row. A new statistic means a new column and a kernel edit.
This PR adds no API for custom statistics or per-module reductions. That needs its own design.
Commit: 3ecc4fb


### Which regular pipeline schedules support tensor logging?

Only `1F1B` and `Interleaved1F1B`. Tensor logging uses an explicit allowlist and fails during setup for ZBVZeroBubble, DualPipeV, or any other schedule until a focused test proves complete forward and backward metric coverage.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

just curious, is this for all metrics, or just some subset of them, or from interaction with other components? seems nice to fix in future

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: It is about gradient rows, not all metrics. Schedules that split backward run a separate weight-gradient pass. In a CPU probe, a hook on a linear layer's output fired twice (input pass, then weight pass), while a hook on the next op's output fired once.
So the logger allows only schedules with one full backward per microbatch (1F1B, GPipe, Interleaved1F1B, LoopedBFS) and no schedule CSV. The TODO at that check names a fix: an identity autograd.Function, which fired once in the same probe.
Commit: 7c05147

slot: StatisticBufferSlot,
value: torch.Tensor,
) -> None:
with spmd.no_typecheck():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: can probably use @spmd.no_typecheck decorator form.

but also typechecking should be off for non-FWD-BWD stuff, I would more broadly no-typecheck metrics processing, e.g. decorate collect()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done for the stats call: TensorLogger._accumulate now has @spmd.no_typecheck, and the gradient hook calls it too. log_fwd and log_fwd_bwd reach it only after their early return, so a run without a logger never enters the context.
collect() needs no decorator: Trainer.train_step calls it after engine.forward_backward returns, outside the type-checked region.
Commit: 7c05147


sum_statistics = self.statistic_buffers.sum_statistics.clone()
maxima = self.statistic_buffers.maxima.clone()
if dist.is_initialized():

@pianpwk pianpwk Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

if this is checking single vs. multi device, maybe the state should own the global mesh/PG and check if None. could this be a bit sus (idk what happens if dist setup, but using only 1 device)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done. The logger picks its process group once at build: WORLD when the world size is above 1, else None.
collect() skips both all-reduces when it is None. So one process with torch.distributed initialized runs no collective.
Commit: 7c05147

_local_tensor(cotangent),
slot_index,
)
return cotangent

@pianpwk pianpwk Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

i actually don't know if custom autograd fn is better or worse, I wonder if PP issues are related to this

@pianpwk pianpwk Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: can probably @no_typecheck any logging functions

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Your hunch about PP was right. Under split backward, a CPU probe fired a hook on a linear output twice, while an identity autograd.Function fired once.
I kept the hook: callsites stay one line (log_fwd_bwd returns nothing) and the autograd graph does not change. Split-backward schedules are rejected, and the TODO at that check names the Function as the fix.
On no_typecheck: TensorLogger._accumulate now has @spmd.no_typecheck, and the gradient hook calls it (see the decorator thread).
Commit: 7c05147

collapsed_stride,
value.storage_offset(),
)
return value

@pianpwk pianpwk Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nerding out a bit: dim_order -> permute -> is_contiguous might simplify this logic (also maybe is_non_overlapping_and_dense util)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done. The op now calls value.permute(value.dim_order()) and copies only if the result is still not contiguous. This replaces the old storage-order helper.
test_triton_kernel_matches_reference checks a transpose and a strided slice against the CPU reference.
Commit: 3ecc4fb


finite_absolute = torch.where(finite, value_fp32.abs(), -torch.inf)
updated_maximum = torch.maximum(maximum_row, finite_absolute.amax())
maximum_row.copy_(updated_maximum)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

q: is this more reference impl, or do we actually want to support train / log on cpu

@felipemello1 felipemello1 Aug 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reference / testing, but i am not 100% confident we should keep it. Any thoughts? Perhaps i should keep and make it clearer in the docstring?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

hmm maybe I would just separate as a ref impl? to be clear it's not expected in the runtime path

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: It is the reference. It is now registered only as the op's CPU kernel (register_kernel("cpu")), and its docstring says accelerators use the Triton kernel.
It stays next to the op so the CPU unit tests can run the whole logger. The GPU test compares Triton against it.
Commit: 3ecc4fb


if torch.compiler.is_compiling():
return _active_state is not None
return _enabled or _include_tensor_logging_calls

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is there a way to configure say, if i'm only interested in half or 10% of the tensors that logging is setup for, and I don't want to launch kernels for all the others (e.g. filter in/out by fqns)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@felipemello1 felipemello1 Aug 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I am sure that there is some way. But I didn't get that far. I think i will put it as a TODO in the code and let someone in the community pick it up.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Not in this PR. Today you pick tensors by editing the register_* and log_* calls.
I left a TODO in _should_run_calls for logging a subset (for example by FQN) without launching the other kernels.
Commit: 7c05147

tianyu-l pushed a commit that referenced this pull request Sep 10, 2026
…MoE balance loss (#3864)

## Summary

Adds `LoggedAuxLoss` (`torchtitan/models/common/aux_loss.py`): a
framework for auxiliary objectives that live inside the model. A
per-layer loss value has nowhere to go in the model output, so the
framework carries it in two other ways:

- **Injection.** The value is fed back through an identity autograd
Function on a carrier tensor: the forward returns the carrier unchanged,
the backward supplies ones for the loss term. An objective can then
shape the router's weights without being part of the returned loss,
which is what pipeline parallelism requires.
- **Metrics.** Every instance accumulates its value in the forward,
inside a retained `torch_remat` region so activation checkpointing never
re-runs the side effect. A step pre-hook rolls the instances into
per-group registers, and `collect_aux_loss_metrics` reduces them once
per log step: summed over the configured reduce mesh and the pipeline
stages, and divided by the build-time instance count, i.e. the mean over
layers.

`SeqwiseLoadBalanceLoss` (`torchtitan/models/common/moe.py`) is its
first usage. It implements the DeepSeek-V3 Sec 2.1.2 per-forward balance
loss (Eqs 17-20):

$$f_i = \frac{E}{K T} \sum_t \mathbf{1}[t \to i], \qquad s'_{t,i} =
\frac{s_{t,i}}{\sum_j s_{t,j}}, \qquad p_i = \frac{1}{T} \sum_t
s'_{t,i}, \qquad L_{bal} = \sum_i f_i p_i$$

The balancing unit is one forward's folded token stream, a DP-local
microbatch. Global balance stays with the auxiliary-loss-free bias path.

The plumbing that comes with it:

- The router builds its one-hot routing map, returns it instead of the
full scores, and passes it to the loss, so the loss counts exactly the
tokens the router counted.
- `make_moe_config(aux_loss_coeff=...)` enables the loss at 1e-3 for
every deepseek_v3 flavor.
- Both trainers set the step's denominator before the
gradient-accumulation loop and log the metric.

## Normalization

Each rank contributes a **token-additive** loss and the framework
divides by the global valid-token count, the same denominator the main
loss uses; no per-rank or per-microbatch averaging is applied. The
result is the **per-token mean** and does not depend on DP degree, PP
microbatches or gradient accumulation.

## Tests

`tests/unit_tests/cpu/test_aux_loss.py` covers six behaviors: value,
register and injected gradient against an explicit Eqs 17-20 reference;
accumulation across forwards and roll-up/zero semantics; no double count
under `torch_remat.checkpointing`; the Config ownership
`make_moe_config` relies on; an 8-rank CPU float64 + gloo spmd_types
case (dp2/cp2/tp2) with EP on and off and the typechecker on and off;
and the pipeline-stage summation of the collected metric. The
`test_moe.py` and gpu `test_remat.py` stubs follow the router's new
return value.

## Follow-ups

- The retained `torch_remat` region only takes effect under `RegionAC`;
under the PyTorch-checkpoint policies (`FullAC`, `SelectiveAC`) the
enclosing block is replayed and the logged metric over-counts (2x under
`FullAC`). The injected gradient is unaffected.
- Metric logging reduces a device scalar and calls `.item()` today; it
should go through the GPU-tensor logging framework (TODO #4202 in
`aux_loss.py`) once that lands.
@claude claude Bot mentioned this pull request Nov 2, 2026
Felipe Mello added 7 commits November 3, 2026 01:30
Copy the statistics op and its Triton kernel from the tensor logging
prototype unchanged. The next commit adapts the op API.

Checked: an old-vs-new dump of 8 fixed inputs (fp32, bf16, transpose,
permute, strided slice, nan/inf/zero, empty, 5M elements) gives equal
buffers on CPU and CUDA, and CPU matches CUDA.
TensorLogger owns the statistic buffers and one SUM and one MAX all-reduce
on log steps. Model code calls module functions (register_fwd,
register_fwd_bwd, log_fwd, log_fwd_bwd), like structured_logger.

- Trainer.Config.tensor_logger: TensorLogger.Config | None, log_freq must
  be a multiple of metrics.log_freq.
- Log calls return during torch_remat replay, so each tensor counts once.
- With accelerator graphs the calls run every step and a device flag
  gates the writes; eager non-recording steps launch nothing.
- PP metadata inference is cleared through the schedule's cleanup hook.
- Rejected at config time: SDC replay, split-backward PP schedules,
  schedule CSV, GraphTrainer, FaultTolerantTrainer.
- tests: a test-only sanity probe (features.py) and CPU tests for remat,
  cadence and derived fields, and unsupported configs.
The existing real-PG PP4 Interleaved1F1B entry now runs with the
test-only probe at log_freq=1. The probe leaves the loss unchanged and
fails the run if any statistic differs from its exact expected value:
stage ownership of rows, row order across ranks, and metadata inference
on step 1 recording nothing.
@felipemello1
felipemello1 force-pushed the codex/69-tensor-logging-v4-pr1-core branch from 60148f0 to c6267a6 Compare November 3, 2026 11:42
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 3, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 0s —— View job


I'll analyze this and get back to you.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude fable review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 10m 13s —— View job


Verdict: Approve (pending the empty "Summary (human-written)" section and a maintainer's review) — full review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging; the design follows the direction the maintainers set in the earlier review rounds, the earlier review comments are addressed at HEAD, and I found no correctness problem I can substantiate. A maintainer still needs to review: this touches the trainer, every shared model module, and eight model variants.

What this PR does. Adds an opt-in TensorLogger (Trainer.Config.tensor_logger, default off) that publishes 8 statistics per logged tensor and its gradient every log_freq steps. Model modules register row names in __init__ and log in forward; each rank accumulates into fixed per-row buffers via a Triton kernel (a device flag skips off steps inside captured graphs), and collect() runs one SUM and one MAX all-reduce on recorded steps. Unsupported combinations (split-backward PP schedules, schedule CSVs, sdc_replayer, GraphTrainer, FaultTolerantTrainer, log_freq not a multiple of metrics.log_freq) raise at config time.

Example.

config.tensor_logger = TensorLogger.Config(log_freq=10)
# publishes e.g. tensor_logger/layers.3.attention.xq.fwd.rms = 0.92
#                tensor_logger/layers.3.attention.xq.bwd.rms = 1e-05

Must fix

  1. PR description -- the "Summary (human-written)" section is empty. Per CONTRIBUTING.md / the pr-description skill, the author fills this in; the agent-written details don't replace it.

Should consider

  • tests/unit_tests/gpu/observability/test_tensor_logger.py:132 -- the observed-once test skips four models that override Decoder.forward (deepseek_v4, kimi_k2_7, qwen3_5, muse_spark); see inline comment.
Details

Gate: the problem (no per-layer signal; shards under FSDP/TP/CP/PP/EP) is real, and models/common/aux_loss.py:264 on main already carries a TODO(#4202) waiting on this logger, so the direction is maintainer-endorsed. All earlier maintainer comments are resolved at HEAD (api.py, tensor_logger package name, TensorLogger as a Configurable with Config.build, no publish filter, config-time ValueErrors, log_fwd/log_fwd_bwd naming, cadence coupled to metrics.log_freq).

Checked and found sound: collect()'s all-reduces run on rank-uniform steps only, and should_log (step == 1 or step % log_freq == 0) is true on every recorded step given the multiple-of constraint; the private engine._forward_backward_accelerator_graph_enabled access follows the existing validator-build pattern; register_post_metadata_inference_cleanup is an established in-repo mechanism; models not edited (gpt_oss, qwen3, llama3) use the shared forwards unchanged; the probe's exact-equality asserts are safe because its sums are exact in fp32 regardless of atomic order; flux inherits the working train_step and fails loudly if no rows are registered; the RL trainer is a separate class with no such field.

Not verified (needs GPUs / multi-node): the bitwise loss and grad_norm equality claims, the step-time and memory numbers, Triton kernel behavior on ROCm, and TP-without-SP gradient-statistics correctness beyond the author's 1-GPU oracle runs.



# kimi_k3 and muse_glimmer override Decoder.forward and some module forwards.
@pytest.mark.parametrize("name", ["llama3", "deepseek_v3", "kimi_k3", "muse_glimmer"])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This test guards exactly the invariant that a model overriding Decoder.forward (or a shared module's forward) keeps the logging calls -- but four of the models that override Decoder.forward and received callsite edits in this PR are not in the list: deepseek_v4, kimi_k2_7, qwen3_5, and muse_spark. A later refactor of one of their forwards can silently drop a call, and its registered rows would publish nothing with no test failing. Either add them to the parametrize list (the check is cheap per model: one debug-model forward/backward) or say in the comment why these four representatives cover the others.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Not adding them in this PR. This was raised in two earlier review rounds, and the reason still holds. These four debug models need extra setup to build and run outside the trainer:

  • deepseek_v4's build_model_config takes no attn_backend.
  • muse_spark and kimi_k2_7 need flex-only QK clipping and mixed dtypes.

That setup would make a small unit test model-specific.

Their logging calls are covered end to end instead. The stress matrix runs each of them through the trainer with the test-only probe (TensorLoggerSanityProbe, log_freq=1): deepseek_v4, kimi_k2_7, qwen3_5, qwen3_6 and muse_spark, plus kimi_k3. The probe's collect() asserts that every registered row has observation_count == owners x calls_per_step, so a dropped call fails the run. All of these pass at this head.

The trade-off: that matrix is not in CI. If maintainers want CI coverage for these four, adding them to the parametrize list with per-model setup is a follow-up.

@felipemello1
felipemello1 marked this pull request as draft November 3, 2026 16:03
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 3, 2026
tianyu-l pushed a commit that referenced this pull request Nov 5, 2026
## Summary

Z loss has become a fairly popular regularization loss used together
with Cross Entropy. I already did a PR about this but it stalled for
there were major mods coming to the way loss was handled. I do not know
if the situation stabilized from
#2576 but here I am
re-proposing the same feature.

## Why
Adds an optional z-loss regularizer used by PaLM/OLMo/Trinity) to
`CrossEntropyLoss`. To make it observable, the trainer and validator now
log the metrics a loss returns (both dropped them before).

```python
CrossEntropyLoss.Config(global_vocab_size=V, z_loss_weight=1e-4)  # None = off (default)
# loss = (sum_t CE_t + w * sum_t lse_t^2) / N
# logs:  ce_loss/mean, z_loss/mean                         (train)
#        validation_metrics/ce_loss/mean, .../z_loss/mean  (validation)
```

## What changed
**z-loss**
- `CrossEntropyLoss.Config.z_loss_weight: float | None`. When set, the
loss adds `w * sum lse^2` before token normalization and returns
`ce_loss/mean` and `z_loss/mean` (unweighted). When `None`, the path is
unchanged.
- `cross_entropy_and_logsumexp` (new, `@local_compile("loss")`): returns
`(CE, lse[T])` from one logsumexp. Under TP it uses
`_LossParallelCrossEntropy(..., return_lse=True)`.
- `_LossParallelCrossEntropy(return_lse=False)`: optional second output.
lse = `local_max + log(sum_exp)` from the existing all-reduces (no extra
collective); backward adds `softmax * grad_lse` (still collective-free).
`return_lse=False` is unchanged.

**Loss-metric logging**
- `combine_loss_metrics(metrics_list, *, mesh=None)` +
`loss_metric_reduce_op(key)` in `loss.py`: one rule set by key suffix
(`/mean`, `/frac`, `_mean`, `_frac` → sum; `/max` → max; `/min` → min),
applied locally and, with `mesh`, across ranks.
- `ChunkedLossWrapper` now uses it instead of `_combine_chunk_metrics`
(mechanical move).
- `Trainer.train_step`: combines loss metrics over microbatches and the
loss mesh and logs them. `TODO(#4202)`.
- `Validator`: collects loss metrics on the non-PP path and on the PP
path (one `loss_metrics` dict per microbatch via
`pp_schedule.eval(loss_kwarg_mbs=...)`, filled by `_scalar_loss_fn`);
combines across steps and ranks; divides sum-type keys by the global
valid-token count; logs them as `validation_metrics/<key>`.
- LossFunction now types a Loss ((loss, metrics)); the raw mse_loss
kernel annotation is fixed accordingly (typing only)

## User-facing changes
| Before | After |
| --- | --- |
| no z-loss | `CrossEntropyLoss.Config(z_loss_weight=...)` |
| loss metrics dropped by trainer and validator | logged
(`ce_loss/mean`, `z_loss/mean`, `validation_metrics/...`) |
| — | with z-loss on, `loss_metrics/global_avg_loss` and
`validation_metrics/loss` include `w * z`; compare `ce_loss/mean`
against runs without z-loss |


## Numerics
**z-loss off:** bitwise-equal loss and grad_norm vs. base `b832ae41` (20
steps, seed 42, deterministic, `scripts/loss_compare.py --assert-equal
--metrics loss,grad_norm`):

| Config | GPUs | Loss | grad_norm |
| --- | --- | --- | --- |
| llama3 debug, FSDP 4 | 4x A100-SXM-64GB | bitwise equal | bitwise
equal |
| llama3 debug, FSDP 2 + TP 2 | 4x A100-SXM-64GB | bitwise equal |
bitwise equal |
| llama3 debug, PP 2 + FSDP 2 (1F1B, 8 microbatches) | 4x A100-SXM-64GB
| bitwise equal | bitwise equal |

**z-loss on vs. off** (`w = 1e-4`): llama3 (4 layers, dim 8192, seq
2048), FSDP 2 × TP 2, 4x A100-SXM-64GB, 400 steps, seed 42,
deterministic, local `c4_test` data. TP exercises the new `probs *
grad_lse` backward.
- `global_avg_loss == ce_loss/mean + w * z_loss/mean` at every step (max
abs diff 2e-6).
- `ce_loss/mean` tracks the baseline loss: mean over steps 301–400 is
2.8065 vs. 2.8091; validation CE at step 400 is 2.7249 vs. 2.7268.
- `z_loss/mean` falls from ~1500 (warmup spike) to 234 (lse ≈ 36 → 15).

<img width="2250" height="660" alt="zloss_fsdp2_tp2"
src="https://github.com/user-attachments/assets/e0f91785-5892-4736-bb80-dd1660b541ef"
/>

The implementation matches OLMo-core's `cross_entropy_loss(...,
compute_z_loss=True)`: identical loss, z term equal to the last fp32
digit, gradients within 6e-17.

## Testing
- New: `test_cross_entropy_and_logsumexp_matches_cross_entropy_loss` (no
TP; CE and lse vs. fp64).
- New: `test_cross_entropy_and_logsumexp_parity` (4 TP ranks, uneven
vocab, `IGNORE_INDEX`, strict spmd typechecking). TP CE is bitwise equal
to `cross_entropy_loss`; lse and the gradient of `CE + sum(lse^2)` match
fp64. Catches regressions in the custom lse backward.
- New: `test_validation_logs_loss_metrics`: `/mean` metrics are
normalized by the valid-token total and `/max` is not.
- Updated for the new `_validate_body` return value and validator mocks:
`test_validator.py`, `test_accelerator_graph_validation_config.py`, GPU
`test_accelerator_graph_train_eval.py` (11/11 pass on 4x A100, including
the PP schedules).
- Also run: `test_loss.py`, `test_trainer.py`, `test_invalid_loss.py`,
`test_pipeline_parallel.py`, `test_compile_config.py`,
`graph_trainer/tests/test_chunked_loss.py`.

---------

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
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).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

4 participants