Skip to content

fix(utils): TimeoutChecker budgets for the slowest step and upcoming validation - #4483

Open
linj-glitch wants to merge 7 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/timeout-checker-slowest-step
Open

linj-glitch wants to merge 7 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/timeout-checker-slowest-step

Conversation

@linj-glitch

@linj-glitch linj-glitch commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Current integration and validation (2026-10-29 UTC)

Merged upstream main feb735f6132179d62634f515b2727952efb0dd14 into this branch with a signed additive commit, 9343a128fd5569e3a505129e06e6ad9547ea33b7, to satisfy the required CI freshness gate. The production patch retains exactly its original added and removed lines. An independent integration review found no new production issues.

  • Targeted tests on the resulting tree: 38 passed, 531 deselected, 28 warnings. Invocation from tests/: pytest unit/utils/test_timer.py unit/algorithms/test_grpo.py -k 'TimeoutChecker or timeout or next_step_runs_validation' -p no:cacheprovider -o 'addopts=-rA -q'.
  • pre-commit run --all-files: formatting, Ruff, TOML, and recipe checks passed. Pyrefly reports 44 errors, with identical error messages, source paths, and multiplicities on pristine upstream main; there are no new diagnostics from this PR. The overall hook command therefore exits 1 for the baseline type errors.
  • git diff --check passed; the commit contains current main and a DCO sign-off. Validation used the existing Python 3.13 environment and a private CPU-only Ray cluster, with module resolution verified against this PR checkout.

No real Slurm timeout or functional/convergence run was performed; this refresh preserves the checkpoint look-ahead patch.

Repository CI must validate this exact head; earlier-head results do not establish that it passes. Existing reviews have been preserved.

What does this PR do ?

Makes the checkpoint_must_save_by look-ahead in TimeoutChecker predict the next step from the slowest step seen so far instead of the mean, and lets the sync GRPO loops add one more step's worth of time when the next step will also run validation (periodic schedule or val_at_end). The estimate is a heuristic over step times observed in the current process: a job may save and exit earlier than before, by roughly the gap between its slowest observed step and a typical one (plus one more step when the next step validates); it is not a hard bound on a step slower than any seen so far.

Issues

None.

Usage

No new config. Every algorithm loop already constructs TimeoutChecker(timeout=checkpointing["checkpoint_must_save_by"], fit_last_save_time=True), so the new estimate applies to any run that sets checkpointing.checkpoint_must_save_by. would_save() / check_save() gain an optional extra_s argument (default 0.0) that is only used when fit_last_save_time=True; grpo_train and grpo_train_sync pass it automatically. A custom loop can do the same:

timeout = TimeoutChecker(timeout="00:03:30:00", fit_last_save_time=True)
...  # optional initial validation / warm-up: not timed as an iteration
timeout.start_iterations()  # right before the training loop
for step in ...:
    ...
    timeout.mark_iteration()
    # Budget an extra generation wave when the next step will also validate.
    should_save = timeout.check_save(
        extra_s=max(timeout.iteration_times) if next_step_validates else 0.0
    )

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
  • Did you run the unit tests and functional tests locally? Visit our Testing Guide for how to run tests (unit tests only, see Validation below)
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs. (Docstrings and inline comments; no docs page references checkpoint_must_save_by beyond the exemplar YAMLs.)

Additional Information

Root cause. checkpoint_must_save_by exists so that a job saves and exits before the scheduler's wall-clock limit. With fit_last_save_time=True, would_save() fired when elapsed + mean(iteration_times) >= deadline. RL step times vary widely (long-tail generation in agentic rollouts, or a step that also runs validation), so a step longer than the mean could start just before the deadline and still be running when the job was killed. That step's work was lost, and so was the checkpoint the deadline was meant to produce; users had to set the deadline much earlier than needed to stay safe.

How it manifests. A job hits the Slurm time limit mid-step even though checkpoint_must_save_by looked like it had enough margin, and the run resumes from the previous checkpoint.

