Repository navigation
feat(eval): plan a benchmark, serve it and run single tasks in-process - #5593
Conversation
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
d9d7fcf to
1a8d0d6
Compare
6d30824 to
0a833e1
Compare
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
HOLD — the new in-process API has blockers in command-line/config isolation and default rollout identity, plus reliability issues in task execution and server startup.
I inspected all nine changed files and traced the affected preparation, routing, response, capture, cleanup, and startup paths. The eight findings below include repair guidance and preservation checks. I couldn't execute tests in this read-only review; all proposed checks and suggested patches need verification.
Note: formal approval is not available for this request, so this review is posted as a comment only.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| `work_dir` receives the collated files; a temporary directory is used when it is None. | ||
| """ | ||
| global_config_dict = _benchmark_config(asset_config_path("benchmark", benchmark), overrides) | ||
| plan = plan_for_config(global_config_dict, PrepareBenchmarkConfig.model_validate(global_config_dict), task_ids) |
There was a problem hiding this comment.
BLOCKER — The in-process API still inherits CLI help handling
With sys.argv = ["trainer", "--help"], this call exits the host process instead of returning a plan. PrepareBenchmarkConfig inherits BaseNeMoGymCLIConfig.pre_process, which calls ArgumentParser.parse_known_args() without an argument list and then calls exit() when it sees --help or -h. Setting the config parser's skip_load_from_cli=True doesn't bypass this validator. The same leak occurs in TrainDataProcessorConfig during collation and RolloutCollectionConfig during TaskRunner.run_task.
Could you add an explicit non-CLI validation mode to BaseNeMoGymCLIConfig.pre_process and propagate it through the PrepareBenchmarkConfig, TrainDataProcessorConfig, and RolloutCollectionConfig validations reached by these Python entry points? The invariant is that library calls neither interpret the host program's arguments nor exit because of them. Preserve existing CLI help behavior; don't temporarily rewrite process-wide sys.argv. The shared validation-mode plumbing needs a compatible API choice, so I haven't supplied a speculative patch.
Proposed checks, not executed: use a local one-row benchmark with downloads and HTTP stubbed, set the host arguments to --help and then -h, and call the real planning and runner validation paths. Both must complete without SystemExit, with sys.argv unchanged. Retain ordinary argument-free behavior and the CLI assertions in the existing help tests. The new planning test currently mocks out PrepareBenchmarkConfig.model_validate, so it cannot catch this failure.
There was a problem hiding this comment.
Fixed in fc61d10. plan_benchmark, serve_benchmark and TaskRunner.run_task now build their config models inside ignoring_command_line(), so the host's sys.argv is not read and --help no longer exits the process. Tests cover plan-style config building, serve_benchmark and run_task under argv = ['trainer', '--help'], plus the context manager itself.
| `work_dir` receives the collated files; a temporary directory is used when it is None. | ||
| """ | ||
| global_config_dict = _benchmark_config(asset_config_path("benchmark", benchmark), overrides) | ||
| plan = plan_for_config(global_config_dict, PrepareBenchmarkConfig.model_validate(global_config_dict), task_ids) |
There was a problem hiding this comment.
BLOCKER — Prepare scripts don't receive the locally resolved config
In a fresh external process, plan_benchmark("gpqa", overrides={"hf_token": token}) reaches GPQA's prepare(), which obtains its token through get_global_config_dict(). This entry point has only built a local config, so the global getter invokes the default parser and caches a process-wide config. The explicit token is therefore not the token the prepare script reads, and unrelated host arguments can abort planning. If another config is already cached, preparation reads that config instead. HLE has the same dependency.
Could you pass the resolved credentials/config through the preparation contract and update these dependent prepare scripts to consume that explicit input? Preserve zero-argument prepare scripts and the existing CLI fallback. Temporarily setting and resetting the global config would violate the advertised long-lived-process contract. The compatible preparation interface needs to be chosen, so no exact patch is proposed here.
Proposed checks, not executed: stub the dataset download and call the real GPQA planning/preparation path with an explicit token. Assert that the download receives that token, the host arguments remain untouched, and maybe_get_global_config_dict() remains None. Repeat with a different config already cached: planning must still use the explicit token and leave the cached config unchanged. Retain CLI preparation and IFEval planning, whose prepare script doesn't consult the global config.
There was a problem hiding this comment.
Fixed in fc61d10. Planning now runs the prepare step inside scoped_global_config_dict(resolved_config), so get_global_config_dict() returns the config built from the caller's overrides. The previous global config (or none) is restored afterwards, also when planning fails, and concurrent scopes are serialized by a lock. I re-ran the case with IFEval's prepare script: it now sees the caller's hf_token and policy_model_name and no key from the host's argv.
| rows = self._helper.preprocess_examples( | ||
| [self._row_of_task[task_id]], task_ids=[task_id], num_repeats=num_repeats | ||
| ) | ||
| if rollout_id is not None: |
There was a problem hiding this comment.
BLOCKER — Default task calls reuse the same rollout identity
For unstamped rows a and b, both run_task("a") and run_task("b") preprocess a one-row batch, so both receive task index 0, rollout index 0, and capture key 0-0. Repeated calls of the same task also reuse that key. Concurrent calls consequently append unrelated model exchanges to the same capture file, silently mixing rollout evidence. With checkpointing enabled on the same environment server, the second live episode is rejected as already running.
Could you allocate a fresh ID for each invocation when neither the argument nor the source row explicitly supplies one? Import uuid4 and replace the current conditional stamping block with:
if rollout_id is None and self._row_of_task[task_id].get("_ng_rollout_id") is None:
rollout_id = f"task-{uuid4().hex}"
if rollout_id is not None:
rows = [_with_rollout_id(row, rollout_id, index, num_repeats) for index, row in enumerate(rows)]This source-reasoned suggestion preserves explicit argument IDs, existing row-supplied identities and attempt bookkeeping, and the helper's repeat suffixes. Callers that deliberately supply identities still own their uniqueness. It doesn't mutate the source rows. Please verify the patch before adopting it.
Proposed checks, not executed: dispatch concurrent calls of different tasks and two calls of the same task without explicit identities; every capture key must differ. A two-repeat call must share one fresh base with -r0/-r1. Retain the explicit-ID assertions, and add cases confirming that a row-supplied saved remains saved for one rollout and saved-r0/saved-r1 for repeats when no argument overrides it.
There was a problem hiding this comment.
Fixed in fc61d10. A run_task call without a rollout_id now gets a fresh one (uuid4().hex), so concurrent calls no longer share a capture key. An explicit id is still used as given, and the docstring now says it must differ between concurrent calls. Test: three concurrent calls with repeats produce four distinct ids.
| ) | ||
| if rollout_id is not None: | ||
| rows = [_with_rollout_id(row, rollout_id, index, num_repeats) for index, row in enumerate(rows)] | ||
| completed = [ |
There was a problem hiding this comment.
RISK — Close the completion iterator when run_task fails or is cancelled
With two repeats, let one /run fail while the other remains blocked, or cancel the awaiting run_task. This comprehension exits without closing its iterator, so the remaining requests continue after the task call has failed or been cancelled. The caller has no iterator handle with which to stop them. The production iterator intentionally schedules independent requests and requires its owner to close it on early exit.
Could you replace lines 235–237 with:
completions = self._helper.run_examples(rows, head_server_config=self._registry_server)
try:
completed = [await rollout for rollout in completions]
finally:
await completions.aclose()Preserve the original exception/cancellation and successful raw responses and rewards. This joins local client work; it doesn't acknowledge remote sandbox cleanup. Update _FakeRuns to provide the production iterator's aclose contract rather than returning a list. The suggested code hasn't been executed.
Proposed checks: use the real iterator with a fake transport, block one repeat, and make the other fail. Assert that the original error propagates and the blocked request receives cancellation before run_task exits. Also cancel run_task after both requests start and assert both settle. Retain successful repeat rewards and explicit rollout IDs. The existing iterator test already pins the dependent cancellation behavior.
There was a problem hiding this comment.
Fixed in fc61d10. run_task keeps the completion iterator in a variable and awaits the rollouts in try/finally: await completions.aclose(). Tests cover a failing rollout and cancellation of the task.
| """ | ||
| if task_id not in self._row_of_task: | ||
| raise ConfigError(f"No input rows for task ids {[task_id]}") | ||
| rows = self._helper.preprocess_examples( |
There was a problem hiding this comment.
RISK — Complete the materialized-task execution path
A valid collated row such as {"task_id":{"taskset":"bench","task_id":"a"},"task_input":{"responses_create_params":{"input":[]},"task_data":{}}} indexes successfully, but run_task("a") fails before HTTP dispatch even when the deployment has a route for bench. preprocess_examples constructs its config without environment_server_routes, while materialized rows require that route in every routing mode. Passing its current global_config_dict argument alone won't fix this because that argument is used only after preprocessing.
Could you resolve the running deployment's taskset routes and pass them into preprocessing through an additive shared-helper parameter? Completing this path also requires handling native responses: they put the score in response["result"]["reward"], not the top-level field read at line 239. Reuse the native response validation/projection contract to obtain the reward while retaining the raw reply in TaskResult.results. Don't turn handled failures or absent rewards into fabricated zeros. The failure representation needs a deliberate API choice, so no speculative implementation is suggested.
Proposed checks, not executed: use a fake registry config with environment_server_routes={"bench":"env"} and run the row above through real preprocessing/dispatch. A matching native success with result={"reward":0.5} must yield [0.5] and retain the unchanged reply in results; a native failure must surface an actionable task failure, not KeyError. Preserve flat-row dispatch/top-level rewards, unchanged materialized task input, and missing-route rejection when the deployment truly has no route.
There was a problem hiding this comment.
Addressed in fc61d10 by refusing instead of supporting: TaskRunner raises ConfigError for a materialized task row, saying it runs flat task rows only. Before, the first run_task of such a row failed with a ValueError from preprocessing (No environment server route is configured for taskset ...). Running materialized rows needs the registry's environment_server_routes passed into preprocessing and a run against a taskset benchmark, which I did not do here. I would add that in a follow-up with its own test against a real taskset.
| _checked_overrides(overrides), | ||
| ) | ||
| return GlobalConfigDictParser().parse( | ||
| GlobalConfigDictParserConfig(initial_global_config_dict=initial, skip_load_from_cli=True) |
There was a problem hiding this comment.
RISK — Planning closes and replaces active exporters
_benchmark_config() invokes the runtime parser with skip_exporters=False. The parser calls setup_exporters, which unconditionally tears down existing exporters. Calling plan_benchmark("ifeval") inside a process with an active tracking run therefore closes that run. If the planning config has no exporter settings, subsequent metric exports become no-ops; otherwise planning may open a replacement run.
Could you disable live exporter setup specifically in _benchmark_config() by replacing its parser-config construction with:
GlobalConfigDictParserConfig(
initial_global_config_dict=initial,
skip_load_from_cli=True,
skip_exporters=True,
)This preserves config resolution while leaving exporter ownership with runtime startup. Don't change the parser default or the separate serving path. Please verify this source-reasoned suggestion before adopting it.
Proposed checks, not executed: open the recording exporter fixture, call planning through the real parser, and assert that the same exporter remains registered, wasn't torn down, and receives a subsequent metric. Planning with exporter settings in a bare process must not open a tracking run. Preserve runtime exporter setup and explicit setup's replacement behavior.
There was a problem hiding this comment.
Fixed in fc61d10. The parser config built for planning and for serving now sets skip_exporters=True, so the host's active exporters are neither torn down nor replaced. Test: the config passed to the parser has skip_exporters. I re-ran the case with a registered exporter: it is still active after plan_benchmark and its teardown() was not called.
| if registry_port is not None: | ||
| if not 0 < registry_port < 65536: | ||
| raise ConfigError(f"registry_port must be a port number from 1 to 65535, got {registry_port!r}") | ||
| initial = OmegaConf.merge(initial, {HEAD_SERVER_KEY_NAME: {"port": registry_port}}) |
There was a problem hiding this comment.
RISK — registry_port can silently change during startup
serve_benchmark(..., registry_port=5555) promises a fixed address for a runner in another process, but this assignment doesn't pin it. When the registry bind fails with EADDRINUSE, RunHelper.start invokes _move_to_a_fresh_port, which explicitly relocates the registry too. Serving can succeed elsewhere while the external runner keeps using 5555.
Could you propagate the explicit-port constraint into startup retry handling? An explicitly requested registry port must either bind unchanged or fail startup after cleanup. Suppress relocation only for the explicitly pinned registry; retain retries for managed servers and an unpinned registry. The supervisor needs a supported way to receive this constraint, so I haven't suggested a wrapper-side override of its private method.
Proposed checks, not executed: force a registry bind failure on the requested port and assert that the context body never runs, startup reports failure, and started resources stop. With the port free, assert that the yielded config and listener use exactly it. Preserve relocation for an unpinned registry and the managed-server retry in the existing startup test.
There was a problem hiding this comment.
Fixed in fc61d10. After the servers start, serve_benchmark compares the registry server's port with registry_port. If they differ, it shuts the servers down and raises ConfigError('registry_port N is in use: ...'). I re-ran the case with the port held by another socket against the real IFEval servers: it now raises instead of returning another port.
| raise ConfigError(f"registry_port must be a port number from 1 to 65535, got {registry_port!r}") | ||
| initial = OmegaConf.merge(initial, {HEAD_SERVER_KEY_NAME: {"port": registry_port}}) | ||
| helper = RunHelper() | ||
| helper.start(GlobalConfigDictParserConfig(initial_global_config_dict=initial, skip_load_from_cli=True)) |
There was a problem hiding this comment.
RISK — Startup errors escape the advertised ConfigError boundary
The new API says unavailable servers raise ConfigError, but this call can raise ServerStartFailedError when a server exits before readiness, or ServerSpinupTimeoutError when readiness times out. Both inherit RuntimeError, so callers following the documented error contract miss these ordinary startup failures. The new failed-start test injects ConfigError directly and cannot detect this distinction.
Could you translate these typed startup failures at the wrapper boundary? Import the two exception classes and replace the start call with:
try:
helper.start(
GlobalConfigDictParserConfig(
initial_global_config_dict=initial, skip_load_from_cli=True
)
)
except (ServerStartFailedError, ServerSpinupTimeoutError) as error:
raise ConfigError(str(error)) from errorKeep this outside the yield's cleanup block: RunHelper.start already cleans up failed starts. Preserve its typed exceptions for other callers, existing ConfigErrors, and exceptions raised inside the context body. The suggested code hasn't been executed.
Proposed checks: inject each typed startup exception and assert that entering the context raises ConfigError with the original message and __cause__, without entering the body or shutting down twice. Retain direct propagation of existing ConfigErrors, normal exit cleanup, and propagation of a caller's RuntimeError with one shutdown.
There was a problem hiding this comment.
Fixed in fc61d10. serve_benchmark now turns ServerSpinupTimeoutError and ServerStartFailedError into ConfigError, with the original error as __cause__; RunHelper.start has already stopped the servers by then. The docstring also lists the registry-port case. Tests cover both error types and the chained cause.
0a833e1 to
244e14f
Compare
244e14f to
36f3924
Compare
preprocess_examples(rows, task_ids=[...]) keeps only the named tasks, selected by the id each row carries (task_id, problem_id or instance_id), each task once before repetition, so the repeat count alone decides the number of samples. Selection lives in nemo_gym.task_selection: every row must carry an id, unknown ids and differing rows that share an id are config errors, and rows are selected before they are copied. Signed-off-by: Ingo Guehring <[email protected]> (cherry picked from commit 95718ab) Signed-off-by: Ingo Guehring <[email protected]>
`nemo_gym.environment.plan_benchmark(name)` resolves, prepares, plans and collates one benchmark in one call, building the same plan as `gym eval plan`, without reading `sys.argv` or setting Gym's process-wide config. `TaskRunner(rows, head_server=...)` checks and indexes the rows once and runs one task per `run_task` call against running servers. Their signatures are pinned by a test: they change only additively. Signed-off-by: Ingo Guehring <[email protected]>
`plan_benchmark` takes its config as a dict, but the servers could only be started by `gym env start`, whose config is command-line text. A caller that holds the dict had to write it out as `++key=value` tokens, which Gym then parsed back into the same dict, and the two paths could disagree: Hydra does not accept a nested dict or a list of dicts as a value, and it treats backslashes, quotes and non-ASCII text differently from JSON. `serve_benchmark(benchmark, model_type=..., overrides=...)` builds the config from the same kind of dict as `plan_benchmark` and starts the servers with `RunHelper`, as `gym env start` does, then stops them on exit. It yields the head server for a `TaskRunner`. Both `plan_benchmark` and `serve_benchmark` refuse a dotted override key at any depth with a `ConfigError`: merged as a dict, "judge.model" is one key with a dot in its name, while `++judge.model=x` on the command line sets `model` inside `judge`, so the dotted form would silently do nothing. Signed-off-by: Ingo Guehring <[email protected]>
A caller outside Gym should need only the names `nemo_gym.environment` exports, not Gym internals. - `PlannedBenchmark.task_digests()` and `gym_commit` give the per-task input digests and the Gym commit of a plan, so callers do not read the plan's fields. `to_json()` and `from_json()` carry a plan to another process. - `EvalPlan` is exported next to `PlannedBenchmark`, so its type no longer has to be imported from `nemo_gym.eval.eval_plan`. - `serve_benchmark(..., registry_port=)` fixes the registry server's port, so a caller that serves from another process knows the address before the servers start and does not have to set the registry server's config key itself. - The module docstring and the API reference say what is stable (the exported names, their signatures and result fields), that `TaskResult.results` is raw and unstable, and the constraints on process, working directory and a writable checkout. Tests pin the new signatures and the result fields. Signed-off-by: Ingo Guehring <[email protected]>
A program that calls plan_benchmark, serve_benchmark or TaskRunner is not the Gym CLI, but these calls read and changed process state as if it were. Fix the review findings on this PR: - Build CLI config models from their given values alone (ignoring_command_line) while planning, serving and preprocessing a task, so the host's --help or other flags are neither read nor exit the process. - Run the benchmark's prepare step with the resolved config as the global config (scoped_global_config_dict) and restore the previous one afterwards. - Leave the host's active exporters alone (skip_exporters). - Give each run_task call without a rollout_id a fresh one, so concurrent calls do not share a capture key. - Close the completion iterator when a rollout fails or the task is cancelled. - Refuse materialized task rows in TaskRunner with a ConfigError, as they need environment server routes it does not have. - Raise ConfigError when the requested registry_port is not the one the registry server started on, and when servers fail to start, keeping the original error as the cause. Signed-off-by: Ingo Guehring <[email protected]>
fc61d10 to
47fdd47
Compare
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP — no eligible findings remain in this follow-up.
I checked the eight prior findings against the current source and traced the fixes through their affected paths:
- Configuration isolation: library validation now bypasses host argument parsing while retaining ordinary CLI help behavior. Planning supplies its resolved config during preparation, restores the previous cached config afterward, and skips exporter setup. See planning and config restoration.
- Task execution: default calls receive fresh rollout identities, and failure or cancellation closes the production completion iterator. Materialized rows are explicitly rejected before execution rather than accepted into an unsupported path. See TaskRunner.
- Server startup: a relocated registry port is rejected before the context yields, with shutdown afterward. Typed startup failures become
ConfigErrorwith the original cause preserved. See serve_benchmark.
This was a follow-up, not a fresh whole-PR review. The previously reviewed tree wasn't available, which limited independent comparison of the inter-review delta. No new regression meeting the introduction-evidence and impact-escalation requirements was established. I inspected the relevant regression tests but couldn't execute them in this read-only review.
Review generated by codex. This was a findings-only review. Request a full review with /review reset=true.
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42043368788 |
Lets a caller outside Gym plan a benchmark, start its servers and run single tasks in-process. The code lives in
nemo_gym.environmentand is exported from the package.This PR is stacked on the one that moves benchmark preparation out of the CLI: its base branch is that change, so the diff here is only the feature.
What changed
Task selection.
RolloutCollectionHelper.preprocess_examples(rows, task_ids=[...])keeps only the named tasks, selected by the id each row carries (task_id,problem_idorinstance_id), each task once before repetition. Rows without an id, unknown ids and differing rows that share an id areConfigErrors. New modulenemo_gym.data.task_selection.Plan and run.
plan_benchmark(name, task_ids=, overrides=)resolves, prepares, plans and collates one benchmark in one call, without readingsys.argvor setting Gym's process-wide config.TaskRunner(rows, registry_server=...)checks and indexes the rows once and runs one task perrun_taskcall against running servers. The registry server is the server that serves the run's config and the other servers' addresses.Serve.
serve_benchmark(benchmark, model_type=, overrides=)starts a benchmark's servers from a config dict and stops them on exit. Before, onlygym env startcould start them, from command-line text, which cannot express every dict (a nested dict or a list of dicts is not a value Hydra accepts) and reads quotes, backslashes and non-ASCII text differently from JSON. Planning and serving now take the sameoverridesdict and merge it the same way. Likegym env start, it sets this process's Gym configuration, so serve one benchmark per process.A self-contained API for callers outside Gym.
PlannedBenchmark.task_digests()andgym_commitgive a plan's per-task input digests and Gym commit;to_json()andfrom_json()carry a plan to another process;EvalPlanis exported next to it; andserve_benchmark(..., registry_port=)fixes the registry server's port, so a caller that serves from another process knows the address before the servers start. The module docstring and the API reference say what is stable (the exported names, their signatures and result fields), thatTaskResult.resultsholds Gym's raw responses and is not part of the contract, and what the constraints are (process-wide config, working directory, a writable checkout). Tests pin the signatures and the result fields.Overrides are a nested dict, not dotted paths. A key that contains a dot is refused with a
ConfigErrorat any depth, instead of being silently ignored: in a dict it would be one key with a dot in its name, while on the command line the same text names a path.The calling program's state stays its own. These calls are used from programs that have their own command line, configuration and telemetry, so they do not read or replace them:
sys.argv: a--helpthere no longer prints Gym's help and exits (ignoring_command_line()innemo_gym.config.config_types).overridesas Gym's global config while it runs, and the previous one is restored afterwards (scoped_global_config_dict()).run_taskcall without arollout_idgets a fresh one, so concurrent calls do not share a capture key; a rollout id the caller passes must be unique per concurrent call.serve_benchmarkraisesConfigErrorwhen the servers do not start (the original error is the cause) and when the requestedregistry_portis not the one the registry server started on.TaskRunnerrefuses a materialized task row with aConfigError: it runs flat task rows only.Why
Trainers and evaluation services that drive Gym from their own process need to plan a benchmark, run it task by task and own the server lifecycle, without shelling out to the CLI. There is no separate issue for this.
Compatibility
Additive. New public names in
nemo_gym.environment;preprocess_examplesgains an optional keyword;gym eval planbehaves as before.ignoring_command_line()andscoped_global_config_dict()are new helpers innemo_gym.config; the command-line behavior of every existing config model is unchanged outside them. The newTaskRunnerparameter uses the name "registry server" so that the public signature, which changes only additively, does not pin the term "head server".Validation
data/test_task_selection), the in-process API (environment/test_in_process,test_public_api) and the command-line switch (config/test_config_types_help). Each of the behaviors in "The calling program's state stays its own" has a test. With the fix reverted (and the two new helpers as no-ops), 13 of the new tests fail; with the dotted-key rule switched off, exactly the refusal tests fail.pre-commit run --all-filespasses on the top of the stack, including ruff, ruff-format and import-linter.pytest tests/unit_tests -n 4on the top of the stack: 18,576 passed, 111 failed, 6 collection errors. The same test files onorigin/maingive 108 failures and the same 6 errors: they come from this macOS machine (for examplemlflowis not installed). The one failure that differs,test_slurm_script::test_build_vllm_ray_serve_command_multi_node_chain_survives_symmetric_run_entrypoint, passes when run alone.plan_benchmark,serve_benchmarkandTaskRunner(2 tasks run concurrently), with the model served by a local stub that returns a fixed reply. The plan survivesto_jsonandfrom_jsonunchanged; the servers came up on exactly the port passed asregistry_port; both tasks ran and were verified (rewards 1.0 and 0.0, as expected for a fixed reply); and the servers stopped when the context exited. Withregistry_portheld by another process,serve_benchmarkraisesConfigError. No real model was used.