Repository navigation
Conversation
|
Bugbot is not enabled for your account, so this pull request was not reviewed. Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs. |
a129770 to
46c5f72
Compare
saumishr
left a comment
There was a problem hiding this comment.
Review: sizing the NemoGym actor's max_concurrency
The core change is right and unusually well evidenced. I independently confirmed the load-bearing premises against Ray at the pinned version (uv.lock resolves 2.56.1):
DEFAULT_MAX_CONCURRENCY_ASYNC = 1000andDEFAULT_MAX_CONCURRENCY_THREADED = 1, applied only whenmax_concurrencyis unset (actor.py#L1806-L1813). Unchanged from 2.50.0 through 2.56.1.NemoGymreally is an async actor —has_async_methodscountsisasyncgenfunction, soasync def run_rolloutsalone is enough — so the 1000 default genuinely applied.- The admission cap is real and reproduces: with
max_concurrency=3, nine 1.2 s streaming calls ran in three waves and the actor never exceeded 3 concurrent executions. - One in-flight prompt really is one
run_rolloutscall holding its slot until the group completes; the slot is not released between yields, because Ray parks the whole fiber until the generator is exhausted.
Two things to fix before merge, then a set of doc/test/hardening items. Neither bug is a live break: no YAML anywhere under examples/ sets env.nemo_gym.max_concurrency, so both are traps for the next user rather than something failing today.
Blocking-ish
- The v1 call site passes Ray's default as a fan-in (
grpo.py:720). Two consequences: the new comment's "byte-for-byte as it was configured before" is false (the value is 1008, not 1000), and becauserollout_fan_indoubles as a hard floor, a v1 user setting a sanemax_concurrency: 64now gets a lateValueErrortelling them to lowerasync_rl.max_inflight_prompts— a knob the v1 config does not have. Three of the five reviewers found this independently, and one reproduced it as a failing test. configured == rollout_fan_inis accepted (nemo_gym.py:1061), which leaves zero slots for the actor's own control plane while the derived default deliberately reserves 8 for exactly that. Reproduced on a live actor: atmax_concurrency == fan_inthe actor'shealth_checktimes out under the sameasyncio.wait_forshape the watchdog uses, whilefan_in + 8answers in 0.00 s. The error message one line down actively steers users into the starved value, and a new test pins it as intended.
Non-blocking: three docstring/error-message corrections about where Ray actually queues the surplus and what a large cap costs (it's inside the actor on a fiber semaphore, not at the raylet, and an async slot costs no threads); the untested spinup_nemo_gym_actor wiring plus the unreached validator call site, both mutation-checked; a missing should_use_nemo_gym gate; and max_inflight_prompts / max_buffered_rollouts accepting 0.
One note on the description rather than the code: the "seventeen warnings" evidence probably reflects duplicated log surfacing rather than queue depth. Ray doubles next_queueing_warn_threshold_ after each crossing and keeps one counter per process, so a single submitter at ~5120 in flight logs this exactly once. That doesn't weaken the sizing argument — the pump is a single SingleControllerActor, so there is one submitter, and the argument rests on the code path plus the 896-1152 cliff.
Details inline. Findings that didn't survive scrutiny were dropped rather than posted.
| # that default keeps the v1 actor byte-for-byte as it was | ||
| # configured before max_concurrency became explicit; the fan-in | ||
| # that needed sizing is the SingleController one. | ||
| rollout_fan_in=RAY_DEFAULT_ASYNC_ACTOR_MAX_CONCURRENCY, |
There was a problem hiding this comment.
[BUG] This call site passes Ray's default as a fan-in, which has two separate consequences.
(a) The comment doesn't describe what the code does. resolve_nemo_gym_max_concurrency(None, rollout_fan_in=1000) returns 1000 + NEMO_GYM_CONTROL_CONCURRENCY_HEADROOM = 1008 (nemo_gym.py:1115-1117), not 1000, so "keeps the v1 actor byte-for-byte as it was configured before" isn't accurate. Behaviourally harmless — 1008 ≥ Ray's 1000, so v1 is never narrowed — but someone auditing v1 for a regression will be looking for 1000.
(b) rollout_fan_in is also a hard floor, so an explicit v1 value is now rejected. validate_nemo_gym_actor_concurrency treats it as a minimum (nemo_gym.py:1061), so a v1 gym user who sets env.nemo_gym.max_concurrency: 64 — legitimate on a path whose true fan-in this very comment calls "single digits" — gets ValueError: env.nemo_gym.max_concurrency (64) is below the rollout fan-in (1000)..., advising them to "lower async_rl.max_inflight_prompts". That key exists only on AsyncRLConfig (single_controller_utils/config.py:196); v1's async block is grpo.async_grpo: AsyncGRPOConfig (grpo.py:280). It also raises from inside setup() — grpo.py:1243 on Megatron, or out of f.result() at grpo.py:1358-1360 on vLLM, i.e. after the engine has already loaded.
No shipped YAML sets this key, so (b) is a latent trap rather than a live break.
Related, and the flip side of (b): validate_nemo_gym_actor_concurrency's docstring (nemo_gym.py:1043-1045) says to "call this from config validation so an explicit value that is too small fails before any cluster is built", but validate_gym_actor_concurrency is wired only into validate_single_controller_config (config.py:356). On v1 that promise doesn't hold, and the late raise above is the only enforcement — worth either wiring the validator into v1's config validation or scoping the docstring claim to SC.
Suggested fix: separate "the default to derive when unset" from "the floor an explicit value must clear". The cheapest correct version keeps the option explicit, fixes the comment, and makes the validator's remediation text path-agnostic (name the caller's rollout fan-in rather than an SC-only config key). If you'd rather have v1 not participate in the floor at all, rollout_fan_in: Optional[int] = None works — but it has to return configured when the user set one and omit max_concurrency only when it is None, otherwise an explicit v1 value gets silently dropped.
At minimum, the comment:
| rollout_fan_in=RAY_DEFAULT_ASYNC_ACTOR_MAX_CONCURRENCY, | |
| # This path fans in per prompt *batch* (one run_rollouts call per | |
| # in-flight AsyncTrajectoryCollector batch worker, or one per step | |
| # on the synchronous path), not per prompt, so its true fan-in is | |
| # single digits and has never approached Ray's default. Passing | |
| # that default keeps the v1 actor at least as permissive as Ray | |
| # would have made it (1000 + headroom); the fan-in that needed | |
| # sizing is the SingleController one. | |
| rollout_fan_in=RAY_DEFAULT_ASYNC_ACTOR_MAX_CONCURRENCY, |
There was a problem hiding this comment.
fixed in 7df2524
Took the second option you offered rather than the first: rollout_fan_in is now Optional[int] and the v1 call site declares None, which omits max_concurrency from .options() entirely -- so the v1 actor really is as it was before this option existed, not 1008 -- and holds an explicit env.nemo_gym.max_concurrency to no floor. An explicit value is still returned verbatim; only None omits the option, so a v1 value cannot be silently dropped. The validator's docstring now scopes its config-load promise to paths that actually declare a fan-in, and the remediation text names the caller's rollout fan-in rather than an SC-only config key.
| raise ValueError(f"rollout_fan_in must be positive, got {rollout_fan_in}") | ||
| if configured_max_concurrency is None: | ||
| return | ||
| if configured_max_concurrency < rollout_fan_in: |
There was a problem hiding this comment.
[BUG] < accepts configured == rollout_fan_in, which leaves the actor zero slots for anything that isn't a rollout — while the derived default deliberately adds NEMO_GYM_CONTROL_CONCURRENCY_HEADROOM for exactly that reason ("so a saturated rollout queue cannot lock the actor's control plane out", nemo_gym.py:78-80). The message just below then steers users into the starved value: "Raise env.nemo_gym.max_concurrency to at least {rollout_fan_in}" — and test_explicit_value_equal_to_fan_in_is_allowed pins it as intended.
Reproduced on Ray 2.55, four streaming tasks saturating the actor and then the actor's own health_check under asyncio.wait_for (the same shape the watchdog uses):
max_concurrency == fan_in : health_check TIMED OUT (3s)
fan_in + HEADROOM (8) : health_check OK in 0.00s
A control run showed the blocked call returning at the exact moment a slot frees (t=6.01s against a 6s occupant), so this is admission blocking, not object-store latency.
Concretely, with async_rl.max_inflight_prompts: 64 and env.nemo_gym.max_concurrency: 64: the pump saturates at exactly 64 (asyncio.Semaphore(max_inflight_prompts), single_controller.py:362, released only in the finally at :384-386), so once rollouts routinely outlast a tick, the watchdog's probe (single_controller.py:781, :824-838) can't be admitted within its interval_s bound and every tick reports WARNING: environment health -- environment 'nemo_gym' did not answer its health check within 30.0s under the default stall_action: warn, or raises RuntimeError under abort (single_controller.py:784-788). The same starvation blocks shutdown(), the other method the headroom comment names.
Fix: require an explicit value to clear the same bar the derived default sets, and flip the test. This also corrects the mechanism clause (the surplus waits inside the actor process on Ray's fiber rate limiter, not at the raylet — see the separate comment on the docstring):
| if configured_max_concurrency < rollout_fan_in: | |
| if configured_max_concurrency is None: | |
| return | |
| required = rollout_fan_in + NEMO_GYM_CONTROL_CONCURRENCY_HEADROOM | |
| if configured_max_concurrency < required: | |
| raise ValueError( | |
| f"env.nemo_gym.max_concurrency ({configured_max_concurrency}) is below " | |
| f"the rollout fan-in ({rollout_fan_in}) plus the control-plane " | |
| f"headroom ({NEMO_GYM_CONTROL_CONCURRENCY_HEADROOM}) the actor needs. " | |
| f"Ray admits only max_concurrency tasks into an async actor at a time " | |
| f"and parks the rest inside the actor process (they show up as " | |
| f"PENDING_ACTOR_TASK_ORDERING_OR_CONCURRENCY), where no NeMo-RL " | |
| f"backpressure valve can see them, so the surplus rollouts would " | |
| f"never start -- and with no headroom left the watchdog's " | |
| f"health_check is not admitted either and reads as an unhealthy " | |
| f"environment. Raise env.nemo_gym.max_concurrency to at least " | |
| f"{required}, lower the caller's rollout fan-in, or unset " | |
| f"env.nemo_gym.max_concurrency to have it derived from the " | |
| f"in-flight cap." | |
| ) |
| groups and no training steps at all. | ||
|
|
||
| Every in-flight prompt is exactly one ``run_rollouts`` streaming call that | ||
| holds its concurrency slot until that prompt's whole group is done, so the |
There was a problem hiding this comment.
[RISK] Low severity, and worth stating in the docstring rather than fixing here: this invariant has an escape hatch. An abandoned run_rollouts keeps its slot past the prompt's lifetime, because Ray runs a generator task to completion regardless of the caller — ObjectRefGenerator.__del__ only calls async_delete_object_ref_stream (ray/_private/object_ref_generator.py:289-295), never a cancel — and _stream_rows (rollout_manager.py:835-837) never calls ray.cancel. Verified on a max_concurrency=1 actor: breaking out of the async for, then del gen and gc.collect(), left a following ping blocked for the generator's full remaining ~9s, while ray.cancel(gen) in the same position freed the slot immediately.
Being precise about severity, because two triggers don't fire with shipped defaults: rollout_timeout_s defaults to None (single_controller_utils/config.py:70, and the exemplar sets it to null), so there's no deadline; and _abort_stale_inflight is short-circuited on the gym path (single_controller.py:988-992, TODO(#2625)). What remains by default are the driver-side protocol guards in _stream_rows (invalid / undispatched / duplicate rowidx, rollout_manager.py:841-852), which exit the loop with the actor task still running and are retried as DATA up to max_data_attempts_per_prompt=2, plus cancellation during teardown. Worst case is bounded at roughly max_infra_attempts(5) + max_data_attempts(2) - 1 streams per in-flight prompt, so it can exceed fan_in + 8 — but there's no stall here today, and failures raised inside the actor (GymTransportError, RolloutDataFailure, the NaN RuntimeError) all end the generator and leak nothing.
The reason it's worth a note: pre-PR, Ray's 1000 default absorbed this at the default max_inflight_prompts=32. fan_in + HEADROOM doesn't, so a latent leak becomes newly consequential — and if #2625 lands and re-enables the stale abort for gym, it fires on every weight sync.
Optional fix, with an in-repo precedent: vllm_generation.py:836-838 already does except (asyncio.CancelledError, GeneratorExit): ray.cancel(...); raise for its worker stream. Mirroring that in _stream_rows would make this docstring's invariant true. Worth noting in the comment that it frees the Ray slot but not the aiohttp work rch.run_examples has already started inside the actor.
There was a problem hiding this comment.
fixed in 7df2524
Took the docstring route you suggested: resolve_nemo_gym_max_concurrency now states that the headroom is a floor on non-rollout capacity rather than a hard bound, because an abandoned run_rollouts generator keeps its slot until the task ends. Left the _stream_rows ray.cancel mirror out -- it is a behaviour change in a file this PR does not touch, and belongs with the #2625 work that would re-enable the stale abort for gym.
| multimodal_flags[_flag] = bool(_value) | ||
| # A Ray actor option, not a Gym setting, so it must not reach Gym's global | ||
| # config parser. | ||
| max_concurrency = resolve_nemo_gym_max_concurrency( |
There was a problem hiding this comment.
[RISK] Low severity: the new knob is inert on the other two NemoGym spinup paths. distillation.py:529-567 and examples/nemo_gym/prefetch_venvs.py:71-106 build NemoGymConfig and call NemoGym.options(...) inline instead of going through this helper, popping only invalid_tool_call_patterns and thinking_tags. So a user's env.nemo_gym.max_concurrency is silently ignored there (the actor gets Ray's 1000) and the key rides into initial_global_config_dict.
The stray key is harmless, so the comment above ("it must not reach Gym's global config parser") is stronger than the consequence: Gym filters unknown top-level keys by value type and a scalar can't be read as a server config. num_gpu_nodes already demonstrates this — it's read with .get() and never popped (nemo_gym.py:1205), and production configs set it (examples/nemo_gym/nemotron-3-super/stage1_rlvr.yaml:298), so a NeMo-RL-only key reaches Gym's parser on every gym run today without incident.
Which means the actual complaint is the inert knob, not the leak — so a defensive pop in NemoGym._spinup would address the wrong half. The clean fix is routing distillation.py through spinup_nemo_gym_actor; if that's out of scope for this PR, a line in this function's docstring saying the knob only applies to the SC and v1 paths would keep the next reader out of the trap. Those paths already ignore pad_dynamic_image_shapes and tokenizer_config as well, so this is pre-existing duplication rather than something the PR breaks.
There was a problem hiding this comment.
fixed in 7df2524
Took the docstring option: spinup_nemo_gym_actor now states that only the SC and v1 paths route through it, and that max_concurrency -- along with the pre-existing pad_dynamic_image_shapes and tokenizer_config -- is inert on the distillation and prefetch_venvs paths that build the actor inline. Routing distillation.py through the helper is the real fix, but that is pre-existing duplication rather than something this PR introduces.
| # the NemoGym actor's Ray max_concurrency, since each in-flight prompt is | ||
| # one run_rollouts call on that actor — see | ||
| # nemo_rl.environments.nemo_gym.resolve_nemo_gym_max_concurrency. | ||
| max_inflight_prompts: int = 32 |
There was a problem hiding this comment.
[SUGGESTION] Low severity and not PR-introduced (the diff only touches this field's comment), but the PR makes it visible: max_inflight_prompts accepts 0, and the new rollout_fan_in <= 0 check (nemo_gym.py:1057-1058) is now the first and only thing anywhere that rejects it — and only on gym runs. I looked for an earlier guard and there is none: AsyncRLConfig's two model_validators don't read this field, MasterConfig has no validators, validate_single_controller_config never reads it, and there's no assert repo-wide.
So 0 parses, and then asyncio.Semaphore(0) (single_controller.py:362) is awaited at :439 and the pump never dispatches — a silent hang on native SC runs. On gym runs it surfaces as ValueError: rollout_fan_in must be positive, got 0, naming a keyword argument that maps to no config key.
max_buffered_rollouts two lines down has the identical failure (Semaphore(0) at single_controller.py:204-206, acquired at :437).
Fix: bound both in the schema, which matches the idiom of the neighbouring RolloutFailureConfig / WatchdogConfig in this same file (PositiveInt, PositiveFloat, NonNegativeInt) — the three ints in AsyncRLConfig are currently all unbounded, so this is about matching those neighbours rather than an inconsistency within this class. Safe to tighten: all five shipped SC configs set max_inflight_prompts: ${grpo.num_prompts_per_step}.
| max_inflight_prompts: int = 32 | |
| max_inflight_prompts: PositiveInt = 32 |
| """Return the Ray ``max_concurrency`` to create the NemoGym actor with. | ||
|
|
||
| Ray admits at most ``max_concurrency`` tasks into an async actor at a time | ||
| and leaves the rest queued at the submitting raylet, which logs |
There was a problem hiding this comment.
[DOC] The surplus is not queued at the raylet, and this wording is repeated in a ValueError an operator reads while debugging a stall (:1066) and in the spinup comment (:1220, "from the raylet's side"). Someone told "raylet" will go read raylet logs and ray status and find nothing, when the evidence is N fibers parked on a semaphore inside one actor process.
What Ray actually does at the pinned 2.56.1:
- The submitter drains unconditionally —
while (true) { PopNextTaskToSend(); PushActorTask(...); }(actor_task_submitter.cc#L572-L579). There is nomax_concurrency-derived window on the submitter; the only submitter cap ismax_pending_calls, which defaults to-1and is inert when non-positive. PushActorTaskis a direct gRPC to the actor's core worker, so the raylet is not on the actor-task path at all.- The cap is applied inside the actor:
EnqueueFiberwraps the callback asrate_limiter_.Acquire(); callback(); rate_limiter_.Release();, whererate_limiter_is aFiberRateLimiter(max_concurrency)semaphore (fiber.h#L155-L162). - Ray's own "pending submission" text is itself misleading — its counter is
inflight_task_callbacks_.size(), i.e. RPCs already sent (actor_task_submitter.cc#L598) — and it's emitted by the submitting worker viaPushError, not by the actor or the raylet (core_worker_process.cc#L507-L514).
Worth naming the observable state while you're in here: Ray records these as PENDING_ACTOR_TASK_ORDERING_OR_CONCURRENCY before enqueueing (common.proto#L933, "waiting due to ordering or concurrency constraints"), and TaskState.state is filterable, so ray list tasks -f state=PENDING_ACTOR_TASK_ORDERING_OR_CONCURRENCY gives the next operator a diagnostic instead of a dead end. (Task-status events are subject to worker-side buffer caps, so at several thousand tasks treat it as a signal, not an exhaustive count.)
To be clear about what is right here: the existing clause "where no NeMo-RL backpressure valve can see them" is correctly scoped and should stay — the surplus genuinely is invisible to this repo's own valves.
| and leaves the rest queued at the submitting raylet, which logs | |
| Ray admits at most ``max_concurrency`` tasks into an async actor at a time | |
| and parks the rest inside the actor process, as fibers blocked on its | |
| concurrency semaphore; the submitting worker logs | |
| ``>N tasks pending submission to actor NemoGym`` and nothing else, and Ray | |
| records them as PENDING_ACTOR_TASK_ORDERING_OR_CONCURRENCY. Its | |
| default for async actors is ``RAY_DEFAULT_ASYNC_ACTOR_MAX_CONCURRENCY``, and | |
| a run that keeps more rollouts in flight than that produces no rollout | |
| groups and no training steps at all. |
| actor has to admit ``rollout_fan_in`` of them. The derived default is that | ||
| plus ``NEMO_GYM_CONTROL_CONCURRENCY_HEADROOM`` for the actor's non-rollout | ||
| methods, and deliberately nothing more: the caller's own in-flight cap is | ||
| the backpressure valve, and a much larger (or unbounded) value would only |
There was a problem hiding this comment.
[DOC] Low severity, but this is the paragraph the next person sizing this knob will reason from, and both halves of the justification are off.
"unbounded" isn't expressible. max_concurrency is _counting_option("max_concurrency", False), so -1 is rejected: ValueError: The keyword 'max_concurrency' only accepts None, 0 or a positive integer (measured). 0 passes validation and then produces an actor that never executes a task, since FiberRateLimiter(0).Acquire() waits on num_ > 0 forever.
A slot costs no memory on an async actor. FiberState spawns exactly one fiber_runner_thread regardless of the value (fiber.h#L104-L153) — measured OS thread count in the actor process was flat at 52 for max_concurrency of 1, 1000 and 5128. The per-slot cost people expect is the threaded path, where BoundedExecutor really does threads_.reserve(max_concurrency). And the 256 KiB fiber stack (kStackSize) is paid per enqueued task whether or not it is admitted, because EnqueueFiber constructs the fiber before Acquire() blocks — so raising the cap adds no stacks.
The defensible version of the argument is about live application state and event-loop contention, not per-slot allocation. Note a larger cap isn't free either — more admitted rollouts means more live rollout state — so it's worth saying that rather than implying the cap is the memory knob:
| the backpressure valve, and a much larger (or unbounded) value would only | |
| methods, and deliberately nothing more: the caller's own in-flight cap is | |
| the backpressure valve, and a much larger value would only admit more | |
| rollouts into the actor at once -- more live rollout state to hold and more | |
| coroutines contending for its single event loop -- without making the | |
| surplus any more visible to NeMo-RL than before. |
|
|
||
| message = str(excinfo.value) | ||
| assert "env.nemo_gym.max_concurrency" in message | ||
| assert "async_rl.max_inflight_prompts" in message |
There was a problem hiding this comment.
[TEST] The pure functions are well covered, but the two lines whose loss reproduces the original 68-node stall are not tested at either layer.
1. spinup_nemo_gym_actor itself never runs. All six references under tests/ are in test_single_controller_setup.py (lines 428, 509, 535, 561, 606, 629) and every one patches the function out, so neither nemo_gym_dict.pop("max_concurrency", None) nor nemo_gym_opts = {"max_concurrency": max_concurrency} is exercised. I confirmed the gap is load-bearing by mutation: replacing that dict with {} leaves options kwargs as just ['runtime_env'], and the suggested assertion fails — i.e. the test catches a reintroduced stall, and today's suite would not.
2. validate_gym_actor_concurrency is never reached through validate_single_controller_config. All five tests in the new TestValidateGymActorConcurrency call the helper directly, so deleting the single call site at config.py:356 keeps the suite green while the guard silently reverts to the stall it replaces. Mutation-checked the same way: with the call removed the entry point no longer raises. The sibling test_resiliency_config.py:220-276 already routes every case through the entry point, including its own "env absent" case.
Both tests below pass as written (verified in this worktree; NemoGym.options() is called with kwargs, so .call_args.kwargs is the right target, and all patch targets exist as module attributes):
def _spinup_with_stubbed_ray(nemo_gym_config, *, rollout_fan_in):
"""Run spinup_nemo_gym_actor with every out-of-process dependency stubbed."""
fake_nemo_gym = MagicMock(name="NemoGym")
with (
patch.object(nemo_gym_mod, "NemoGym", fake_nemo_gym),
patch.object(nemo_gym_mod, "ray", MagicMock(name="ray")),
patch.object(
nemo_gym_mod, "get_actor_python_env", return_value="/usr/bin/python"
),
patch.object(nemo_gym_mod, "get_nemo_gym_uv_cache_dir", return_value=None),
patch.object(nemo_gym_mod, "get_nemo_gym_venv_dir", return_value=None),
):
spinup_nemo_gym_actor(
env_configs={"nemo_gym": nemo_gym_config},
base_urls=["http://127.0.0.1:8000"],
model_name="test-model",
enable_router_replay=False,
routed_experts_dtype="int16",
use_fastokens=False,
rollout_fan_in=rollout_fan_in,
)
options_kwargs = fake_nemo_gym.options.call_args.kwargs
(built_config,), _ = fake_nemo_gym.options.return_value.remote.call_args
return options_kwargs, built_config
class TestSpinupNemoGymActorConcurrency:
"""max_concurrency is a Ray option, so it must reach .options() and only there."""
def test_derived_value_reaches_ray_options(self):
options_kwargs, _ = _spinup_with_stubbed_ray({}, rollout_fan_in=5120)
assert options_kwargs["max_concurrency"] == (
5120 + NEMO_GYM_CONTROL_CONCURRENCY_HEADROOM
)
def test_explicit_value_is_moved_out_of_the_gym_global_config(self):
options_kwargs, built_config = _spinup_with_stubbed_ray(
{"max_concurrency": 6144, "some_gym_setting": 1}, rollout_fan_in=5120
)
assert options_kwargs["max_concurrency"] == 6144
assert "max_concurrency" not in built_config["initial_global_config_dict"]
assert built_config["initial_global_config_dict"]["some_gym_setting"] == 1Needs from unittest.mock import MagicMock, patch and spinup_nemo_gym_actor on the existing import.
For the entry-point half, in tests/unit/single_controller/test_config_validation.py — note it cannot reuse that file's _master_config, which passes only env and async_rl and so dies on the first cross-check inside validate_single_controller_config; this is test_resiliency_config.py's fuller shape:
def _full_master_config(*, env: dict, max_inflight_prompts: int) -> MasterConfig:
"""Populate everything validate_single_controller_config reads end to end."""
return MasterConfig.model_construct(
async_rl=AsyncRLConfig(
min_groups_for_streaming_train=2,
max_inflight_prompts=max_inflight_prompts,
max_buffered_rollouts=max_inflight_prompts * 2,
),
grpo=GRPOConfig.model_construct(
num_prompts_per_step=2,
num_generations_per_prompt=4,
skip_reference_policy_logprobs_calculation=False,
),
policy={"train_global_batch_size": 8},
loss_fn=SimpleNamespace(reference_policy_kl_penalty=0),
env=env,
checkpointing={"enabled": False, "metric_name": None},
)
class TestGymActorConcurrencyIsReachedFromTheEntryPoint:
"""Only load-time protection if validate_single_controller_config runs it."""
def test_entry_point_rejects_an_actor_that_cannot_admit_the_fan_in(self) -> None:
master_config = _full_master_config(
env={"should_use_nemo_gym": True, "nemo_gym": {"max_concurrency": 1}},
max_inflight_prompts=2,
)
with pytest.raises(ValueError, match="below the rollout fan-in"):
validate_single_controller_config(master_config)| Args: | ||
| master_config: The SingleController master config being validated. | ||
| """ | ||
| env_config = getattr(master_config, "env", None) |
There was a problem hiding this comment.
[SUGGESTION] Low severity: this skips the should_use_nemo_gym gate that its nearest analog in this same function relies on. The rollout_failure check 95 lines below reads env_config.get("should_use_nemo_gym") precisely to decide which half of a config block is inert, and its comment says why — "This check only reads it to decide which half of the block is inert, so skip rather than fail a construction over it" (config.py:404-408).
Without that gate, a native SC run that carries an inherited or leftover env.nemo_gym block with an explicit max_concurrency below max_inflight_prompts is rejected over a knob that is a no-op for it, since nothing on the native path ever creates the Gym actor.
| env_config = getattr(master_config, "env", None) | |
| env_config = getattr(master_config, "env", None) | |
| if env_config is None: | |
| return | |
| # Mirrors the rollout_failure check below: should_use_nemo_gym decides which | |
| # settings are inert, and an inert knob should not fail a run. | |
| if not env_config.get("should_use_nemo_gym"): | |
| return | |
| nemo_gym_config = env_config.get("nemo_gym") | |
| if nemo_gym_config is None: | |
| return |
…an-in A 68-node SingleController run produced zero training steps and zero rollout groups. The rollout pump dispatched 5120 concurrent generate_and_push calls, each of which is exactly one run_rollouts streaming call on the single NemoGym actor, and NemoGym.options() never passed max_concurrency -- so Ray's async-actor default of 1000 applied and the surplus sat queued at the submitting raylet, which logged ">5000 tasks pending submission to actor NemoGym" seventeen times and nothing else. A sweep put the cliff between 896 and 1152 in flight: a round number that says admission cap, not organic event-loop saturation. Pass max_concurrency explicitly, resolved in one place from the caller's own fan-in. Absent env.nemo_gym.max_concurrency the default is the fan-in plus a small control-plane headroom, and deliberately no more: the caller's in-flight cap is the backpressure valve already, and an unbounded value would just relocate the same queue from the raylet into the actor's event loop, where it costs actor memory and is no more visible than before. An explicit env.nemo_gym.max_concurrency below the in-flight depth is now a ValueError at config load (validate_gym_actor_concurrency, alongside validate_sampler_buffer_capacity) rather than a stall discovered hours in, and the resolved value is printed at spinup so the two numbers that decide this are in the log. The v1 async-GRPO path fans in per prompt batch rather than per prompt -- single digits, never near Ray's default -- so it passes that default and its actor is configured exactly as before. Signed-off-by: Saurabh Mishra <[email protected]>
Addresses the review findings on NVIDIA-NeMo#3672. An explicit env.nemo_gym.max_concurrency equal to the rollout fan-in was accepted, which leaves the actor zero slots for anything that is not a rollout while the derived default deliberately reserves eight for exactly that. On a live actor, health_check timed out under the watchdog's own asyncio.wait_for shape at max_concurrency == fan_in and answered in 0.00s at fan_in + 8. An explicit value now has to clear the same bar the derived default sets, and the error names that bar instead of steering the reader into the starved value. The v1 GRPO path passed Ray's own default as its fan-in. That made resolve_nemo_gym_max_concurrency return 1008 rather than leaving the v1 actor as it was, and it turned 1000 into a floor no v1 user could clear with a sensible value: env.nemo_gym.max_concurrency: 64 was rejected, advising them to lower async_rl.max_inflight_prompts -- a key that exists only on AsyncRLConfig, not in v1's config. rollout_fan_in is now Optional and v1 declares None, which leaves max_concurrency off the actor entirely (byte-for-byte as before this option existed) and holds an explicit value to no floor it could not have known about. validate_gym_actor_concurrency now skips when should_use_nemo_gym is falsy, mirroring the rollout_failure check beside it, so a native run carrying a leftover env.nemo_gym block is not failed over a knob that is inert for it. max_inflight_prompts and max_buffered_rollouts become PositiveInt. Both back an asyncio.Semaphore in the rollout pump, where 0 is not a small value but a pump that never dispatches -- previously reachable, and surfacing on gym runs only, as a rollout_fan_in error naming no config key. Docstring and message corrections, none of them behavioural: Ray parks the surplus inside the actor process as fibers on its concurrency semaphore rather than queueing it at the submitting raylet, and records it as PENDING_ACTOR_TASK_ORDERING_OR_CONCURRENCY, which is a diagnostic an operator can actually query; "unbounded" is not expressible for this option and an async slot costs no thread, so a larger cap costs live rollout state and event-loop contention rather than memory per slot; the headroom is a floor on non-rollout capacity rather than a hard bound, because an abandoned run_rollouts generator keeps its slot until the task ends; and the knob is inert on the distillation and prefetch_venvs spinup paths, which build the actor inline. Tests: spinup_nemo_gym_actor is now exercised with Ray stubbed, covering that max_concurrency reaches .options(), stays out of Gym's global config, and is omitted on the v1 shape; and validate_gym_actor_concurrency is reached through validate_single_controller_config rather than only called directly, so deleting its call site fails the suite. Signed-off-by: Saurabh Mishra <[email protected]>
46c5f72 to
7df2524
Compare
|
/ok to test 7df2524 |
The two spinup_nemo_gym_actor.assert_called_once_with sites in test_grpo.py enumerate every kwarg, so adding rollout_fan_in to the v1 call site made them fail with a one-kwarg diff -- L0_Unit_Tests_Algorithms caught it on the dynamo case (test_setup_initializes_noncolocated_dynamo_with_nemo_gym); the trtllm case has the identical assertion and is fixed here too. Assertion-only change: the v1 path still declares rollout_fan_in=None, which leaves max_concurrency off the actor exactly as before this option existed. Signed-off-by: Saurabh Mishra <[email protected]>
…an-in The actor was created with no max_concurrency, so Ray's async-actor default of 1000 applied while async_rl.max_inflight_prompts drives 1024. The excess never reached the actor: it queued at the raylet, and the requests that were in flight sat unanswered until their peers dropped the connection. Jobs 6440386, 6440389 and 6440393 each burned ~40 minutes and completed zero steps under ServerDisconnectedError storms of 1800-2600, all emitted by the single NemoGym actor against both the policy vLLM and the Gym resources servers. Derive the actor's concurrency from the fan-in plus a small control-plane headroom so _spinup and shutdown cannot be locked out by a saturated rollout queue. Squashed from 40cfa10 and 7df2524 on sc-cpu-rdma (PR NVIDIA-NeMo#3672), which do not yet exist upstream. Signed-off-by: Saurabh Mishra <[email protected]>
build_nemo_gym_actors created its actors with no max_concurrency, so Ray's
async-actor default of 1000 applied to each. Past that limit the surplus does
not raise and does not queue anywhere this repo can see it: it parks inside the
actor as fibers on its concurrency semaphore, the submitter logs "tasks pending
submission to actor NemoGym", and the run stops producing steps. A silent hang,
on whatever allocation it was holding.
That ceiling is per ACTOR, not per job, so the shard plan decides where it
binds. The judge shard carries jailbreak_detection alone (1.36% of the blend)
on one un-replicated actor, while the verifier's 32 replicas take the rest
round-robin, which puts the first breach on a verifier replica:
judge (1 actor) verifier (each of 32)
8K GBS 118 268
16K GBS 237 536
32K GBS 473 1,073 <- over
Derive each actor's concurrency from the caller's in-flight cap plus a small
control-plane headroom, so _spinup and shutdown cannot be locked out by a
saturated rollout queue.
The fan-in is applied WHOLE to every replica rather than divided by the replica
count. Routing is by agent name and does not split evenly -- the table above is
the whole point -- so an even division would under-provision whichever shard
runs hot. max_concurrency only bounds a semaphore, and the caller's in-flight
cap still bounds the true total across all actors, so per-actor
over-provisioning costs nothing it did not already cost.
Paths that declare no fan-in keep the option off the actor entirely and stay
byte-for-byte as they were, which covers the v1 GRPO path.
Adapted from ad1ce8f (saumishr/RL, squashed
from PR NVIDIA-NeMo#3672), which wires this through spinup_nemo_gym_actor. That
function is not on the sharded SingleController path -- setup.py reaches the
actors through build_nemo_gym_actors -- so the helpers and constants are taken
from it unchanged and the wiring is extended to both creation sites there.
Signed-off-by: Saurav Muralidharan <[email protected]>
build_nemo_gym_actors created its actors with no max_concurrency, so Ray's
async-actor default of 1000 applied to each. Past that limit the surplus does
not raise and does not queue anywhere this repo can see it: it parks inside the
actor as fibers on its concurrency semaphore, the submitter logs "tasks pending
submission to actor NemoGym", and the run stops producing steps. A silent hang,
on whatever allocation it was holding.
That ceiling is per ACTOR, not per job, so the shard plan decides where it
binds. The judge shard carries jailbreak_detection alone (1.36% of the blend)
on one un-replicated actor, while the verifier's 32 replicas take the rest
round-robin, which puts the first breach on a verifier replica:
judge (1 actor) verifier (each of 32)
8K GBS 118 268
16K GBS 237 536
32K GBS 473 1,073 <- over
Derive each actor's concurrency from the caller's in-flight cap plus a small
control-plane headroom, so _spinup and shutdown cannot be locked out by a
saturated rollout queue.
The fan-in is applied WHOLE to every replica rather than divided by the replica
count. Routing is by agent name and does not split evenly -- the table above is
the whole point -- so an even division would under-provision whichever shard
runs hot. max_concurrency only bounds a semaphore, and the caller's in-flight
cap still bounds the true total across all actors, so per-actor
over-provisioning costs nothing it did not already cost.
Paths that declare no fan-in keep the option off the actor entirely and stay
byte-for-byte as they were, which covers the v1 GRPO path.
Adapted from ad1ce8f (saumishr/RL, squashed
from PR NVIDIA-NeMo#3672), which wires this through spinup_nemo_gym_actor. That
function is not on the sharded SingleController path -- setup.py reaches the
actors through build_nemo_gym_actors -- so the helpers and constants are taken
from it unchanged and the wiring is extended to both creation sites there.
Signed-off-by: Saurav Muralidharan <[email protected]>
build_nemo_gym_actors created its actors with no max_concurrency, so Ray's
async-actor default of 1000 applied to each. Past that limit the surplus does
not raise and does not queue anywhere this repo can see it: it parks inside the
actor as fibers on its concurrency semaphore, the submitter logs "tasks pending
submission to actor NemoGym", and the run stops producing steps. A silent hang,
on whatever allocation it was holding.
That ceiling is per ACTOR, not per job, so the shard plan decides where it
binds. The judge shard carries jailbreak_detection alone (1.36% of the blend)
on one un-replicated actor, while the verifier's 32 replicas take the rest
round-robin, which puts the first breach on a verifier replica:
judge (1 actor) verifier (each of 32)
8K GBS 118 268
16K GBS 237 536
32K GBS 473 1,073 <- over
Derive each actor's concurrency from the caller's in-flight cap plus a small
control-plane headroom, so _spinup and shutdown cannot be locked out by a
saturated rollout queue.
The fan-in is applied WHOLE to every replica rather than divided by the replica
count. Routing is by agent name and does not split evenly -- the table above is
the whole point -- so an even division would under-provision whichever shard
runs hot. max_concurrency only bounds a semaphore, and the caller's in-flight
cap still bounds the true total across all actors, so per-actor
over-provisioning costs nothing it did not already cost.
Paths that declare no fan-in keep the option off the actor entirely and stay
byte-for-byte as they were, which covers the v1 GRPO path.
Adapted from ad1ce8f (saumishr/RL, squashed
from PR NVIDIA-NeMo#3672), which wires this through spinup_nemo_gym_actor. That
function is not on the sharded SingleController path -- setup.py reaches the
actors through build_nemo_gym_actors -- so the helpers and constants are taken
from it unchanged and the wiring is extended to both creation sites there.
Signed-off-by: Saurabh Mishra <[email protected]>
Overview
A 68-node SingleController run produced zero training steps and zero rollout groups. The rollout pump dispatched 5120 concurrent generate_and_push calls, each of which is exactly one run_rollouts streaming call on the single NemoGym actor, and NemoGym.options() never passed max_concurrency -- so Ray's async-actor default of 1000 applied and the surplus sat queued at the submitting raylet, which logged ">5000 tasks pending submission to actor NemoGym" seventeen times and nothing else. A sweep put the cliff between 896 and 1152 in flight: a round number that says admission cap, not organic event-loop saturation.
Pass max_concurrency explicitly, resolved in one place from the caller's own fan-in. Absent env.nemo_gym.max_concurrency the default is the fan-in plus a small control-plane headroom, and deliberately no more: the caller's in-flight cap is the backpressure valve already, and an unbounded value would just relocate the same queue from the raylet into the actor's event loop, where it costs actor memory and is no more visible than before.
An explicit env.nemo_gym.max_concurrency below the in-flight depth is now a ValueError at config load (validate_gym_actor_concurrency, alongside validate_sampler_buffer_capacity) rather than a stall discovered hours in, and the resolved value is printed at spinup so the two numbers that decide this are in the log.
The v1 async-GRPO path fans in per prompt batch rather than per prompt -- single digits, never near Ray's default -- so it passes that default and its actor is configured exactly as before.
What does this PR do ?
Add a one line overview of what this PR aims to accomplish.
Issues
List issues that this PR closes (syntax):
Usage
# Add a code snippet demonstrating how to use thisBefore your PR is "Ready for review"
Pre checks:
Additional Information