Skip to content

[Observability 3/7] Experiment metrics with background aggregation subprocess - #2603

Closed
felipemello1 wants to merge 1 commit into
gh/felipemello1/19/basefrom
gh/felipemello1/19/head
Closed

felipemello1 wants to merge 1 commit into
gh/felipemello1/19/basefrom
gh/felipemello1/19/head

Conversation

@felipemello1

@felipemello1 felipemello1 commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

How to review

Prioritize the files under /observability. Check how they are used in the toy example.
No need to nitpick the toy example. Real implementation in trainer are in PRs 7 and 8.

Summary

The experiment metrics layer. Each rank calls record_metric(key, MetricValue) which serializes to per-rank experiment JSONL. Five metric types: MeanMetric, MaxMetric, MinMetric, SumMetric, NoOpMetric.

The logging subprocess (logging_worker in aggregation.py) runs as a multiprocessing.Process. The training process signals it via queue.put((step, is_validation)) after each log step.

Example

record_metric("trainer_throughput/tps_mean", MeanMetric(sum=tps))
// dump_dir/experiment_logs/trainer_rank_0_experiment.jsonl
{"key": "trainer_throughput/tps_mean", "reduce": "MeanMetric",
 "sum": 1234.5, "weight": 1.0,
 "step": 42, "rank": 0, "source": "trainer",
 "caller": "torchtitan/trainer.py:542:train_step", "timestamp": 1708200121.724}

// dump_dir/experiment_logs/trainer_rank_1_experiment.jsonl
{"key": "trainer_throughput/tps_mean", "reduce": "MeanMetric",
 "sum": 1180.2, "weight": 1.0,
 "step": 42, "rank": 1, "source": "trainer",
 "caller": "torchtitan/trainer.py:542:train_step", "timestamp": 1708200121.725}

// After aggregation: (1234.5 + 1180.2) / (1.0 + 1.0) = 1207.35

Aggregation (Logging Subprocess)

The training process never reads JSONL or writes to backends directly.
A background subprocess on rank 0 handles all aggregation and output:

                  Training Process (all ranks)
                  ┌─────────────────────────────────┐
                  │  record_metric("loss", ...)     │──→ experiment.jsonl (per rank)
                  │                                 │
                  │                                 │
                  │  # on log steps:                │
                  │  barrier()                      │
                  │  log_queue.put(step) ───────────│──┐  (~0.1ms, non-blocking)
                  └─────────────────────────────────┘  │
                                                       │
                  Logging Subprocess (rank 0 only)     │
                  ┌─────────────────────────────────┐  │
                  │  step = queue.get() ◄───────────│──┘
                  │  read all experiment.jsonl files│
                  │  aggregate by key (reduce)      │
                  │  write to WandB / TensorBoard   │
                  │  print to console               │
                  └─────────────────────────────────┘

The subprocess is spawned via logging_worker from aggregation.py. Here's
the RL pattern where the controller owns the subprocess directly:

import multiprocessing
from torchtitan.observability import logging_worker

# Spawn the logging subprocess
log_queue = multiprocessing.Queue()
log_process = multiprocessing.Process(
    target=logging_worker,
    args=(log_queue, OUTPUT_DIR),
    kwargs={
        "enable_wandb": True,
        "enable_tensorboard": False,
        "console_log_metric_keys": [
            "training/loss_mean",
            "training/grad_norm_max",
            "rl/reward_mean",
            "trainer_throughput/tps_mean",
        ],
    },
    daemon=True,
)
log_process.start()

# Each actor calls record_metric locally — writes go to JSONL
# ...

# After each step, signal the subprocess to read + aggregate + flush
log_queue.put((step, False))  # (step, is_validation)

# Shutdown
log_queue.put(None)
log_process.join()

console_log_metric_keys controls which metrics appear in the console output.
The subprocess prints one line per step with only the keys listed.

Perf

Timing (local filesystem, 100 metrics/rank):

Aggregation benchmarks are measured on local filesystem without multithreading. NFS will be slower for the read, but shouldn't be an issue since it is non-blocking + multithreading.

Scale Read Aggregate Total
10 files (1K entries) 9ms 0.5ms 10ms
100 files (10K entries) 88ms 6ms 94ms
500 files (50K entries) 333ms 35ms 368ms

None of this blocks training. Training pays only the signal cost (~0.1ms).

Test plan

