Skip to content

fix: raise an actionable error when a prepare_for_* step is skipped - #3690

Open
VishnuR23 wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
VishnuR23:fix/prepare-step-error-messages
Open

VishnuR23 wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
VishnuR23:fix/prepare-step-error-messages

Conversation

@VishnuR23

Copy link
Copy Markdown
Contributor

What does this PR do ?

Turns the opaque CUDA illegal memory access you get from skipping a prepare_for_*() step into a RuntimeError that names both the API you called and the prepare step you missed.

Issues

Closes #1141

Usage

Policy workers offload model parameters to CPU between phases (finish_inference, offload_after_refit), and the matching prepare_for_* call onloads them again. Reaching a compute API without that call leaves parameters on CPU while the rest of the step assumes CUDA. As #1141 notes, that's easy to hit when writing a custom training loop, and the resulting failure points nowhere near the missing step.

Before — an illegal memory access from somewhere deep in the forward pass. After:

policy.offload_after_refit()
policy.get_logprobs(data)
RuntimeError: DTensorPolicyWorkerV2.get_logprobs() was called while the model
parameters are still on CPU. Call prepare_for_lp_inference() to onload the model
before get_logprobs(). Parameters are offloaded to CPU between phases (for example
by finish_inference() or offload_after_refit()), and without the onload this
typically fails later as a CUDA 'illegal memory access'.

What changed

AbstractPolicyWorker._assert_model_onloaded() checks the device of the model's first parameter and raises naming the API and the required prepare call. It's wired into the compute entry points of all three policy workers:

Worker Guarded API Required call
DTensor v1 / v2 train prepare_for_training
DTensor v1 / v2 get_logprobs, score, get_topk_logits prepare_for_lp_inference
Megatron train prepare_for_training
Megatron get_logprobs, get_topk_logits prepare_for_lp_inference

get_reference_policy_logprobs delegates to get_logprobs, so it's covered without a second check.

The check deliberately does not fire in three cases:

  • FSDP cpu_offload — parameters legitimately stay on CPU during compute, so callers pass params_may_be_offloaded=self.cpu_offload. Megatron only has optimizer_cpu_offload (params are always onloaded for compute), so it passes nothing.
  • A model with no parameters — nothing to check.
  • Any non-CPU device — only a CPU-resident model is treated as offloaded.

Megatron holds a list of virtual pipeline chunks rather than a single module, so first_parameter_device() accepts both shapes.

I also added docstrings to the PolicyInterface lifecycle methods (prepare_for_training, finish_training, prepare_for_lp_inference), which had none — that covers the "or document" half of the issue for someone reading the interface before writing their own loop.

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests? — tests/unit/models/policy/test_prepare_step_guards.py, 8 tests covering the raise path, the message contents, the module-list shape, and each of the three skip conditions. The real workers are Ray actors needing a GPU, so the guard is exercised through a minimal AbstractPolicyWorker subclass.
  • Did you run the unit tests and functional tests locally? — see below
  • Did you add or update any necessary documentation? — interface docstrings; no user-facing config or feature change

Additional Information

  • Local verification (macOS, CPU-only, so GPU paths could not be exercised):
    • pytest tests/unit/models/policy/test_prepare_step_guards.py → 8 passed
    • ruff check / ruff format --check → clean
    • pyrefly check → no new errors versus main
    • pytest tests/unit/models/policy → the failures there (test_split_api_wrappers.py, test_utils.py, test_policy_validation.py) reproduce identically on a clean main with Torch not compiled with CUDA enabled; none of those files import the modules touched here.
  • Scope note: value workers (nemo_rl/models/value/workers/) have the same prepare_for_training / prepare_for_inference lifecycle and could take the same guard. I left them out to keep this focused on the policy path from the issue — happy to extend if you'd prefer it in one change.

@VishnuR23
VishnuR23 requested review from a team as code owners August 18, 2026 00:52
@copy-pr-bot

copy-pr-bot Bot commented Aug 18, 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.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Aug 20, 2026
@VishnuR23
VishnuR23 force-pushed the fix/prepare-step-error-messages branch from 310ac17 to f4cc142 Compare August 23, 2026 05:28
@tildahh

tildahh commented Sep 10, 2026

Copy link
Copy Markdown

Nice improvement! The parameter-device check gives a much clearer error for offloaded models. One edge case I noticed from reading the lifecycle methods: prepare_for_lp_inference() brings parameters onto CUDA, so _assert_model_onloaded() passes, but that doesn't necessarily mean the worker is ready for training.

