Repository navigation
[config] Make metric exporters and LR scheduler construction configurable - #5775
Conversation
|
@claude review |
|
Claude finished @tianyu-l's task in 4m 59s —— View job Approve -- please address the RL README wording before merging. See review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The PR swaps the enable_* exporter booleans for Configurable exporters selected by config type, which is what rules/config.md asks for. Rank selection and LR numerics are unchanged, and I found no stale callsites.
What this PR does. TensorBoard, W&B and MLflow loggers become Configurable components. The supervised and RL MetricsProcessors now build them from a single loggers: list[BaseLogger.Config], which removes LoggerContainer and _build_metric_logger. Rank selection stays the same: non-metrics ranks build exporters only when save_for_all_ranks, and never for metrics_rank_only (MLflow). The RL wandb_project env-var mutation becomes WandBLogger.Config.project. LRSchedulersContainer drops its hand-written Config.build() and does the schedule setup in __init__(config, *, optimizers, training_steps). The schedule math is unchanged.
Example.
# before
MetricsProcessor.Config(enable_tensorboard=True, enable_wandb=True) # order fixed: wandb, tb, mlflow
RLMetricsProcessor.Config(enable_wandb=True) # os.environ.setdefault("WANDB_PROJECT", "titan_rl")
CustomLRSchedulers.Config().build(...) # returns base LRSchedulersContainer
# after
MetricsProcessor.Config(loggers=[WandBLogger.Config(), TensorBoardLogger.Config()])
RLMetricsProcessor.Config(loggers=[WandBLogger.Config(project="titan_rl")]) # env untouched
CustomLRSchedulers.Config().build(...) # returns CustomLRSchedulersMust fix
torchtitan/rl/README.md:251,:272-- the docs tell users to assignloggers = [TensorBoardLogger.Config()], which silently drops the default W&B exporter. They should say to append it instead.
Should consider
tests/rl/unit_tests/cpu/test_metrics.py:658,:735-- these two tests no longer guard anything distinct now that the env mutation is gone. Delete them.tests/unit_tests/cpu/observability/test_validation_metrics_window.py:69-- the full-processor rewrite adds monkeypatches, andresets == 2now counts the constructor's reset. The smaller change isprocessor.loggers = [...].tests/unit_tests/cpu/components/optim/test_lr_scheduler.py:62-- the subclass test duplicates the generic owner wiring thattest_configurable.pyalready covers.torchtitan/components/optim/lr_scheduler.py:71-- the class docstringArgs:still lists onlyoptimizers. It should also listconfigandtraining_steps.
Questions
- Do RL runs still need a separate
titan_rlW&B project? The newWandBLogger.Config.projectfield exists only for that, and each of the ~22 RL recipe call sites repeatsproject="titan_rl". If the defaulttorchtitanproject (orWANDB_PROJECT) is fine, the field and the repetitions can go.
Details
- Rank selection check (
metrics.py:462-471). Withsave_for_all_ranks=False, only the metrics rank builds exporters, as before. WithTrue, every rank builds the non-MLflow exporters intorank_{r}, and MLflow is built only on the metrics rank, as before._get_metrics_rankand the ft/replica path layout are unchanged. - Behavior changes, all intentional and stated in the description. Exporter order follows the list order. W&B construction errors now propagate instead of being logged and swallowed, which matches the explicit-over-implicit rule. The MLflow dependency check moves to
Config.__post_init__, so it still runs on every rank. - LR scheduler. The code is moved verbatim (re-indented). In
test_accelerator_graph_lr_metrics_stay_on_host,warmup_steps=0, training_steps=2gives a factor of 0.5 at step 1, which matches the old1/(step+1)lambda and the5e-4assertion. - Callsites. A search of the whole repo, including hidden files, found no remaining
enable_tensorboard/enable_wandb/enable_mlflow/wandb_project/LoggerContaineruses and no directLRSchedulersContainer(...)constructors. The only exceptions aredocs/benchmarks/...trainy-whitefiber.md, which is a historical benchmark record, and the old-checkout branch inscripts/_checkpoint_test_config.py. That branch is justified becauseloss_compare.pyinjects this module into older revisions, and its dedupe avoids two TensorBoard writers in one directory. config.to_dict()serializesloggersas a list of field dicts without the type. This matches the existing behavior for other polymorphic lists such asoptimizers.
Not verified: GPU numerics (I relied on the author's bitwise loss/grad_norm comparison). A maintainer still needs to review, since this touches core observability and optimizer code.
| `config.metrics.loggers = []` in your recipe. Set | ||
| `config.metrics.loggers = [TensorBoardLogger.Config()]` to write TensorBoard metrics. |
There was a problem hiding this comment.
The old enable_tensorboard = True added TensorBoard next to the recipe's W&B exporter. loggers = [TensorBoardLogger.Config()] replaces the list, so a user who follows this line turns W&B off without meaning to. The same wording is at line 272. Suggest describing it as an append:
| `config.metrics.loggers = []` in your recipe. Set | |
| `config.metrics.loggers = [TensorBoardLogger.Config()]` to write TensorBoard metrics. | |
| `config.metrics.loggers = []` in your recipe. Append | |
| `TensorBoardLogger.Config()` to `config.metrics.loggers` to also write TensorBoard metrics. |
| disable it in the recipe with `config.metrics.loggers = []`. Set | ||
| `config.metrics.loggers = [TensorBoardLogger.Config()]` to write TensorBoard metrics under | ||
| the output directory. |
There was a problem hiding this comment.
Same problem as line 251: assigning the list drops the default W&B exporter.
| disable it in the recipe with `config.metrics.loggers = []`. Set | |
| `config.metrics.loggers = [TensorBoardLogger.Config()]` to write TensorBoard metrics under | |
| the output directory. | |
| disable it in the recipe with `config.metrics.loggers = []`. Append | |
| `TensorBoardLogger.Config()` to `config.metrics.loggers` to also write TensorBoard metrics under | |
| the output directory. |
| def test_wandb_project_default_titan_rl(self, tmp_path, monkeypatch) -> None: | ||
| """When `WANDB_PROJECT` is unset and `wandb_project` is at the | ||
| default, the build should write `titan_rl` to the env var.""" | ||
| """The RL recipe default selects the titan_rl project without an env var.""" |
There was a problem hiding this comment.
Removing os.environ.setdefault("WANDB_PROJECT", ...) makes two of these tests redundant:
test_wandb_project_default_titan_rlno longer tests a default. It passesproject="titan_rl"explicitly, which is the same thing astest_wandb_project_config_overrides_defaultwith a different string.test_tensorboard_only_does_not_set_wandb_project_env(line 658) guarded the env mutation, and that code path no longer exists.
Suggest deleting both. test_wandb_project_env_var_wins and test_wandb_project_config_overrides_default already cover the precedence contract.
| assert logged["validation_metrics/throughput(tps)"] == 200 | ||
| assert processor.data_loading_times == [] | ||
| assert processor.device_memory_monitor.resets == 1 | ||
| assert processor.device_memory_monitor.resets == 2 |
There was a problem hiding this comment.
This test checks that validation is measured over its own window. Building the full processor pulls in get_rank and get_peak_flops monkeypatches and a device_name stub. It also changes this assertion from 1 to 2, because the count now includes the constructor's reset_peak_stats(), which hides the reset the test exists to check. Config-built exporters and the runtime constructor contract are already covered by test_only_metrics_rank_uses_mlflow (TensorBoard + MLflow through MetricsProcessor.Config(...).build) and the RL fanout test.
The smaller change keeps the old object.__new__ setup and sets processor.loggers = [SimpleNamespace(log=lambda m, step: logged.update(m))]. The assertion can then stay resets == 1.
| config.optim.lr_scheduler.min_lr_factor = min_lr_factor | ||
| return config | ||
|
|
||
| def test_subclass_config_builds_custom_scheduler(self): |
There was a problem hiding this comment.
Optional: the fix deletes the hand-written build() override, after which LRSchedulersContainer.Config uses the generic __init_subclass__ owner wiring. tests/unit_tests/cpu/config/test_configurable.py already covers that wiring (test_valid_config, test_old_style_forwarding). This test would only catch someone re-adding a custom build() to this one config, and rules/config.md already forbids that. The repo also has no LRSchedulersContainer subclass. Consider dropping it (17 lines).
Conflict in torchtitan/observability/metrics.py: main (#5775) deleted LoggerContainer and replaced MetricsProcessor.logger with a list of loggers. Drop LoggerContainer.commit with it; MetricsProcessor.commit now loops over self.loggers. The new W&B test builds the logger through WandBLogger.Config.
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
## Why
`Profiler.Config` is one flat config for three tools: Kineto traces, Cuspy
traces (a nested config that only applies with `enable_profiling`) and memory
snapshots. Adding a tool means editing the config, `__enter__`, `step`,
`__exit__` and the annotation helper. The next PR in this stack adds
always-on kernel spans, which would be a fourth tool. Following #5775, each
tool now owns its config, and optional tools are `X.Config | None` fields.
## Design
```
Profiler entry point: builds, steps and closes
| the enabled tools
+-- trace: TraceProfiler | None torch.profiler.profile schedule +
| | trace dump
| +-- KinetoTraceProfiler CPU + CUDA/XPU/Neuron activities
| +-- CuspyTraceProfiler CPU + Cuspy CUDA, pftrace, py stacks
|
+-- memory_snapshot: MemorySnapshotProfiler | None
allocator history; OOM dump on exit
```
```python
# before
Profiler.Config(enable_profiling=True, profile_freq=100,
cuspy=CuspyProfilerConfig(record_py_stacks=True),
enable_memory_snapshot=True, memory_snapshot_freq=50)
# after
Profiler.Config(trace=CuspyTraceProfiler.Config(freq=100, record_py_stacks=True),
memory_snapshot=MemorySnapshotProfiler.Config(freq=50))
```
## User-facing changes
| Before | After |
| --- | --- |
| `enable_profiling=True` | `trace=KinetoTraceProfiler.Config()` |
| `enable_profiling=True, cuspy=CuspyProfilerConfig(...)` | `trace=CuspyTraceProfiler.Config(...)` |
| `save_traces_folder`, `profile_freq`, `profiler_{warmup,active,repeat,skip_first,skip_first_wait}` | `save_folder`, `freq`, `warmup`, `active`, `repeat`, `skip_first`, `skip_first_wait` |
| `enable_memory_snapshot=True` | `memory_snapshot=MemorySnapshotProfiler.Config()` |
| `save_memory_snapshot_folder`, `memory_snapshot_freq`, `memory_snapshot_max_entries` | `save_folder`, `freq`, `max_entries` |
| memory snapshot freq falls back to `profile_freq` | defaults to 10 |
| `Profiler.active()` | removed (no callers) |
Output paths, structured-log span names and
`maybe_cuda_graph_annotation_config()` are unchanged.
Mechanical, safe to skim: recipe, test and doc migrations (`torchtitan_recipes/`,
`tests/`, graph_trainer docs, numerics_debugging skill).
## Numerics
Loss and grad_norm are bitwise identical to main for 20 steps of the llama3
debug model. Setup: flex attention, seed 42, deterministic, 2 GPUs, Kineto
trace and memory snapshot enabled.
## Testing
- Profiler, trainer and graph_trainer profiler unit tests.
- New `test_memory_snapshot_dumps_every_freq_steps_and_on_oom`: the OOM dump
moved into `MemorySnapshotProfiler.close(exc)` and had no test.
- 2-GPU debug model runs: the Kineto trace with memory snapshots, and the
Cuspy trace with py stacks, write the same files at the same steps as main.
ghstack-source-id: a8f54dd
Pull Request resolved: #5871
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
## Why
`Profiler.Config` is one flat config for three tools: Kineto traces, Cuspy
traces (a nested config that only applies with `enable_profiling`) and memory
snapshots. Adding a tool means editing the config, `__enter__`, `step`,
`__exit__` and the annotation helper. The next PR in this stack adds
always-on kernel spans, which would be a fourth tool. Following #5775, each
tool now owns its config, and optional tools are `X.Config | None` fields.
## Design
```
Profiler entry point: builds, steps and closes
| the enabled tools
+-- trace: TraceProfiler | None torch.profiler.profile schedule +
| | trace dump
| +-- KinetoTraceProfiler CPU + CUDA/XPU/Neuron activities
| +-- CuspyTraceProfiler CPU + Cuspy CUDA, pftrace, py stacks
|
+-- memory_snapshot: MemorySnapshotProfiler | None
allocator history; OOM dump on exit
```
```python
# before
Profiler.Config(enable_profiling=True, profile_freq=100,
cuspy=CuspyProfilerConfig(record_py_stacks=True),
enable_memory_snapshot=True, memory_snapshot_freq=50)
# after
Profiler.Config(trace=CuspyTraceProfiler.Config(freq=100, record_py_stacks=True),
memory_snapshot=MemorySnapshotProfiler.Config(freq=50))
```
## User-facing changes
| Before | After |
| --- | --- |
| `enable_profiling=True` | `trace=KinetoTraceProfiler.Config()` |
| `enable_profiling=True, cuspy=CuspyProfilerConfig(...)` | `trace=CuspyTraceProfiler.Config(...)` |
| `save_traces_folder`, `profile_freq`, `profiler_{warmup,active,repeat,skip_first,skip_first_wait}` | `save_folder`, `freq`, `warmup`, `active`, `repeat`, `skip_first`, `skip_first_wait` |
| `enable_memory_snapshot=True` | `memory_snapshot=MemorySnapshotProfiler.Config()` |
| `save_memory_snapshot_folder`, `memory_snapshot_freq`, `memory_snapshot_max_entries` | `save_folder`, `freq`, `max_entries` |
| memory snapshot freq falls back to `profile_freq` | defaults to 10 |
| `Profiler.active()` | removed (no callers) |
Output paths, structured-log span names and
`maybe_cuda_graph_annotation_config()` are unchanged.
Mechanical, safe to skim: recipe, test and doc migrations (`torchtitan_recipes/`,
`tests/`, graph_trainer docs, numerics_debugging skill).
## Numerics
Loss and grad_norm are bitwise identical to main for 20 steps of the llama3
debug model. Setup: flex attention, seed 42, deterministic, 2 GPUs, Kineto
trace and memory snapshot enabled.
## Testing
- Profiler, trainer and graph_trainer profiler unit tests.
- New `test_memory_snapshot_dumps_every_freq_steps_and_on_oom`: the OOM dump
moved into `MemorySnapshotProfiler.close(exc)` and had no test.
- 2-GPU debug model runs: the Kineto trace with memory snapshots, and the
Cuspy trace with py stacks, write the same files at the same steps as main.
ghstack-source-id: 02ee207
Pull Request resolved: #5871
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0) (oldest at bottom): * #5792 * __->__ #5871 ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why `Profiler.Config` is one flat config for three tools: Kineto traces, Cuspy traces (a nested config that only applies with `enable_profiling`) and memory snapshots. Adding a tool means editing the config, `__enter__`, `step`, `__exit__` and the annotation helper. The next PR in this stack adds always-on kernel spans, which would be a fourth tool. Following #5775, each tool now owns its config, and optional tools are `X.Config | None` fields. ## Design ``` Profiler entry point: builds, steps and closes | the enabled tools +-- trace: TraceProfiler | None torch.profiler.profile schedule + | | trace dump | +-- KinetoTraceProfiler CPU + CUDA/XPU/Neuron activities | +-- CuspyTraceProfiler CPU + Cuspy CUDA, pftrace, py stacks | +-- memory_snapshot: MemorySnapshotProfiler | None allocator history; OOM dump on exit ``` ```python # before Profiler.Config(enable_profiling=True, profile_freq=100, cuspy=CuspyProfilerConfig(record_py_stacks=True), enable_memory_snapshot=True, memory_snapshot_freq=50) # after Profiler.Config(trace=CuspyTraceProfiler.Config(freq=100, record_py_stacks=True), memory_snapshot=MemorySnapshotProfiler.Config(freq=50)) ``` ## User-facing changes | Before | After | | --- | --- | | `enable_profiling=True` | `trace=KinetoTraceProfiler.Config()` | | `enable_profiling=True, cuspy=CuspyProfilerConfig(...)` | `trace=CuspyTraceProfiler.Config(...)` | | `save_traces_folder`, `profile_freq`, `profiler_{warmup,active,repeat,skip_first,skip_first_wait}` | `save_folder`, `freq`, `warmup`, `active`, `repeat`, `skip_first`, `skip_first_wait` | | `enable_memory_snapshot=True` | `memory_snapshot=MemorySnapshotProfiler.Config()` | | `save_memory_snapshot_folder`, `memory_snapshot_freq`, `memory_snapshot_max_entries` | `save_folder`, `freq`, `max_entries` | | memory snapshot freq falls back to `profile_freq` | defaults to 10 | | `Profiler.active()` | removed (no callers) | Output paths, structured-log span names and `maybe_cuda_graph_annotation_config()` are unchanged. Mechanical, safe to skim: recipe, test and doc migrations (`torchtitan_recipes/`, `tests/`, graph_trainer docs, numerics_debugging skill). ## Numerics Loss and grad_norm are bitwise identical to main for 20 steps of the llama3 debug model. Setup: flex attention, seed 42, deterministic, 2 GPUs, Kineto trace and memory snapshot enabled. ## Testing - Profiler, trainer and graph_trainer profiler unit tests. - New `test_memory_snapshot_dumps_every_freq_steps_and_on_oom`: the OOM dump moved into `MemorySnapshotProfiler.close(exc)` and had no test. - 2-GPU debug model runs: the Kineto trace with memory snapshots, and the Cuspy trace with py stacks, write the same files at the same steps as main.
Summary (human-written)
Metrics logger is not object-oriented while it should be -- this PR addresses it.
LR scheduler mostly is, but was using config in the wrong way -- this PR fixes it.
Why
Metrics processors already use
Configurable, but their exporters are selected by backend-specific booleans and hardcoded constructors. Adding an exporter requires editing the supervised or RL processor, even though both already share the logger implementations.LR schedulers have a related construction gap:
LRSchedulersContainer.Config.build()always returns the base container. A subclass with its own nested config therefore loses its custom behavior unless it also overridesbuild(). The new subclass regression fails on base commit8289613196e474828ff9e81d55227812f10d1d32with a base container instead of the requested subclass.Example:
What changed
Configurablecomponents with nested configs. Both metrics processors consume logger config lists; remove the fixed exporter factory andLoggerContainer.WandBLogger.Config.project.WANDB_PROJECTstill takes precedence; constructing an RL processor no longer mutates that environment variable. Exporter construction failures now propagate rather than being swallowed by the supervised W&B factory.Configurable.Config.build(). The schedule formula, host LR handling, metrics, and checkpoint state are unchanged.Alternatives considered
User-facing changes
enable_tensorboard=Trueloggers=[TensorBoardLogger.Config()]enable_wandb=Trueloggers=[WandBLogger.Config()]enable_mlflow=Trueloggers=[MLFlowLogger.Config()]wandb_project="titan_rl"WandBLogger.Config(project="titan_rl")loggers=[]Numerics
Compared against
8289613196e474828ff9e81d55227812f10d1d32on four NVIDIA GB300 GPUs, with seed 42, deterministic execution, the Llama 3 debug model, FlexAttention, sequence length 128, and 10 training steps. Loss and gradient norm were read from TensorBoard and checked withscripts/loss_compare.py --metrics=loss,grad_norm --assert-equal.Testing
python -m pytest tests/unit_tests/cpu/components/optim tests/rl/unit_tests/cpu/test_metrics.py tests/unit_tests/cpu/observability -q: 342 passed, 1 skipped (optional real MLflow client absent).python -m pytest tests/unit_tests/cpu/scripts/test_loss_compare.py tests/unit_tests/cpu/scripts/test_checkpoint_compat_test.py tests/unit_tests/cpu/config -q: 217 passed.pr-reviewskill approve after fixing their initial callsite/constructor-contract findings.Known validation limitations
2.16.0.dev20261010+cu132rejectsloss_kwarg_mbsfor pre-split pipeline inputs. PP GPU numerics could not be compared; pipeline rank selection remains covered by CPU tests.distributed/batch_invariant.py; that unrelated cleanup is excluded from this PR.