Scope / changes.

  • nemo_rl/utils/timer.py: would_save(extra_s=0.0) / check_save(extra_s=0.0) predict the next step with max(iteration_times) + max(0.0, extra_s) instead of the mean. With a stable step time max is close to the mean; with variable step times the estimate is larger. Docstring and comments describe this as a heuristic over observed timings rather than a guarantee. mark_iteration() no longer raises UnboundLocalError when start_iterations() was never called (the first mark then starts the first iteration); not reachable from the training loops, which all call start_iterations() first, but iteration_times is now load-bearing.
  • nemo_rl/algorithms/grpo.py (_grpo_train_impl, the sync grpo_train path) and nemo_rl/algorithms/grpo_sync.py (grpo_train_sync): when the next step will run validation, check_save is called with extra_s = max(iteration_times). The look-ahead lives in a shared helper, _next_step_runs_validation, that mirrors should_run_validation for step total_steps + 2 (periodic schedule with val_period / val_start_at, or val_at_end when the next step is the last one by max_num_steps or by the epoch bound) and is false on the last step, which has no successor. A validating step costs roughly one more generation wave, and that time is not in iteration_times until a validating step has run in this process (for example right after a resume).
  • Both sync GRPO loops now call timeout.start_iterations() right before the training while loop instead of before the optional val_at_start pass, so the initial validation (and refit) is not recorded as the first, and therefore slowest, "iteration" that the max-based estimate would then use for the whole run.
  • All other callers (async GRPO, DPO, SFT and SFT v2, RM, PPO, distillation, xtoken off-policy distillation, single-controller) are not edited; they only pick up the max-based estimate through their existing check_save() calls.

Behaviour change. Only affects runs with checkpoint_must_save_by set (all algorithm loops construct the checker with fit_last_save_time=True). Jobs whose step times vary may save and exit earlier than before: the early exit is bounded by the difference between the slowest observed step and a typical step, plus one step when the next step validates in the two sync GRPO loops. The estimate uses only steps observed in the current process: a step slower than every step seen so far, or the first validating step after a resume in loops other than the two sync GRPO loops, can still overrun the deadline. In loops other than the two sync GRPO loops, start_iterations() still precedes val_at_start, so an initial validation there can inflate the estimate for the rest of the run (safe direction; follow-up). Nothing changes when fit_last_save_time=False or when checkpoint_must_save_by is unset.