In Megatron, that call releases grad-buffer storage unless keep_train_buffers=True, and can also offload optimizer state when offload_optimizer_for_logprob is enabled. The DTensor workers can likewise offload optimizer state. A subsequent train(eval_mode=False) without prepare_for_training() would therefore pass this guard without the training state being restored.

Would it make sense to cover that transition with a training-readiness check and a regression test, while preserving supported CPU-offload configurations and keep_train_buffers=True behavior?

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-customer Waiting on the original author to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Sep 10, 2026
@VishnuR23
VishnuR23 force-pushed the fix/prepare-step-error-messages branch from f4cc142 to 9540bea Compare September 21, 2026 05:07
VishnuR23 added a commit to VishnuR23/RL that referenced this pull request Sep 21, 2026
Review feedback on NVIDIA-NeMo#3690: the device check alone is not enough.
prepare_for_lp_inference() moves parameters onto CUDA, so
_assert_model_onloaded() passes, but with keep_train_buffers=False it
also releases Megatron grad-buffer storage and moves optimizer state to
CPU when offload_optimizer_for_logprob is set. A train(eval_mode=False)
reached from there would clear the existing guard while the training
state is still parked, dropping accumulated gradients or failing on a
CPU-resident optimizer.

Record the parking in _training_state_parked at the points that actually
do it -- the grad-buffer release and the optimizer offload in each
worker's prepare_for_lp_inference -- and clear it in
prepare_for_training, which is what restores them. train() consults it
via _assert_training_state_restored() only when eval_mode is False,
since a forward-only eval pass needs neither buffers nor optimizer.

Setting the flag from the offloading branches rather than from
keep_train_buffers alone keeps two supported paths quiet: a
configuration that offloads nothing never sets it, and
keep_train_buffers=True leaves the training state alone, so an
already-open train step is unaffected.

Tests: the parked-state error and its message, the restored case, the
default, and a structural check that each worker which sets the flag
also clears it in prepare_for_training -- the asymmetry that would
otherwise wedge every later train step. Verified the structural check
fails against a worker with the clear removed.

Closes NVIDIA-NeMo#1141

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Vishnu Rajeev <[email protected]>
@VishnuR23

Copy link
Copy Markdown
Contributor Author

Thanks — you're right, and I confirmed it against the current code rather than taking it on faith. prepare_for_lp_inference() onloads parameters, so _assert_model_onloaded() sees a CUDA-resident model and passes, while with keep_train_buffers=False it has separately:

  • released grad-buffer storage (megatron_policy_worker.py, the not keep_train_buffers and not uses_mxfp8_shared_buffer branch), and
  • moved optimizer state to CPU when offload_optimizer_for_logprob is set — Megatron and both DTensor workers.

So train(eval_mode=False) from there clears the existing guard with the training state still parked. Pushed a fix.

What it does. A _training_state_parked flag on AbstractPolicyWorker, set at the points that actually park state — the grad-buffer release and the optimizer offload inside each prepare_for_lp_inference — and cleared in prepare_for_training, which is what restores them. train() checks it through _assert_training_state_restored() only when eval_mode=False, since a forward-only eval pass needs neither the buffers nor the optimizer.

On preserving the two cases you named. Setting the flag from the offloading branches rather than from keep_train_buffers alone is what keeps both quiet:

  • keep_train_buffers=True never reaches those branches, so an already-open train step is untouched. The single-controller chunked path (keep_train_buffers=step_open) also calls prepare_for_training before each chunk, so it clears the flag regardless.
  • A configuration that offloads nothing — DTensor with offload_optimizer_for_logprob=False, or Megatron on the MXFP8 shared-buffer path — never sets the flag, so CPU-offload setups and no-offload setups both stay silent. Had I keyed it off not keep_train_buffers, those would have started raising spuriously.

I also checked the call ordering in sft.py and single_controller.py: both already call prepare_for_training() before training, including after the train(eval_mode=True) validation loop, so no existing flow trips this.

Tests. The parked-state error and its message, the restored case, the default, plus a structural check that every worker setting the flag also clears it in prepare_for_training — that asymmetry is the dangerous one, since a stuck flag would wedge every later train step. I verified that check fails against a worker with the clear removed.

The branch is also rebased onto current main.

