Repository navigation
[fix] wandb: stop dropping validation metrics logged at a training step (1/2) - #5227
felipemello1 wants to merge 5 commits into
Conversation
52ea9f5 to
c662560
Compare
WandBLogger.log commits every wandb.log(step=N). W&B drops later logs to a committed step, so validation logged after training at the same step never lands. Accumulate each step's row and push it with an explicit commit(): the trainer commits after validation; the RL controller commits the previous step at the top of each step and the last row after post-training validation.
…it() The RL trainer loop now calls metrics_processor.commit() at the top of each step.
e82acc1 to
09deddb
Compare
|
Reply from claude: Rebased on main. The patch is unchanged: main still commits every W&B log ( @claude please review |
|
Claude finished @felipemello1's task in 1m 45s —— View job Needs discussion: the patch looks correct, but it conflicts with #5648, which fixes the RL half of the same bug a different way. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- the patch looks correct and small, but #5648 (vkuzo, open) fixes the RL half of the same bug in a conflicting way. Maintainers need to pick one before this lands.
What this PR does. WandBLogger.log stops passing commit=True, so every log to step N accumulates into W&B row N. A new commit() (a no-op on BaseLogger, forwarded by LoggerContainer and both MetricsProcessors) pushes the open row. The core Trainer.train calls it after validation. The RL controller calls it at the top of each trainer-loop step and after post-training validation.
Example. Core run, log_freq=10, validator freq=10:
main: log(train, step=10, commit=True) -> row 10 committed
log(val, step=10, commit=True) -> dropped (row 10 already committed)
PR: log(train, step=10); log(val, step=10)
commit() -> log({}, step=10, commit=True) -> row 10 = train + validation_metrics/*
In RL, the same thing happens to post-training validation at num_training_steps (controller.py:915).
Must fix
- PR description -- "Summary (human-written)" is empty. The author has to write it (agents leave it as the placeholder).
- Overlap with #5648 -- #5648 fixes the dropped final RL validation with
define_metric("*", step_metric="trainer/step")and still commits on every log. That makes_stepcount log events instead of optimizer steps, and it leaves coreTrainervalidation dropped. This PR argues against that design, with reasons (_stepalignment,WANDB_RESUME_FROM/WANDB_FORK_FROM=<run>?_step=N), and it also fixes core. I'd go with this PR. The two edit the same lines ofWandBLogger.logandtest_metrics.py::test_wandb_with_log_dir, so they can't both land. Close one, and link it in the description of the other.
Should consider
torchtitan/experiments/torchft/trainer.py:534-- oneself.metrics_processor.commit()after thevalidator.validate(...)block would make torchft behave like core: rows go out on time instead of one logged step late. Its test already uses aMagicMockprocessor, so no test change. This is cheaper than the NOTE explaining why it's skipped.
Details
- Callsites checked.
metrics_processor.log/logger.logare called only fromtrainer.py,components/validator.py,models/flux/validator.py(all insideTrainer.trainbefore the newcommit()), torchft's owntrain(), and the RL controller (controller.py:927,:1225). Nothing logs to step N aftercommit()in core, so nothing can be dropped there. Test stand-ins:test_trainer.py:980andtest_invalid_loss.pycall onlytrain_step, nottrain(), so they don't needcommit. - Exit paths. If
DataloaderExhaustedErroris raised,train_stephasn't logged yet and the previous step was already committed. If validation or the RL loop raises,close()callswandb.finish(), which flushes the open row. torchft and any other loop that never callscommit()falls back to W&B's default: row N is committed when step N+1 is logged. - RL ordering. The first iteration's
commit()pushes the pre-validation row (step=start_step). The commit inside the loop leaves the last step open, so post-validation joins it, andcontroller.py:917pushes it. - Latency. In core, a training row now reaches W&B after checkpoint save and validation for that step, not right after
train_step. That's negligible. - The resume case (pre-validation at
start_step, which an earlier run of the same W&B run already committed) behaves the same as on main.
Not verified: W&B's real behavior for log(step=N) without commit followed by log({}, step=N, commit=True). I'm relying on the author's offline .wandb readback, which wasn't re-run on this head.
A maintainer still needs to review (core trainer.py and observability/metrics.py).
Like Trainer.train: the row goes out at the end of its step instead of when the next step logs.
|
Reply from claude: Addressed the 20:59 review in e2dea62: torchft calls @claude please review |
|
Claude finished @felipemello1's task in 51s —— View job Needs discussion: the torchft item is fixed. Two things are still open: the empty human-written summary, and the conflict with #5648, which the maintainers need to settle. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- the new commit resolves the torchft item and no new problems turned up, but #5648 (still open) conflicts with this PR, and only maintainers can decide between them.
Re-review of e2dea62 (since the 20:59 review).
Resolved
- torchft:
torchtitan/experiments/torchft/trainer.py:539callsself.metrics_processor.commit()after the validator block, in the same place coreTrainer.traindoes (torchtitan/trainer.py:496).self.metrics_processoris built fromconfig.metrics.build(...)(torchft/trainer.py:222), the coreMetricsProcessor, which now hascommit(). The NOTE explaining why torchft skipped the commit has been removed. - "Not verified" from the last review: the author read back the real
WandBLoggeroffline on this head (W&B 0.31.0). Validation lands in the training row,close()flushes an uncommitted last row, and main drops the validation keys. That covers the W&B behavior I couldn't check myself.
Still open (must fix)
- PR description: "Summary (human-written)" is still empty. The author has to write it.
- Overlap with #5648 (vkuzo, open): both PRs edit the same lines of
WandBLogger.logandtest_metrics.py::test_wandb_with_log_dir, so they can't both land. My recommendation is unchanged: take this PR. It keeps_stepaligned with the optimizer step, and it also fixes coreTrainervalidation, which #5648 leaves dropped. Once maintainers decide, close the other PR and link it from this description.
Details
- With torchft added, every
train()in the repo callscommit()once per step, after validation. There are only two:torchtitan/trainer.py:456andtorchtitan/experiments/torchft/trainer.py:484. Nothing logs to step N after that commit, so no log can be dropped. - torchft's
DataloaderExhaustedErrorbreakskips the commit for that iteration, buttrain_stephadn't logged yet, so no row is open. Core behaves the same. - The torchft test uses a
Mockprocessor, so the new call needs no test change.
A maintainer still needs to review (core trainer.py and observability/metrics.py).
|
Reply from claude: heads-up for reviewers. #5648 (draft) fixes the same bug: W&B drops a validation log made at a step that training already logged. The two PRs edit the same lines of How each fixes it:
Evidence for this PR on its current head: the real |
|
Reply from claude: Similar open PR: #5648 (vkuzo, draft). It fixes the RL half of the same W&B commit bug and edits the same lines of
|
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.
…or; METRICS.md names commit() Trainer.train now calls metrics_processor.commit() after each step, so the fake trainer in test_trainer_keeps_scheduled_eval_during_warmup needs one. METRICS.md's custom-exporter paragraph now says when commit() is called.
|
Reply from claude: Merged main (0d35b95) in b05915e. Main's #5775 deleted d3b269c fixes a test this PR broke: the fake trainer in Tests at d3b269c: @claude please review |
|
Claude finished @felipemello1's task in 56s —— View job Needs discussion: the merge and the test fix are correct, and the summary is now filled in. The only open item is the conflict with #5648, which the maintainers need to settle. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- the merge and the test fix are correct and the human-written summary is now filled in. The only open item is the conflict with #5648 (still an open draft), and that is the maintainers' call.
Re-review of b05915e + d3b269c (since the 21:12 review).
Resolved
- "Summary (human-written)" is now written by the author.
- Merge with #5775 (
LoggerContainerdeleted):MetricsProcessor.commit()(torchtitan/observability/metrics.py:645) walksself.loggersthe same waylog(:577,:631) andclose(:649) do. The RL processor's_backendsareBaseLoggerinstances (MetricBackendis an alias,rl/observability/metrics/processor.py:22), sobackend.commit()resolves for TensorBoard, W&B and MLflow. MLflow inherits the no-op. test_accelerator_graph_validation_config.py:244: this was the only stand-in trainer that runsTrainer.train. The repo has just twotrain()loops (torchtitan/trainer.py:486,experiments/torchft/trainer.py:503), and both now callcommit()after validation. The other fake processors (test_trainer.py:159,:978,test_invalid_loss.py,test_validator.py) never reachtrain().
Still open (must fix)
- Overlap with #5648 (vkuzo, draft): both PRs edit the same lines of
WandBLogger.log, so only one can land. My recommendation hasn't changed: keep this PR. It keeps_stepequal to the optimizer step, and it also fixes core and torchft validation, which #5648 leaves dropped. Once maintainers decide, close the other PR and link it in this description.
Should consider
tests/rl/unit_tests/cpu/test_metrics.py:692-694-- the newcommit()assertion repeats whattest_wandb_commit_keeps_validation_in_the_training_rowalready checks on the sameWandBLogger(plus its idempotence). Dropping these 3 lines removes the duplication; the RL test keeps checking thatlogno longer passescommit=True.
No new problems in the new commits.
A maintainer still needs to review (core trainer.py and observability/metrics.py).
… a step are kept (#5903) ## Summary (human-written) Previously I added "commit=True" to titan, because in coreweave i would see multiple steps and wouldnt see logging. This damage pretraining, because log is called twice, and once you log a step, you connect log again for the same step. This PR solves both problems in one way: - Add a step_metric, instead of step This automatically commits, and support multiple .log calls to the same step. ## Agent details **TLDR:** W&B drops every validation row logged at a step that training already logged. That is every core validation row at the default settings. Now each W&B row carries the training step as `trainer/step` and logs without `step=`, so W&B keeps every row, in core training and RL alike. On the core debug model, main keeps 1 of 4 validation rows in W&B; this PR keeps 4 of 4. ```text main: log(train, step=10) -> row 10 sent log(validation, step=10) -> dropped this PR: log(train, step=10) -> row {trainer/step: 10, loss: ...} log(validation, step=10) -> row {trainer/step: 10, validation_metrics/loss: ...} ``` ```python # before self.wandb.log(wandb_metrics, step=step, commit=True) # after (the two define_metric calls run once, in __init__) self.wandb.define_metric("trainer/step") self.wandb.define_metric("*", step_metric="trainer/step") self.wandb.log({**wandb_metrics, "trainer/step": step}) ``` **Problem** 1. `WandBLogger.log` calls `wandb.log(metrics, step=N, commit=True)`. 2. W&B ignores a log to a step below its current one. After row N is sent, step N is below it. 3. Core training logs validation right after training, at the same step (`Trainer.train`). 4. At the defaults (`log_freq=10`, validator `freq=10`), both log at the same steps, so every core validation row is dropped. 5. RL drops its final validation pass the same way: it logs at the last step, after training logged that step. **Solution** 1. Every row carries the training step in a regular key, `trainer/step`. 2. Rows log without `step=`, so W&B sends each one at once. `commit=True` is W&B's default when `step` is not given. 3. `define_metric` makes `trainer/step` the x-axis of the generated charts. 4. Unchanged: TensorBoard and MLflow. Metric keys keep their names; every W&B row gains one key, `trainer/step`. **Results** ```text main vs this PR, same recipe: core debug model (llama3 debugmodel), 1 GPU, 10 steps, log_freq=5, validator freq=5. Validation ran at steps 1, 2, 5 and 10. Training logged at steps 1, 5 and 10. W&B rows read back with the API. main (9f70e55) this PR validation rows in W&B 1 of 4 (step 2) 4 of 4 (steps 1, 2, 5, 10) training rows in W&B 3 (steps 1, 5, 10) 3 (steps 1, 5, 10) summary validation loss 6.97 (step 2's, stale) 4.14 (step 10's) ``` - On main, W&B dropped validation at steps 1, 5 and 10: training had already logged those steps. ```text Online run, wandb 0.31.0, with this PR's WandBLogger at its head. Rows read back with wandb.Api().run(...).scan_history(), 20 s after close(): _step trainer/step logged 0 0 validation/reward 0.1 1 1 loss 0.9 2 2 loss 0.8 3 3 loss 0.7 4 1 validation/reward 0.2 <- older trainer/step, logged after step 3: kept 5 4 loss 0.6 6 2 validation/reward 0.3 <- last row, older trainer/step: kept ``` - All 7 rows were kept. - With `wandb.log` calls that pass no `step=`, a CPU repro also measured rows landing in 7-18 s, and every row surviving a kill 20 s after the last log. - Not checked: a kill right after a log. ```text dapo_math, Qwen3.5-4B-Base, 4K context, 1 trainer GPU + 3 generator GPUs, seed 0, 10 steps; W&B rows read back this PR before this PR (same recipe, 50 steps, 11-02) validation rows 2: trainer/step 0 and 10 (the final pass) 1: step 0; the final pass at step 50 was dropped training rows 10 (trainer/step 1-10) 50 steps 1-10 reward ~0.2, loss ~0.02, grad norm ~0.09 in both runs; the same training keys, apart from keys added on main since 11-02 ``` **Costs.** W&B's `_step` (`Step` in the UI) now counts rows: 1. A saved panel with `Step` on its x-axis must switch to `trainer/step`. Runs from before this PR have no `trainer/step`, so a panel that mixes old and new runs needs `Step` for the old ones. Not checked in the UI. 2. `WANDB_RESUME_FROM` and `WANDB_FORK_FROM` take `<run>?_step=N`. To rewind to training step S, look up the `_step` of a row whose `trainer/step` is S (`METRICS.md` shows how). A rewind also drops validation rows for older steps that were logged after that row. 3. Only if you set `WANDB_RUN_ID` to an existing run (torchtitan starts a new run on every launch): the run appends its rows, so replayed steps show twice. Before, W&B dropped them. 4. The runs table's `trainer/step` column shows the last row's step. After a validation row for an older step, that is not the newest step. You may ask: - Why not RL only? #5648 makes the same change opt-in, and only RL opts in. Core keeps `step=`, so core validation rows stay dropped (#5027). This PR changes the default for core and RL. - Why not just drop `commit=True`? W&B then holds row N until step N + 1 logs. RL rows would land one RL step late (minutes), and a scancel or time limit would lose the last row. - Why not collect a step's logs and commit after the last one? Every trainer would need to call that commit, after its last log of each step. #5227 did this; it is closed in favor of this PR. - Is it OK that `Step` counts rows for every W&B user? It follows W&B's own guidance. The `wandb.log` docstring (wandb 0.31.0) says the step must always increase, that any metric can be the x-axis, and that it is often better to treat the W&B step like a timestamp than a training step. NOTE: - Fixes #5027. - The RL periodic-validation PR (#5228) logs each pass at the step it started, after training has logged later steps. It needs this PR, or W&B drops those rows. **Test plan** ```text PYTHONPATH=$PWD pytest tests/unit_tests/cpu/observability tests/rl/unit_tests/cpu/test_metrics.py -q # 230 passed, 1 skipped (main: 230 passed, 1 skipped) PYTHONPATH=$PWD pytest tests/unit_tests/cpu -q --continue-on-collection-errors # see the line below pre-commit run --files <changed files> # all hooks pass; pyrefly 0 errors ``` - `tests/unit_tests/cpu`: 1927 passed, 5 failed, 5 skipped, 3 xfailed, 1 error. Main fails the same 5 tests and errors on the same file on this host (aarch64 CPU: inductor's flex_attention lowering in the LoRA and Qwen3.5 mrope tests, and the quantization test's import). - The RL logger test's call assert now expects `{"k": 1.0, "trainer/step": 3}` (`tests/rl/unit_tests/cpu/test_metrics.py`). - Not checked in the W&B UI: a saved panel that mixes runs from before and after this PR. Runs from before have no `trainer/step` key (checked on the 11-02 dapo run's rows), so a panel on `trainer/step` has no x value for them. - CI: `RL Multi-GPU Unit Tests` fails `test_bitwise_parity.py::TestBitwiseParityQwen35DebugVarlen::test_trainer_vs_vllm_prefill`. Main `9f70e5597` fails the same test. --------- Co-authored-by: Felipe Mello <[email protected]>
Summary (human-written)
In coreweave, if we didnt use wand.log(..., commit=True), the logs wouldnt be pushed, so i added it to a PR.
Later i learned that we cannot commit the same step twice, and this happen if you have validation on.
Agent details
TLDR: W&B drops validation metrics logged at a step where training already logged. With the defaults (
log_freq=10, validatorfreq=10), that is every validation in core training.WandBLoggernow collects a step's metrics into one row. A newcommit()sends the row after the step's last log.Problem
WandBLogger.logcallswandb.log(metrics, step=N, commit=True).commit=Truemakes W&B finalize row N and send it at once.validation_metrics/*never reaches W&B.Controller.run). The same rule drops it.Solution
WandBLogger.logno longer passescommit=True. Whenstepis set, W&B then collects the log into that step's row.BaseLogger.commit()sends the open row.Trainer.trainand torchft'strain()call it after validation.METRICS.mdtells custom exporters when it is called.TensorBoardLoggerandMLFlowLoggerstill write at once. Theircommit()is the base no-op.Results
Numerics for a logging fix: which metrics W&B keeps in each row.
The real
WandBLoggerat e2dea62, before the merge with main (the merge leftWandBLogger.logandcommitunchanged), CPU, offline, W&B 0.31.0. Steps 1, 3 and 4 log loss and validation; step 2 logs loss only. Step 4 gets nocommit()beforeclose(). Rows read back from the run file:Core training, 1 GPU, llama3 debugmodel,
log_freq=5, validatorfreq=5, W&B 0.28.1. Run on an earlier version of this change, before its rebase onto main. Losses differ slightly: no fixed seed.RL: in the next PR's 2-GPU run (after the merge with main, so through main's new
loggerslist), every validation pass landed in its step's row, next to that step's training metrics.You may ask:
commit=True? Then W&B sends row N only when step N+1 logs. Every row would show up late: up tolog_freqsteps, or one RL step.define_metric("*", step_metric="step")? Then_stepwould stop matching the training step. That breaks panels of older runs, andWANDB_RESUME_FROM/WANDB_FORK_FROM=<run>?_step=N, whichWandBLoggerpasses towandb.init.NOTE: a step's row reaches W&B when its last log lands. For the last RL step, that is after the post-training validation pass, which can take hours on Terminal-Bench.
close()in afinally, andclose()callswandb.finish().Test plan
New test:
test_wandb_commit_keeps_validation_in_the_training_row. The next PR'stest_overlapped_validation_runs_beside_trainingchecks the RL log and commit order. The fake trainer intest_trainer_keeps_scheduled_eval_during_warmupgets a no-opmetrics_processor, becauseTrainer.trainnow callscommit().CI at this head (d3b269c): Lint, RL CPU, RL 1-GPU and multi-GPU unit tests, RL integration tests and rl-kimi-k3 pass. Core CPU/GPU unit tests and TorchFT tests run only once the PR is ready for review, so the local runs above are their only evidence.