Dependencies / stacking. None. The branch is six commits rebased onto the current main tip f201e5b7c4be59b6030d1d185998193483c81887 (fix(refit): release trainer memory before collective export (#3984)), so it is 0 commits behind main (the pr-branch-up-to-date-check gate fails a PR more than 10 commits behind). It does not depend on, and is not depended on by, any other open PR; #4481 (configurable NCCL collective timeout) touches different code.

Commits (head 6c40f6c52562757106d8e8e64ae6424037a161eb; rebased 2026-10-13 from merge-base b6016e67 onto f201e5b7, so the SHAs differ from the pre-rebase commits 3845728..9e42d4d while the combined diff is unchanged, see Validation).

  • d13522f996ae8e12c06f6cd9e37a655ab5192a53 fix(utils): TimeoutChecker budgets for the slowest step and upcoming validation
  • 95161f7237d2214df172f77ba452962371c0d55d docs(utils): describe the TimeoutChecker look-ahead as a heuristic (comment-only)
  • 0f5e9918ab9de05c4bb08ba13d142ee8634e7c5a fix(utils): make TimeoutChecker.mark_iteration() usable without start_iterations()
  • b606c81e7ac8d47e34b044935d8846045e57f47d fix(grpo): budget the upcoming validation for val_at_end and skip the last step
  • c1e67899b12220f369dcd611e8c385e4c1c30b55 fix(grpo): time TimeoutChecker iterations from the first training step
  • 6c40f6c52562757106d8e8e64ae6424037a161eb test(grpo): reach _next_step_runs_validation through the grpo module alias (main grew the same explicit import list; the final diff leaves the import block untouched)

Self-review. A team self-review of the branch confirmed 11 findings: 7 were fixed in the last four commits above (the val_at_end / last-step gap in the look-ahead, the val_at_start iteration-timing order, the latent mark_iteration() crash, grpo_train_sync and val_start_at test coverage, and tying the budgeted steps to the steps validate() ran on), 2 were corrections to this description (the pyrefly coverage statement and the exhaustive list of unchanged callers), and 2 need no change here: the pre-existing sleep-based test_fit_last_save_time_enabled passes through the plain elapsed branch (the deterministic tests now cover the look-ahead; optional cleanup in a separate PR), and unit-test CI has not yet run on this fork PR (see Remaining gaps).

Tests.

  • tests/unit/utils/test_timer.py: test_fit_last_save_time_uses_slowest_iteration (max fires where a mean-based check would not), test_extra_s_is_added_to_predicted_iteration (extra_s on would_save/check_save, one-shot behaviour preserved), test_extra_s_ignored_without_fit_last_save_time, test_mark_iteration_without_start_iterations.
  • tests/unit/algorithms/test_grpo.py::test_grpo_timeout_budgets_upcoming_validation: parametrized over grpo_train and grpo_train_sync and over six schedules (periodic; periodic from val_start_at=3; val_period=7 over 6 steps so nothing validates, not even after the last step; val_at_end with the last step set by max_num_steps; val_at_end with the last step set by max_num_epochs; periodic plus val_at_end). Each case asserts extra_s == 30.0 (the slowest observed step) exactly on the check before each validating step and 0.0 elsewhere, and that validate() really ran on exactly those steps.
  • tests/unit/algorithms/test_grpo.py::test_grpo_timeout_iterations_start_after_initial_validation: for both sync trainers, validate(step=0) (val_at_start) runs before start_iterations(), which precedes the first mark_iteration().
  • tests/unit/algorithms/test_grpo.py::test_next_step_runs_validation_for_timeout_budget: ten direct cases for the helper, including the epoch-bounded last step, a one-step-per-epoch dataloader wrapping into the final epoch, use_multiple_dataloader (only max_num_steps bounds the run) and the last step itself.
  • The existing test_grpo_exit_on_timeout[grpo_train|async_grpo_train] cover the one-shot exit for both trainers.
  • Red check: with the self-review commits' production changes stashed, the new cases fail for the intended reasons (10 of the 14 budget/ordering cases fail on the pre-fix predicate and ordering; the four purely periodic cases pass; test_mark_iteration_without_start_iterations raises UnboundLocalError).

Validation (2026-10-13, head 6c40f6c52562757106d8e8e64ae6424037a161eb, rebased onto main f201e5b7).
Environment: Python 3.13.14, torch 2.13.0+cu130, 1x NVIDIA L4 (23 GB), shared uv venv synced from main's uv.lock (base + test + dev); Megatron-Core / Megatron-Bridge / TransformerEngine not installed (no mcore tests are in the selection). Native invocation: pytest from tests/ with the repo conftest starting a local Ray cluster (RAY_ENABLE_UV_RUN_RUNTIME_ENV=0), one session at a time.

cd tests && RAY_ENABLE_UV_RUN_RUNTIME_ENV=0 uv run --no-sync pytest unit/utils/test_timer.py -p no:cacheprovider -o addopts='-rA -q'
# 58 passed in 14.92s, exit 0
cd tests && RAY_ENABLE_UV_RUN_RUNTIME_ENV=0 uv run --no-sync pytest unit/algorithms/test_grpo.py -k 'timeout or timer' -p no:cacheprovider -o addopts='-rA -q'
# 26 passed, 220 deselected in 16.05s, exit 0 (exit_on_timeout x2, budgets_upcoming_validation x12,
# iterations_start_after_initial_validation x2, next_step_runs_validation x10)
cd tests && RAY_ENABLE_UV_RUN_RUNTIME_ENV=0 uv run --no-sync pytest unit/algorithms/test_grpo.py -k 'exit_on_timeout or budgets_upcoming_validation or timer or start_iterations' -p no:cacheprovider -o addopts='-rA -q'
# 14 passed, 232 deselected in 29.85s, exit 0 (the handoff's narrower selection: exit_on_timeout x2, budgets_upcoming_validation x12;
# a strict subset of the 26 above)
cd tests && RAY_ENABLE_UV_RUN_RUNTIME_ENV=0 uv run --no-sync pytest unit/algorithms/test_grpo.py -p no:cacheprovider -o addopts='-rA -q'
# 246 passed in 25.98s, exit 0 (whole file, since both sync loop bodies changed; 233 of these tests existed on the
# pre-rebase head, where the whole file also passed 233/233 on 9e42d4d and fb59998; the other 13 arrived with main)
SKIP=pyrefly-typecheck uv run --no-sync pre-commit run --files $(git diff --name-only origin/main...HEAD)
# end-of-file-fixer, trailing-whitespace, ruff, ruff (isort), ruff-format, minimize-check: all Passed, exit 0; working tree unchanged
uv run --no-sync pyrefly check
# errors shown: 0 (errors ignored: 373), exit 0 (nemo_rl/utils/timer.py is in pyrefly.toml project-includes and is covered by this gate;
# grpo.py and grpo_sync.py are not, so per-file `pyrefly check nemo_rl/algorithms/grpo.py nemo_rl/algorithms/grpo_sync.py nemo_rl/utils/timer.py`
# was run as well: 122 diagnostics on this head (grpo.py 94, grpo_sync.py 28, timer.py 0), the identical multiset of
# (file, rule, message) to main f201e5b7 for the same three files (0 new, 0 removed; all pre-existing).
# Earlier run, on the pre-rebase head 9e42d4d against main fe1d97ce: 119 vs 121 diagnostics, 0 new; the one textual
# difference vs main is the pre-existing GenerationConfig.setdefault no-matching-overload at grpo.py:624 (main:632), whose
# message lists one more GenerationConfig key that main added in nemo_rl/models/generation/interfaces.py; this branch touches neither.)

Rebase onto current main (f201e5b7c4be59b6030d1d185998193483c81887): git rebase origin/main from merge-base b6016e67. Two of the six commits stopped on the same adjacent import line in tests/unit/algorithms/test_grpo.py (main added _raise_if_length_penalty_enabled_without_nemo_gym exactly where 86dde25c added _next_step_runs_validation and 9e42d4db removed it again); resolved by keeping both imports in b606c81e and dropping the PR's one in 6c40f6c5, so the final diff does not touch the import block. The other four commits replayed unchanged (same git patch-id). Checks after the rebase: the rebased tree a333d40b49e7121683cc4c88ce63dd6f51371269 is byte-identical to git merge-tree --write-tree origin/main 9e42d4db computed before the rebase; git diff origin/main..HEAD is content-identical to the pre-rebase git diff b6016e67..9e42d4db (same git patch-id c274173c, the same 5 files, +435/-17; only hunk line numbers shift); git rev-list --count HEAD..origin/main is 0; git status --porcelain is empty. All tests above ran on the rebased head, so the earlier scratch-merge runs against fe1d97ce (58 passed; 26 passed, 216 deselected) are superseded.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 5, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@linj-glitch
linj-glitch marked this pull request as draft October 5, 2026 06:10
@linj-glitch
linj-glitch force-pushed the linj/timeout-checker-slowest-step branch from b3af828 to 3845728 Compare October 8, 2026 00:15
@linj-glitch
linj-glitch marked this pull request as ready for review October 13, 2026 05:02
linj-glitch and others added 6 commits October 13, 2026 02:59
…validation

Predict the next iteration with max(iteration_times) instead of the mean so a
slower-than-average step cannot start right before checkpoint_must_save_by and
be killed by the scheduler. check_save/would_save take an optional extra_s, and
the sync GRPO loops pass one step's worth when the next step runs validation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
The look-ahead budgets for the slowest iteration observed so far. The inline
comments claimed that a single slow iteration therefore cannot run past the
deadline, which overstates it: a step slower than any seen so far can still
overrun. Reword the comments in TimeoutChecker.would_save and the two sync GRPO
call sites to describe the estimate as a heuristic over observed timings.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
…_iterations()

mark_iteration() assigned elapsed_time only when previous_iteration_time was
set but appended it unconditionally, so a checker whose start_iterations() was
never called raised UnboundLocalError on the first mark. Treat that first mark
as the start of the first iteration instead. Not reachable from the training
loops, which all call start_iterations() first, but the look-ahead now takes
max(iteration_times), so the list's contents are load-bearing.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
… last step

next_step_validates mirrored only the periodic clause of should_run_validation,
so the step before a val_at_end final step was not budgeted, and the predicate
could be true on the last step, which has no successor. Move the look-ahead
into _next_step_runs_validation, shared by grpo_train and grpo_train_sync,
which follows should_run_validation for the next step (periodic schedule, or
val_at_end when the next step is the last one by max_num_steps or by the epoch
bound) and is false on the last step.

Tests: parametrize test_grpo_timeout_budgets_upcoming_validation over both
sync trainers and over periodic, val_start_at, val_at_end (by steps and by
epochs) and no-validation schedules, assert the budgeted steps against the
steps validate() really ran on, and unit-test the helper directly.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
Both sync GRPO loops called timeout.start_iterations() before the optional
val_at_start pass, so the first recorded iteration included the initial
validation (and refit). With the look-ahead now using max(iteration_times),
that outlier would set the estimate for the whole run and make the job exit
several steps early. Start timing right before the training loop instead. The
async GRPO loop and the other algorithms keep their ordering (follow-up).

Tests: test_grpo_timeout_iterations_start_after_initial_validation checks the
validate(step=0) -> start_iterations() -> mark_iteration() order for both sync
trainers.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
…alias

Reference the helper as grpo_mod._next_step_runs_validation in its unit test
instead of extending the explicit import list, which main has since grown at
the same position (an adjacent-line merge conflict otherwise). The module
alias is already imported for this purpose.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
@linj-glitch
linj-glitch force-pushed the linj/timeout-checker-slowest-step branch from 3845728 to 6c40f6c Compare October 13, 2026 16:36
@linj-glitch

Copy link
Copy Markdown
Contributor Author

/ok to test 6c40f6c

@linj-glitch linj-glitch added the CI:L0 Run doctests and unit tests label Oct 18, 2026
Integrate current upstream main to satisfy the required CI branch freshness gate.

Signed-off-by: Lin Jia <[email protected]>
@linj-glitch

Copy link
Copy Markdown
Contributor Author

/ok to test 9343a12

@terrykong terrykong added CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L0 Run doctests and unit tests labels Oct 29, 2026
potatowarriors added a commit to potatowarriors/RL that referenced this pull request Nov 25, 2026
…(decision 79) - SWE agent loop passes end to end with a scripted model

Gym source: upstream 7bfccecc1 (normalize response tools for replay, NVIDIA-NeMo#3190) as a patch file under gym_patches/,
applied to the submodule and the measurement checkout by tools/apply_gym_patches.sh (idempotent, 'check' mode).
Plugin: alpha_vllm_model also drops the tool-result 'name' and 'provider_specific_fields' before validation
(same targets as upstream NVIDIA-NeMo#4011/NVIDIA-NeMo#4483); its server venv gets nemo-gym from the package index, so a source
patch would not reach it.
Raising the Gym pin was rejected: every Gym containing the fixes pins vllm 0.29, and uv lock fails in a
scratch copy (torchvision 0.28 vs 0.26, then transformers >=5.10.4 vs <5.9; Ray 2.58 vs 2.56.1).
Verified: plugin tests 9 (2 negative controls), Gym test_openai_utils 180, R3 tallies unchanged, scripted-model
loop on the installed configuration 4/4 reward 1 (student_stub7).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JjdZctFTn2wkcheCmz3xKN
Signed-off-by: potatowarriors <[email protected]>

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

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants