Repository navigation
[Observability 3/7] Experiment metrics with background aggregation subprocess - #2603
felipemello1 wants to merge 1 commit into
Conversation
…bprocess [ghstack-poisoned]
| if self.rank == 0: | ||
| print( | ||
| f"step: {self.step} loss: {loss_scalar.item():.5f} " | ||
| f"grad_norm: {grad_norm.item():.5f}" | ||
| ) |
There was a problem hiding this comment.
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.""" |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Can we model this as a MeanMetric? Not necessarily for logging, but in general it seems a useful abstraction.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
what's the relationship between this and logger.info call in torchtitan?
There was a problem hiding this comment.
Titan currently logs key metrics to console on every .log call:
torchtitan/torchtitan/components/metrics.py
Line 526 in 0187d5f
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.
| init_logger() | ||
| init_observability(source="controller", output_dir=OUTPUT_DIR, rank=0) | ||
|
|
||
| # logging_worker reads experiment JSONL from all actors, aggregates |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
is this the same as "set_step"?
There was a problem hiding this comment.
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=[ |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
will make it more explicit, good feedback!

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_workerinaggregation.py) runs as amultiprocessing.Process. The training process signals it viaqueue.put((step, is_validation))after each log step.Example
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:
The subprocess is spawned via
logging_workerfromaggregation.py. Here'sthe RL pattern where the controller owns the subprocess directly:
console_log_metric_keyscontrols 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.
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_spmdRun toy_rl:
python -m torchtitan.experiments.observability.toy_rlSample
{"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)
Console output - toy_rl
Output folder (adds experiment_logs/)
WandB
toy_spmd: https://wandb.ai/cabernet-team/torchtitan/runs/pi8sosf6
toy_rl: https://wandb.ai/cabernet-team/torchtitan/runs/zcl58f75