Run toy_spmd: python -m torch.distributed.run --nproc_per_node=4 -m torchtitan.experiments.observability.toy_spmd
Run toy_rl: python -m torchtitan.experiments.observability.toy_rl

  • 23 new unit tests for aggregation + metrics (67 cumulative)
  • Integration: toy_spmd produces experiment JSONL with aggregated loss/grad_norm/lr
  • Integration: toy_rl produces experiment JSONL from 4 actor types (controller, rollouter, reward, trainer)
  • Integration: logging subprocess writes to WandB and prints console output

Sample

{"reduce": "MeanMetric", "sum": 5.5534299463033676e-05, "weight": 1.0, "key": "trainer_time/data_loading_s", "step": 1, "rank": 0, "source": "trainer", "caller": "torchtitan/experiments/observability/toy_spmd.py:240:batch_generator", "timestamp": 1773611398.1511042}
{"reduce": "MeanMetric", "sum": 3.14233530825004, "weight": 1.0, "key": "trainer_time/forward_backward_s", "step": 1, "rank": 0, "source": "trainer", "caller": "torchtitan/experiments/observability/toy_spmd.py:262:train_step", "timestamp": 1773611401.293699}
{"reduce": "MeanMetric", "sum": 0.15071861585602164, "weight": 1.0, "key": "trainer_time/optimizer_s", "step": 1, "rank": 0, "source": "trainer", "caller": "torchtitan/experiments/observability/toy_spmd.py:274:train_step", "timestamp": 1773611401.444696}

Console output (toy_spmd 4 GPUs, 20 steps)

[titan] 2026-03-15 14:50:01,477 - torchtitan.observability.aggregation - INFO - �[31mstep:  1  �[31mtraining/loss_mean: 3.66  �[32mtraining/grad_norm_max: 0.49  �[33mtraining/lr: 0.0010  �[39m
[titan] 2026-03-15 14:50:01,602 - torchtitan.observability.aggregation - INFO - �[31mstep:  5  �[31mtraining/loss_mean: 3.053  �[32mtraining/grad_norm_max: 0.41  �[33mtraining/lr: 0.0010  �[39m
[titan] 2026-03-15 14:50:02,196 - torchtitan.observability.aggregation - INFO - �[31mstep: 10  �[31mtraining/loss_mean: 2.54  �[32mtraining/grad_norm_max: 0.32  �[33mtraining/lr: 0.0010  �[39m
[titan] 2026-03-15 14:50:02,360 - torchtitan.observability.aggregation - INFO - �[31mstep: 15  �[31mtraining/loss_mean: 2.23  �[32mtraining/grad_norm_max: 0.26  �[33mtraining/lr: 0.0010  �[39m
[titan] 2026-03-15 14:50:02,523 - torchtitan.observability.aggregation - INFO - �[31mstep: 20  �[31mtraining/loss_mean: 2.026  �[32mtraining/grad_norm_max: 0.22  �[33mtraining/lr: 0.0010  �[39m
[titan] 2026-03-15 14:50:02,523 - torchtitan.observability.aggregation - INFO - [logging process] shutting down

Console output - toy_rl

[titan] 2026-03-15 14:52:58,085 - torchtitan.observability.aggregation - INFO - �[31mstep:  1  �[31mtraining/loss_mean: 3.65  �[32mtraining/grad_norm_max: 0.50  �[33mtraining/lr: 0.0010  �[34mrl/reward_mean: 1.0  �[35mrl/completion_len_mean: 16.69  �[39m
[titan] 2026-03-15 14:52:58,221 - torchtitan.observability.aggregation - INFO - �[31mstep:  3  �[31mtraining/loss_mean: 3.33  �[32mtraining/grad_norm_max: 0.45  �[33mtraining/lr: 0.0010  �[34mrl/reward_mean: 1.0  �[35mrl/completion_len_mean: 16.69  �[39m
[titan] 2026-03-15 14:52:58,354 - torchtitan.observability.aggregation - INFO - �[31mstep:  5  �[31mtraining/loss_mean: 3.052  �[32mtraining/grad_norm_max: 0.39  �[33mtraining/lr: 0.0010  �[34mrl/reward_mean: 1.0  �[35mrl/completion_len_mean: 16.69  �[39m
[titan] 2026-03-15 14:52:58,417 - torchtitan.observability.aggregation - INFO - [logging process] shutting down

Output folder (adds experiment_logs/)

outputs/toy_spmd/
├── analysis/
│   └── system_metrics_gantt.json
├── experiment_logs/                    ← NEW in PR3
│   ├── trainer_rank_0_experiment.jsonl
│   ├── trainer_rank_1_experiment.jsonl
│   ├── trainer_rank_2_experiment.jsonl
│   └── trainer_rank_3_experiment.jsonl
├── system_logs/
│   └── trainer_rank_{0-3}_system.jsonl
└── wandb/

WandB

toy_spmd: https://wandb.ai/cabernet-team/torchtitan/runs/pi8sosf6
toy_rl: https://wandb.ai/cabernet-team/torchtitan/runs/zcl58f75

Comment on lines -283 to -287
if self.rank == 0:
print(
f"step: {self.step} loss: {loss_scalar.item():.5f} "
f"grad_norm: {grad_norm.item():.5f}"
)

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.

no need for printing, since now we can collect metrics an log to console.


System metrics: init_observability, set_step, record_span, record_event, EventType
"""
"""TorchTitan Observability Library."""

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.

meh, this is a bad docstring. I can delete it later.


logger = logging.getLogger(__name__)

_QUEUE_TIMEOUT_S = 600 # 10 minutes — if no signal, assume training crashed

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.

unsure about this. Basically if we dont try to flush anything in 10min, we kill this actor. This is bad if some collective takes >10min, e.g. checkpointing. I put this because if for some reason the parent process dies, then there is no way to kill this child process.

with record_span("trainer_time/forward_backward_s", EventType.FWD_BWD):
with loss_parallel():
logits = self.model(tokens)
loss_sum, valid_tokens = self.compute_loss(logits, labels, loss_mask)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we model this as a MeanMetric? Not necessarily for logging, but in general it seems a useful abstraction.

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.

Do you mean a stateful class to help with keeping track of loss and valid tokens, but without .detach and .item(), so we can still run .backward() on it? If so, we could, but i think that it should probably be in a separate PR

return f"{value:.{max(n_decimals, 2)}f}"


def _log_to_console(

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's the relationship between this and logger.info call in torchtitan?

@felipemello1 felipemello1 Mar 18, 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.

Titan currently logs key metrics to console on every .log call:

Maybe it should rename to make it more explicit, e.g. "display_key_metrics_on_console"

Functionality is the same, I just turned it into a function, and let the user pass arbitrary keys that they want to monitor on the console. I needed it because 'eval' and 'train' have different keys.

(from pr4)
image

init_logger()
init_observability(source="controller", output_dir=OUTPUT_DIR, rank=0)

# logging_worker reads experiment JSONL from all actors, aggregates

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'm confused by why you have both MetricsProcessor and this multiprocessing of logging_worker. It seems that

  • metrics processor is more object-oriented, and it can start a subprocess with logging_worker
  • but the API is more rigid in that you have to pass it around -- I thought the point is to be able to log anywhere, so is the end goal removing MetricsProcessor?

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'm confused by why you have both MetricsProcessor and this multiprocessing of logging_worker

I think that this becomes clearer in the follow up PRs, but MetricsProcessor (MP) has multiple methods that help the trainer: 'set_step', 'log', 'record_throughput', 'record_memory', 'reset_counters'. We abstract all of that away to MP, so the trainer is cleaner.

Then, when we call .log(), we trigger the logging_worker.

but the API is more rigid in that you have to pass it around

The MP is just a helper for the trainer. The rest of logging system is independent. You can call 'record_metric' or 'record_span' from anywhere. No need to "pass the MP around".

Let me know if this makes sense or not.

with record_span("trainer_time/validation_s", EventType.EVAL):
self.validate(tokens, labels, loss_mask)

self.metrics_processor.log(step)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is this the same as "set_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.

no,

'set_step' will add the step to every log

`.log' will aggregate and flush all metrics from a given step

trainer = ToyTrainer(device, parallel_dims, OUTPUT_DIR)
mp_config = MetricsProcessor.Config(
enable_wandb=ENABLE_WANDB,
console_log_metric_keys=[

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.

IIUC these are the keys you want to be logged also to the console?

record_metric("training/loss_mean", NoOpMetric(value=loss_scalar.item()))
record_metric("training/grad_norm_max", MaxMetric(value=grad_norm.item()))
record_metric("training/lr", NoOpMetric(value=LR))
record_event(

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 see you're still logging the loss and grad_norm to system metrics along with the record metric. I don't understand why you would need both and the difference between event and metric is blurred. Perhaps this is just a misunderstanding?

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.

will make it more explicit, good feedback!

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

None yet

Development

Successfully merging this pull request may close these issues.

3 participants