One gap I left deliberately, happy to close it if you'd prefer: offload_before_refit() parks optimizer state while leaving parameters on GPU, so in principle it has the same shape. In the refit flow it is followed by offload_after_refit(), which moves parameters to CPU and is therefore caught by the device check, so I did not want to widen the blast radius on a path I can't exercise on a GPU here. Say the word and I'll set the flag there too.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-customer Waiting on the original author to respond labels Sep 21, 2026
VishnuR23 and others added 2 commits September 30, 2026 21:02
Policy workers offload model parameters to CPU between phases
(finish_inference, offload_after_refit), and the matching prepare_for_*
call onloads them again. Reaching a compute API without that call leaves
parameters on CPU while the rest of the step assumes CUDA, which
surfaces as an opaque CUDA 'illegal memory access' that points nowhere
near the missing step. This is easy to hit when writing a custom
training loop.

Add AbstractPolicyWorker._assert_model_onloaded(), which checks the
device of the model's first parameter and raises a RuntimeError naming
both the API being entered and the prepare_for_* call that was missed.
Wire it into the compute entry points of the DTensor v1/v2 and Megatron
workers: train (prepare_for_training) and get_logprobs / score /
get_topk_logits (prepare_for_lp_inference).
get_reference_policy_logprobs delegates to get_logprobs, so it is
covered without a second check.

The check is skipped when FSDP cpu_offload is configured, since
parameters legitimately stay on CPU during compute in that mode, and
when the model has no parameters. Megatron holds a list of virtual
pipeline chunks rather than a single module, so both shapes are
accepted.

Also document the lifecycle contract on the PolicyInterface abstract
methods, which previously had no docstrings.

Closes NVIDIA-NeMo#1141

Signed-off-by: Vishnu Rajeev <[email protected]>
Review feedback on NVIDIA-NeMo#3690: the device check alone is not enough.
prepare_for_lp_inference() moves parameters onto CUDA, so
_assert_model_onloaded() passes, but with keep_train_buffers=False it
also releases Megatron grad-buffer storage and moves optimizer state to
CPU when offload_optimizer_for_logprob is set. A train(eval_mode=False)
reached from there would clear the existing guard while the training
state is still parked, dropping accumulated gradients or failing on a
CPU-resident optimizer.

Record the parking in _training_state_parked at the points that actually
do it -- the grad-buffer release and the optimizer offload in each
worker's prepare_for_lp_inference -- and clear it in
prepare_for_training, which is what restores them. train() consults it
via _assert_training_state_restored() only when eval_mode is False,
since a forward-only eval pass needs neither buffers nor optimizer.

Setting the flag from the offloading branches rather than from
keep_train_buffers alone keeps two supported paths quiet: a
configuration that offloads nothing never sets it, and
keep_train_buffers=True leaves the training state alone, so an
already-open train step is unaffected.

Tests: the parked-state error and its message, the restored case, the
default, and a structural check that each worker which sets the flag
also clears it in prepare_for_training -- the asymmetry that would
otherwise wedge every later train step. Verified the structural check
fails against a worker with the clear removed.

Rebased onto the removal of the DTensor v1 worker (NVIDIA-NeMo#4198), so the guards
now cover the v2 and Megatron workers only. The structural test used to
name the three worker modules; it now discovers them from the package
and skips any that park nothing, so deleting or adding a backend cannot
leave it pointing at a module that is gone.

Closes NVIDIA-NeMo#1141

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Vishnu Rajeev <[email protected]>
@VishnuR23
VishnuR23 force-pushed the fix/prepare-step-error-messages branch from 9540bea to 3229f55 Compare October 1, 2026 04:04
@VishnuR23

Copy link
Copy Markdown
Contributor Author

Rebased onto current main. Two things worth flagging for whoever picks this up:

The DTensor v1 worker is gone (#4198), so this PR no longer touches it — the guards now cover dtensor_policy_worker_v2 and megatron_policy_worker only. The rebase was a modify/delete against that file; I took the deletion.

The structural test no longer hardcodes the worker list. It named all three modules, which is exactly what went stale here, so it now discovers them from nemo_rl/models/policy/workers and skips any that park nothing. Adding or removing a backend can't leave it pointing at a module that no longer exists. Locally that resolves to v2 and Megatron passing, base_policy_worker skipped (it declares the class-level default rather than assigning it).

Re-validated on the rebased branch: 14 passed / 1 skipped in test_prepare_step_guards.py; ruff clean; pyrefly error set byte-identical to a clean main baseline. I also re-checked by AST that all nine guards still sit in the method each one names.

Still happy to extend the flag to offload_before_refit() if you'd like that gap closed in this PR rather than separately.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Oct 1, 2026

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

community-request waiting-on-maintainers Waiting on maintainers to respond

Projects

None yet

Development

Successfully merging this pull request may close these issues.

More helpful error message if prepare_for_*() not called

3 participants