Repository navigation
Conversation
…ve PTY from SWE Pro; Fix TB2.1 interleaved thinking (#3540) <!-- Thanks for contributing to NeMo Gym! Please fill out the sections below. --> ## What does this PR do? 1. New/updated model configs: benchmarks/nemotron_3.5_super/vllm_configs/deepseek_v4_flash_0731.sh, benchmarks/nemotron_3.5_super/vllm_configs/glm_5.3_flash.sh, benchmarks/nemotron_3.5_super/vllm_configs/inkling_small.sh, benchmarks/nemotron_3.5_super/vllm_configs/nemotron_3.5_lightning.sh, benchmarks/nemotron_3.5_super/vllm_configs/nemotron_3.5_super.sh, benchmarks/nemotron_3.5_super/vllm_configs/nemotron_3.5_super_mtp.sh, benchmarks/nemotron_3.5_super/vllm_configs/qwen_3.8_flash_next.sh 2. Allow non-pd setup: benchmarks/nemotron_3.5_super/sbatch_external_vllm.sh 3. Remove PTY from SWE Pro: resources_servers/swebench_pro/tests/test_app.py, resources_servers/swebench_pro/app.py 4. Fix TB2.1 interleaved thinking: responses_api_agents/terminus_2_sandboxed_agent/configs/terminus_2_sandboxed_agent.yaml, responses_api_agents/terminus_2_sandboxed_agent/app.py 5. Misc: benchmarks/nemotron_3.5_super/analyze_waiting_requests.py ## Validation <!-- List the exact commands and checks run against the final diff. --> ## Rollouts <!-- Include representative rollout evidence for behavior-changing environment or agent code, or a justified N/A. --> ## Compatibility and benchmark impact <!-- Describe compatibility, migration, configuration, or benchmark-result effects, or state "None". --> ## Checklist - [ ] I have read the [contributing guidelines](https://github.com/NVIDIA-NeMo/Gym/blob/main/CONTRIBUTING.md). - [ ] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [ ] Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable). - [ ] Documentation added or updated, or N/A with justification. - [ ] Pre-commit checks pass locally (`pre-commit run --all-files`) (so CI lint/format checks pass). - [ ] New source files include the required Apache-2.0 SPDX header. - [ ] All commits have DCO sign-off (`git commit -s`) (so the DCO check passes). --------- Signed-off-by: Brian Yu <[email protected]>
…3538) ## What does this PR do? Retry HTTP 404 and 408 by default in Gym's shared OpenAI-compatible client. Transient model-routing failures can recover without benchmark-specific configuration; permanent errors fail after the bounded attempt budget. The default remains three total attempts, configurable per model server through `max_http_attempts`, with the existing fixed 0.5-second delay between retries. Route exhausted equivalence-judge errors through Gym's shared `judge_failed` handling so saved policy answers can be recovered with `gym eval reverify --judge-failed-only`. This preserves the no-lost-rollouts intent of #2805 using the shared failsafe from #2113, instead of recording an unavailable judge as a completed incorrect answer. Add an optional `max_answer_chars` guard to the shared equivalence verifier. It is unset by default. Evaluation, synthetic data generation, and RL workflows can opt in through the resources-server configuration; the limit changes reward assignment. When enabled, oversized final answers receive zero with an explicit length failure and no judge call; the full response is retained and reasoning is excluded. Missing assistant messages and empty or whitespace-only final assistant text now score zero with `failure_reason: empty_final_answer` and no judge call. The full response is preserved. The check precedes regex extraction and does not bypass the existing fallback for nonempty answers. No separate issue is needed: this addresses observed transient grading failures and pathological repetitive final answers. There are no HLE-specific file changes or retry presets in the final diff. ## Validation On runtime revision `e8cbec0c9e372aff32d84d15898dac668e84b263` (subsequent changes are documentation-only): ```bash .venv/bin/python -m pytest --import-mode=importlib -o addopts='' -o log_cli=false -q \ tests/unit_tests/test_openai_utils.py \ tests/unit_tests/test_judge.py \ tests/unit_tests/test_rollout_reverification.py \ resources_servers/equivalence_llm_judge/tests/test_app.py \ responses_api_models/openai_model/tests/test_app.py .venv/bin/pre-commit run --all-files ``` 479 tests passed; all pre-commit hooks passed. Tests cover default 404/408 recovery, bounded internal/external failures at attempt budgets of one/three/five, preserved requests and terminal error bodies, permanent non-retryable errors, per-model budgets, answer-limit boundaries, default uncapped grading, reasoning exclusion, preserved-response recovery, empty final answers, and nonempty answers whose regex extraction yields an empty match. The shared core changes give this PR full CI scope. The entire component suite was not run locally; the affected suites above were run. ## Rollouts Offline HTTP replay on that runtime revision exercised the actual updated model server and verifier with saved policy responses and recorded judge replies: - Derived reasoning-only and missing-output cases made zero judge calls, retained their responses, and reported `empty_final_answer`. - Default 404 and 408 retries each recovered after two injected failures. - Three consecutive 404s exhausted the default budget and preserved the response as `judge_failed`; a later judge-only replay recovered the grade. - A response with 341,172 reasoning characters and a 4,925-character final answer was graded normally. - A 496,874-character final answer made no judge calls with an explicit 100,000-character limit, and reached the judge normally when the limit was unset. All request hashes and policy responses were preserved. Four live judge-only calls also passed on the earlier revision `083323d99`, before moving 404 retries into shared defaults and moving the cap out of benchmark configs. No additional live calls or policy generation were run for this revision, and no full benchmark was rerun. ## Compatibility and benchmark impact - HTTP 404/408 retries now apply across datasets to clients using the shared implementation. Bad routes/model names fail after the configured budget instead of immediately. The default attempt count remains three; existing internal rate-limit retry extension is unchanged and does not apply to 404/408. - Exhausted equivalence-judge calls become pending failures excluded from scored aggregates, rather than completed zero scores. A run with pending grades is incomplete. Legacy in-band `JUDGE_ERROR` rows remain readable but need migration before judge-failed-only recovery. - Empty final text is now scored zero deterministically rather than sending an extraction-failure placeholder to the judge; this applies to every equivalence-verifier dataset. - `max_answer_chars: null` is the default everywhere, preserving existing answer-length behavior. An explicit limit changes grading semantics, counts the last assistant message before regex extraction, and does not stop generation early. ## Checklist - [x] I have read the contributing guidelines. - [x] The change is focused; no unrelated edits. - [x] Tests added or updated and pass locally. - [x] Documentation updated with retry configuration, recovery, and benchmark impact. - [x] Pre-commit checks pass locally. - [x] New source files include the required Apache-2.0 SPDX header. - [x] All commits have DCO sign-off. --------- Signed-off-by: Igor Gitman <[email protected]>
miniSWE now emits canonical turns, invocation ownership, and per-tool timing and outcomes so Gym rollouts can be inspected and correlated with model-call captures. Enable `observability_enabled: true` in the Gym run configuration. Direct `MiniSWEHarness` callers can pass `observability_enabled=True`; collection is disabled by default. Responses without an ID retain their turn and record a `model_call_reference_unavailable` gap. The change also preserves tool results, including final submission, in combined Responses output; keeps incomplete token usage unknown; and emits namespaced TB4 identities such as `terminal-bench/interleaved-vigenere`. The TB4 smoke runner retains model captures, canonical rollout JSONL, and health reports. Regenerate prepared TB4 datasets to use named task identities in collection. Model-visible prompts, serial execution, and official grading are unchanged. A capped real `interleaved-vigenere` smoke exercised the observation path and completed verification with reward 0 after reaching its step limit. Full pre-commit validation remains pending because the local jj workspace lacks a Git working-tree marker. --------- Signed-off-by: Frederic Lafrance <[email protected]>
…ard (#2611) Closes #2608 `BaseVerifyResponse` carries a single scalar for the outcome, so an environment that *knows* it failed — lost session, unavailable judge, OOM-killed container, reset timeout — can only return `0.0`, which is indistinguishable from a policy that genuinely scored zero. The concept is not new to this repo. It exists in four private locations: - `mask_sample: bool = False` on `SWEBenchWrapperInstanceConfig` (`responses_api_agents/swe_agents/app.py:272`), also `anyterminal_agent/app.py:108` and `anyswe_agent/app.py:180`, documented at `swe_agents/README.md:670`. - `conversational_tool_use/simulation/app.py:112` keeps its own `{"mask_sample": ...}` dict. - `nemo_gym/token_id_capture/delivery.py:49` already defines `MASK_SAMPLE_KEY = "mask_sample"` as a **top-level** rollout field, described there as what "a consumer reads to exclude a rollout from the loss". - NeMo-RL consumes only the first one, through `full_result["instance_config"]["mask_sample"]` (`nemo_rl/experience/rollouts.py:229-241`), which zeroes `loss_multiplier` in `nemo_rl/algorithms/grpo.py:2104`. So core already agrees what the key is called and what it means; it is reachable only if your environment happens to be SWE-shaped or if token capture produced it. verl gets nothing. This is the same objection raised on #2384 — that a fix "should be applied uniformly, to other benchmarks as well" rather than to one harness. Putting the field on the contract is what makes it uniform. ## What this changes **1. The contract** (`nemo_gym/base_resources_server.py`) ```python class BaseVerifyResponse(BaseVerifyRequest): reward: float mask_sample: bool = False # is this reward a valid measurement failure_kind: Optional[str] = None # which kind of failure, from #3179's vocabulary failure_reason: Optional[str] = None # what happened, for a person ``` The three are orthogonal. `mask_sample` decides usability, `failure_kind` groups in logs and metrics, `failure_reason` explains one occurrence. A sample that degraded but was still measured validly names a kind and stays unmasked. `failure_kind` validates against `nemo_gym.failure_kinds` and warns rather than rejects — an unregistered name is a migration signal, and failing the response over it would replace a visible wrong label with an invisible lost failure. An environment that needs something the shared set should not grow uses `<server>:<kind>`. Gym states the fact and stops there. Masking, resampling, excluding from group statistics or dropping the group stays the training framework's decision — the three frameworks we checked genuinely differ. `swe_agents` and `anyswe_agent` mirror their instance-config flag onto the contract field and keep the old location for one release. `anyterminal_agent` already surfaces it through `TerminalBenchMetrics`. **2. Something that reads it** (`nemo_gym/reward_profile.py`, `nemo_gym/rollout_collection.py`) A declaration nothing consumes is not worth much, and the consumer that matters is the one that publishes the score. `compute_aggregate_metrics()` computes quality from the scored subset: the profiler input, a custom `compute_metrics()`, and key-metric selection all skip masked samples. Masked rows stay in the input and are reported as coverage instead — `coverage/measured_rollouts|masked_rollouts` and `coverage/measured_tasks|fully_masked_tasks`. A run where every sample is masked publishes coverage rather than inventing a zero, and a fully masked task is counted without contributing a group. `mask_sample` is stripped before profiling, so it is no longer averaged as though the flag were a measurement. `perf_summary` deliberately keeps using every response, masked included: a masked sample still executed and still reported its latency, so observability coverage should not shrink because a rollout was excluded from scoring. Progress telemetry gets the same split while a run is still going, over the results that reach the main rollout output: - `progress/<agent>/reward` is unchanged — it still averages over every rollout, so an existing dashboard reads the number it read before. - `progress/<agent>/reward_unmasked` is that same average with the masked rollouts removed. - `progress/<agent>/masked_pct` is how many were removed. - `progress/<agent>/failed` and `/omitted` count the attempts that never reach the main output at all, so a sidecar failure is never folded into a quality average as a reward of zero. The gap between the two reward series is the score a run lost to its own infrastructure rather than to the policy. On the run that motivated this, 1172 of 1280 rollouts across steps 61–80 failed in session reset and entered GRPO as legitimate zeros; nothing in the metrics said so. Every new key appears only once something is actually masked, failed or omitted, so a healthy run publishes exactly what it published before. ## Scope Run-level reconciliation is no longer in this PR. #3302 implements it for #2135, using the materialized inventory and attempt journal to account for omitted and unknown work offline — neither of which this contract can see. What remains here is the per-sample half. ## Relationship to the other failure-handling work - **#2552** (merged) landed `failure_reason` and its comment already points here: *"Machine-readable handling belongs to `mask_sample`/`failure_kind`."* This PR is that half. - **#2728** owns `failure_kind` and the shared registry, and already reserves `session_lost` with `source="#2611"`. No overlap — this PR does not touch `failure_kind`. - **#2750** lists this under *Failure fields and artifact integrity*. The design document's rule — *"the producer returns the real result with `mask_sample=True`, a stable `failure_kind`, and a human-readable `failure_reason`"* — is exactly what the three fields together express once this lands. ## Compatibility Defaults are inert; an unmodified environment behaves identically, and a run that masks nothing publishes exactly the keys it published before. One inheritance detail worth naming: `AnySweVerifyResponse` inherits `mask_sample` from both `SWEBenchMetrics` and `BaseVerifyResponse`, and the metrics model wins the MRO, so the contract field resolved to `Optional[bool] = None` with no description on that response. It is restated on the subclass so the schema keeps the contract's type, default and description. ## Tests - `tests/unit_tests/test_base_resources_server.py` — defaults, round trip, that a plain `reward=0.0` is *not* implicitly masked, and that a degraded-but-scored rollout stays unmasked. - `tests/unit_tests/test_aggregate_metrics.py` — a masked zero does not halve the score, the flag is not published as a quality metric, a run that masks nothing is byte-identical, a fully masked run reports coverage instead of a zero, a fully masked task is counted but not scored, custom `compute_metrics()` sees only scored samples, and a fully masked run still reports observability coverage. - `tests/unit_tests/test_rollout_collection.py` — the disposition account closes for every combination and the residual never goes negative; a healthy run adds no keys; a partially masked agent reports its share and the score without it; a fully masked agent publishes no average; failed and omitted attempts are counted, never averaged. - `responses_api_agents/anyswe_agent/tests/test_app.py` — an end-to-end `/run` that constructs and serializes the response. Reverting the fix makes it fail with `TypeError: got multiple values for keyword argument 'mask_sample'`. `uv run --extra dev pytest tests/unit_tests -q` → 3383 passed. Two failures on this branch, `test_e2b_provider` and `test_enroot_provider`, reproduce on a clean `upstream/main` and are unrelated. `pre-commit` clean. --------- Signed-off-by: waple0820 <[email protected]> Co-authored-by: waple0820 <[email protected]>
## Expected An empty or whitespace-only judge reply should produce a retryable `judge_failed` result, excluded from scores by default—not count as an incorrect policy answer. ## Actual AA-LCR's legacy protocol returns `reward=0` and `invalid_judge_response=True` for these replies, including the ungraded sample in the score. ## Fix Move the existing empty-reply check before protocol selection. Nonempty verdicts, empty policy answers, and v1.1 behavior are unchanged. This intentionally revises the legacy compatibility behavior preserved in #3152; scores may change for runs containing empty judge replies. Validation: 231 tests and pre-commit passed. Still Draft: real-model rollout and isolated server/data validation remain incomplete. Signed-off-by: yaoyu-33 <[email protected]>
## Summary - add a `megatron_worker` external staging backend so Megatron-Inference (MInf) serving workers can participate in framework-owned token capture - extract the vLLM worker capture logic from the model server into typed backend handlers (`external_capture.py`) with a shared prepare/finalize lifecycle - both backends follow the same durability boundary: the worker stages the canonical token delta in TQ before responding, returns `ng_commit_coords`, and Gym records a token-free `CallRecord` only after that acknowledgement - the Megatron handler differs from vLLM only in the engine request flag (`return_tokenized_data` instead of `return_tokens_as_token_ids`); both strip token IDs, logprobs, and coordinates off the agent hop - let `begin_call` accept an explicit `weight_version` so the MInf worker can stamp the epoch from engine-finished metadata - add handler, config, and model-server integration coverage ## Testing - `pre-commit run --files` on all changed working-tree files - Gym token-capture and focused model-server suites pass locally ## Baseline note The complete `responses_api_models/vllm_model/tests/test_app.py` run has 15 response-ID expectation failures (`chtcmpl-123` versus `resp_123`). A representative failure reproduces unchanged on `pthombre/tq-tokidcap-capture`, so it is not introduced by this branch. The remaining red CI checks (lint, copyright, `test_server_utils`) come from files this PR does not touch, and the shard 2/6 failures are an apt mirror error. ## Dependencies - This PR intentionally targets `pthombre/tq-tokidcap-capture`, not `main`. - RL consumer: NVIDIA-NeMo/RL#3869. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Laura Dang <[email protected]> Signed-off-by: Laura Dang <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Ananth Subramaniam <[email protected]>
Clarifies how model-call capture and agent observations become ng_trajectory, and how health checks and performance summaries consume it. - Adds an observability hub separating rollout evidence from OpenTelemetry. - Documents correlation, payload retention, and gaps with a schematic and joined example. - Simplifies the capability matrix, removes stale claims, and matches Gym’s documentation style. Related issue: #2891. ## Validation Validated after merging main at `88d9d45385f15b1351cdd055fff396186000f84f`: - `python -m pytest tests/unit_tests/test_fern_docs_links.py tests/unit_tests/test_rollout_observability.py tests/unit_tests/test_rollout_collection.py tests/unit_tests/test_rollout_health.py -q -o addopts='' -o log_cli=false`: 302 passed, 17 subtests passed. - `pre-commit run --all-files`: passed. - `cd fern && npm run check -- --warnings`: 0 errors; missing-redirects check skipped because the local CLI is not authenticated. - Verified all 148 displayed capability cells match current main, with the Terminus2 section preserved verbatim and the Verifiers capture update retained in the new table layout. Rollout evidence: N/A — documentation and documentation regression tests only; no runtime or benchmark-result changes. --------- Signed-off-by: Rita Fernandes Neves <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> Co-authored-by: yaoyu-33 <[email protected]>
<!-- Thanks for contributing to NeMo Gym! Please fill out the sections below. --> ## What does this PR do? <!-- Briefly describe the change and the motivation. Link any related issue, e.g. "Closes #123". --> ## Validation <!-- List the exact commands and checks run against the final diff. --> ## Rollouts <!-- Include representative rollout evidence for behavior-changing environment or agent code, or a justified N/A. --> ## Compatibility and benchmark impact <!-- Describe compatibility, migration, configuration, or benchmark-result effects, or state "None". --> ## Checklist - [ ] I have read the [contributing guidelines](https://github.com/NVIDIA-NeMo/Gym/blob/main/CONTRIBUTING.md). - [ ] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [ ] Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable). - [ ] Documentation added or updated, or N/A with justification. - [ ] Pre-commit checks pass locally (`pre-commit run --all-files`) (so CI lint/format checks pass). - [ ] New source files include the required Apache-2.0 SPDX header. - [ ] All commits have DCO sign-off (`git commit -s`) (so the DCO check passes). Signed-off-by: Brian Yu <[email protected]>
## What does this PR do?
Registers `environment_servers` as a first-class Gym server type for
configuration, discovery, startup, addressing, status, and telemetry.
## Interaction flow
```mermaid
sequenceDiagram
participant C as Rollout collector
participant E as Environment Server
participant R as Task / Resources Server
participant A as Agent Server
participant M as Model Server
participant S as Task sandbox
C->>E: POST /run
E->>R: Seed task session
R-->>E: Tool access and optional SandboxAccess
E->>A: Seed agent session
A->>S: Connect as borrower when supplied
E->>A: Invoke /v1/responses
A->>M: Model and capture requests
A-->>E: Agent response
E->>A: Close agent session
E->>R: Verify response
E->>R: Close task session
E-->>C: Episode result
```
The Environment Server coordinates ordering and the final result. Agent
and Task/Resources Servers retain ownership of the state and resources
they create.
This is part 1 of 13 in the Environment Server stack. Previous: `main`.
Next: [#3483](#3483).
## Validation
- `uv run pytest tests/unit_tests/test_global_config.py -q`
## Rollouts
See the final PR for end-to-end rollout evidence.
## Compatibility and benchmark impact
Existing Agent Server routing remains available during migration.
Signed-off-by: Ananth Subramaniam <[email protected]>
_(Originally branched from `fsiino/super35-vllm-model-tuning`, PR #2599. After that PR merged, we moved the Ultra changes onto updated main and kept the shared launcher compatible. Main was subsequently merged again at `f656822f6`.)_ ## What this PR does - Adds `benchmarks/nemotron_3.5_super/vllm_configs/nemotron_3_ultra.sh`: a fixed Ultra BF16 recipe using piecewise CUDA graphs on both tiers, MTP3, prefix caching, asynchronous prefill, synchronous decode, FP8 KV cache, FP16 Mamba state with stochastic rounding, and expert parallelism. - Adds opt-in coupled deployment to `benchmarks/nemotron_3.5_super/sbatch_external_vllm.sh`. Ultra uses four prefill nodes and four decode nodes, each with four GPUs; each tier distributes the model across 16 GPUs. The default remains independent deployment for models that fit a complete replica on one node. Existing router defaults and sampling overrides are preserved. - Makes walltime and allocation segmentation configurable, bounds coupled startup health probes, and detects coupled prefill/router exits during startup and serving. Adds launcher regression coverage in `tests/unit_tests/test_super_vllm_launcher.py`. ## Benchmark scores | Benchmark | Earlier full run `7014044 / f656822` | Non-eager full run `7093754` | Tracker | |---|---:|---:|---:| | Tau3-Banking | 11.13% | 11.34% | 18.40% | | Tau3-Average | 58.86% | 58.13% | 64.60% | | SciCode — full-problem accuracy | 11.54% | 9.62% | 11.90% | | AA-LCR | 52.13% | 54.22%* | 64.10% | | AA-Omniscience — OmniIndex | 7.65% | 7.58% | 23.80% | | GPQA Diamond | 85.98% | 87.56% | 86.50% | *AA-LCR's newer score covers 1,457/1,600 attempts, versus 1,600/1,600 previously; the apparent increase is not a clean comparison. Tau3-Average equally weights Airline, Retail, Telecom, and Banking. Omniscience answer accuracy was 24.38%/24.08%; that is a different metric from OmniIndex and must not be compared with the tracker's OmniIndex value. Score artifacts: - `results/nemotron-3-ultra-bf16-p4d4-c16-mtp3-v0271-piecewise-copyinputs-full-suite-validation-20260908/resumable_aggregate_metrics.json` - `results/nemotron-3-ultra-mtp3-c16-syncdecode-full-super-20260912-023329/resumable_aggregate_metrics.json` ## Run command — Super suite, post-merge 0.29 (30 minutes) ```bash EXPERIMENT_NAME="nemotron-3-ultra-mtp3-c24-v0290-postmerge-$(date -u +%Y%m%d-%H%M%S)" MODEL=/lustre/fsw/portfolios/llmservice/users/igitman/hf_models/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16 \ VLLM_CONFIG=benchmarks/nemotron_3.5_super/vllm_configs/nemotron_3_ultra.sh \ EXPERIMENT_NAME="$EXPERIMENT_NAME" \ ROLLOUTS_FPATH="results/$EXPERIMENT_NAME/resumable.jsonl" \ EXPORT_TO_CSV=0 \ NUM_PREFILL_NODES=4 \ NUM_DECODE_NODES=4 \ VLLM_PD_DEPLOYMENT_MODE=coupled \ VLLM_SLURM_SEGMENT=4 \ SBATCH_ACCOUNT=nemotron_rl_algo \ SBATCH_PARTITION=batch_long \ SBATCH_QOS=normal \ SBATCH_TIME=2-00:00:00 \ SBATCH_GRES=gpu:4 \ SBATCH_EXPORT=ALL \ CONTAINER="/lustre/fsw/portfolios/llmservice/users/fsiino/repos/Gym-inkling-tuning/results/vllm/vllm-openai:v0.29.0___super-vl-evals-2a3c65b-ultra-with-gym-b894cbe-20260914-202306.sqsh" \ MOUNTS="/lustre:/lustre,$(pwd -P)/env.yaml:/opt/Gym/env.yaml:x-create=file,$(pwd -P)/results:/opt/Gym/results,$(pwd -P)/benchmarks/nemotron_3.5_super/vllm_configs/nemotron_3_ultra.sh:/opt/Gym/benchmarks/nemotron_3.5_super/vllm_configs/nemotron_3_ultra.sh:ro" \ bash benchmarks/nemotron_3.5_super/sbatch_external_vllm.sh \ --config benchmarks/nemotron_3.5_super/eval_container_config.yaml \ '++num_samples_in_parallel=24' \ '++resume_from_cache=true' \ '++critpt_benchmark_agent.responses_api_agents.critpt_agent.datasets=[]' \ '++hle_benchmark_equivalence_llm_judge_simple_agent.responses_api_agents.simple_agent.datasets=[]' ``` The two dataset-list overrides exclude CRITPT and HLE. Remove the corresponding final argument to include either benchmark in a **fresh** experiment. `EXPORT_TO_CSV=0` skips the optional exporter, whose Omniscience metric-key mismatch remains unresolved; evaluation JSON and final aggregate metrics are still written. ## Run command — SWE-bench Verified, post-merge 0.29 (30 minutes) Uses the same Ultra recipe, container, concurrency 24, and coupled P4/D4 allocation as Super, with the OpenCode agent and OpenSandbox configs. Run from the repository root with the existing OpenSandbox connection configured in `env.yaml` or the environment. The distinct experiment name keeps SWE-bench results separate; no CRITPT/HLE exclusions are needed because the Super config is not loaded. ```bash EXPERIMENT_NAME="nemotron-3-ultra-mtp3-c24-v0290-postmerge-swebench-verified-$(date -u +%Y%m%d-%H%M%S)" MODEL=/lustre/fsw/portfolios/llmservice/users/igitman/hf_models/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16 \ VLLM_CONFIG=benchmarks/nemotron_3.5_super/vllm_configs/nemotron_3_ultra.sh \ EXPERIMENT_NAME="$EXPERIMENT_NAME" \ ROLLOUTS_FPATH="results/$EXPERIMENT_NAME/resumable.jsonl" \ EXPORT_TO_CSV=0 \ NUM_PREFILL_NODES=4 \ NUM_DECODE_NODES=4 \ VLLM_PD_DEPLOYMENT_MODE=coupled \ VLLM_SLURM_SEGMENT=4 \ SBATCH_ACCOUNT=nemotron_rl_algo \ SBATCH_PARTITION=batch_long \ SBATCH_QOS=normal \ SBATCH_TIME=2-00:00:00 \ SBATCH_GRES=gpu:4 \ SBATCH_EXPORT=ALL \ CONTAINER="/lustre/fsw/portfolios/llmservice/users/fsiino/repos/Gym-inkling-tuning/results/vllm/vllm-openai:v0.29.0___super-vl-evals-2a3c65b-ultra-with-gym-b894cbe-20260914-202306.sqsh" \ MOUNTS="/lustre:/lustre,$(pwd -P)/env.yaml:/opt/Gym/env.yaml:x-create=file,$(pwd -P)/results:/opt/Gym/results,$(pwd -P)/benchmarks/nemotron_3.5_super/vllm_configs/nemotron_3_ultra.sh:/opt/Gym/benchmarks/nemotron_3.5_super/vllm_configs/nemotron_3_ultra.sh:ro" \ bash benchmarks/nemotron_3.5_super/sbatch_external_vllm.sh \ --config responses_api_models/vllm_model/configs/vllm_model.yaml \ --config benchmarks/swebench/verified/opencode.yaml \ --config nemo_gym/sandbox/providers/opensandbox/configs/opensandbox.yaml \ '++num_samples_in_parallel=24' \ '++resume_from_cache=true' ``` Each command reserves eight nodes / 32 GPUs; running both simultaneously requires 16 nodes / 64 GPUs. These are separate 30-minute validation jobs, not full-suite score runs. Check model/router readiness, live generation, tokens/sec/request, waiting, KV usage, and saved-output health; additionally check sandbox startup and agent activity for SWE-bench. Startup and sandbox preparation consume part of the allocation, so SWE-bench may save few completed attempts within this window. The launcher submits a separate job-scoped cleanup job for each evaluation. ## Command controls and resume | Control | Valid values | Why this command uses it | |---|---|---| | `VLLM_PD_DEPLOYMENT_MODE` | `independent` (default), `coupled` | Branch-added opt-in for multi-node tiers; Ultra requires `coupled` because a complete replica does not fit on one four-GPU node. | | `VLLM_SLURM_SEGMENT` | Unset or a positive integer | Branch-added control; overrides main's `SEGMENT`. If both are unset/empty, use all allocated nodes as one segment. `4` aligns each segment with a four-node tier, the placement used in successful Ultra runs. | | `SEGMENT` | Unset or a positive integer | Main's equivalent segmentation control, honored when `VLLM_SLURM_SEGMENT` is unset/empty. No need to set both. | | `SBATCH_TIME` | Slurm duration within account/partition limits | Branch makes the prior `04:00:00` default configurable. `00:30:00` bounds this tuning test; it is not enough for the full suite. | | `VLLM_USE_V2_MODEL_RUNNER` | Launcher now explicitly sets `0` | Main selects V1, which was faster in our tests. This no longer needs a command argument; submitting `1` will be overridden by the launcher. V1 is version-specific and deprecated, so future containers need revalidation. | | `SBATCH_EXPORT` | Slurm export setting; `ALL` here | Existing Slurm control; carries the run environment, including the fixed output path, into the allocation. | | `++num_samples_in_parallel` | Positive integer | Existing Gym concurrency control. `24` improved aggregate generation relative to `20` while averaging above 90 tokens/sec/request; it does not prove proportionally faster suite completion. | | `ROLLOUTS_FPATH` + `++resume_from_cache` | Fixed output JSONL path; `true` or `false` | Existing controls. Set a unique mounted results path and `true` on the first submission to preserve completed work across Slurm requeues. | For a **manual resume**, wait until the previous job stops, replace the timestamp-generating `EXPERIMENT_NAME` assignment with its exact previous experiment name, and rerun with the same fixed output path, model, recipe, container, datasets, and resume override. Preserve both `resumable.jsonl` and `resumable_materialized_inputs.jsonl`; the latter records the selected tasks. A Slurm requeue reuses the submitted environment without needing that manual edit. Interrupted, unsaved work may be repeated; neither control configures Slurm's requeue policy. Without `ROLLOUTS_FPATH`, the launcher chooses a new timestamped output path at each restart, so `++resume_from_cache=true` alone will not find the prior results. Without resume enabled, Gym may clear the selected output. For any new tuning configuration or dataset selection, use a fresh experiment/output path rather than mixing results with a previous run. ## Changes since review at `f656822f6` - **Hardcoded the tuned settings:** removed `ULTRA_*` switches and their validation branches. Prefill/decode memory utilization is `0.90/0.95`, batched-token limits are `16384/8192`, maximum sequences is `64`, and MTP drafts three extra tokens. Graph modes, copied inputs, and decode capture sizes are fixed in the recipe. - **Removed eager enforcement:** both tiers use `PIECEWISE` graphs with copied inputs; no `--enforce-eager` flag or eager fallback remains. - **Enabled prefix caching:** removed the old disabling flag and warning. The original multiple-local-block assertion did not recur in the subsequent full vLLM 0.27.1 run or the short 0.29 tests. This is not a claim that all cache warnings or output-quality problems are fixed. - **Applied async scheduling where supported by tuning:** enabled on prefill, disabled on decode. Decode async was retested on 0.29 in `7153011`; matching post-warmup durations gave 89.96 versus 95.55 tokens/sec/request with synchronous decode, approximately 6% slower. The reviewer recommendation was to use it if it helps, not require it on both tiers. - **Reused existing concurrency/resume controls:** removed `NUM_SAMPLES_IN_PARALLEL` and `RESUME_EVAL_ON_REQUEUE`. Commands now use Hydra's `++num_samples_in_parallel`, a fixed `ROLLOUTS_FPATH`, and `++resume_from_cache=true`. Launcher tests cover argument preservation and stable output paths across requeues and manual restarts. - **Reconciled the latest main launcher changes:** preserved main's V1 runner setting, router-default balancing thresholds, and `cpu-normal` cleanup QOS. Support both main's `SEGMENT` and our higher-priority `VLLM_SLURM_SEGMENT`, falling back to the calculated node count and emitting exactly one `--segment` argument. Coupled serving remains opt-in. --------- Signed-off-by: Frankie Siino <[email protected]>
…Response validation (#3413) ## What does this PR do? Normalizes LiteLLM native `/v1/responses` payloads prior to `NeMoGymResponse` validation. LiteLLM's responses transformations can return: - `usage.input_tokens_details: null` and `usage.output_tokens_details: null` - a reasoning item without `summary` - reasoning content typed as `output_text` instead of `reasoning_text` This PR: - Normalizes `usage.input_tokens_details` and `usage.output_tokens_details` to object dictionaries with `cached_tokens` and `reasoning_tokens` while preserving reported values. - Defaults missing reasoning `summary` to `[]`. - Changes `output_text` content in reasoning items to `reasoning_text`. - Adds regression unit tests verifying normalization of native response usage details and reasoning items. Closes #3405. ## Checklist - [x] I have read the [contributing guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup). - [x] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [x] Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable). - [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so CI lint/format/copyright pass). - [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check passes). Signed-off-by: Manohar Paturi <[email protected]> Co-authored-by: Manohar Paturi <[email protected]>
…#3549) Terminal-Bench 2.1 task images based on Debian Bullseye can fail package installation when their security repository references packages no longer available from the live mirror. Before `apt-get update`, sandbox setup now redirects the exact Bullseye security source to the signed Debian security snapshot from August 31, 2026. The source-specific expiry exception keeps that snapshot usable without disabling package signature verification. Other distributions and repository entries remain unchanged. Setup runs through `start_with_setup`, so preparation errors retain the existing sandbox cleanup behavior. Validation: - `pytest resources_servers/terminal_bench_2_1/tests/test_app.py -q`: 6 passed. - `pre-commit run --all-files`: passed. - Tests cover Bullseye replacement, unchanged Bookworm/Ubuntu sources, idempotency, setup ordering and error propagation. - No new model rollout was run for this PR; end-to-end benchmark validation remains pending. This fixes package bootstrap without changing task definitions or scoring. A separate issue is unnecessary for this narrowly scoped fix. Kept as a draft pending independent review and CI. Signed-off-by: Adam Rajfer <[email protected]>
## What does this PR do?
Adds experimental `manifest.yaml` metadata for 75 existing benchmark
implementations whose current configs can be represented without
changing their layout or runtime behavior.
Each manifest:
- marks the benchmark as experimental;
- records authors as GitHub handles;
- captures benchmark identity, integration profile, licensing, reward,
determinism, canonical split, and standard prompt configuration;
- mirrors the composition resolved from the existing config, including
the resources server, agent server, model server, and datasets.
This PR is intentionally manifest-only: it does not modify benchmark
configs, tests, or runtime code.
Thirteen config variants that would require directory restructuring or
compatibility wrapper configs are intentionally excluded:
- `apex25/config_with_system`
- `arxivmath_{0426,0526,0626}/config_with_system`
- `brokenarxiv_{0426,0526,0626}/config_with_system`
- `livecodebench/v{5_2408_2502,6_2408_2505}/{config,cascade}`
- `longbench_v2/config_n3_1m`
- `longcodebench/config_n3_1m`
## Validation
- `.venv/bin/python -m pytest
tests/unit_tests/test_environment_manifest.py -q` — 34 passed.
- Catalog validation — all 75 manifests load successfully, resolve
against their existing config, use GitHub-style author handles, and have
no composition mirror differences.
- `git diff --check origin/main...HEAD` — passed.
- Repository secrets detector — passed locally and in CI.
- DCO, lint, copyright, and pre-flight CI checks — passed.
## Rollouts
N/A. This PR adds declarative metadata only and does not change
benchmark configuration or runtime behavior.
## Compatibility and benchmark impact
None. Existing benchmark configs, selectors, execution paths, prompts,
datasets, and scoring behavior are unchanged.
## Checklist
- [x] I have read the [contributing
guidelines](https://github.com/NVIDIA-NeMo/Gym/blob/main/CONTRIBUTING.md).
- [x] The change is focused; unrelated "drive-by" edits are tracked as
separate issues/PRs.
- [x] Existing manifest tests pass locally; no test changes are required
for this metadata-only change.
- [x] Documentation changes are N/A; the manifests are the metadata
being added.
- [ ] `pre-commit run --all-files` was not run locally; the PR lint
check passes.
- [x] SPDX headers are N/A; no source files are added.
- [x] All commits have DCO sign-off, and the DCO check passes.
Signed-off-by: Rita Fernandes Neves <[email protected]>
## What does this PR do? Unbreaks `main` after #3535. Its 75 new `benchmarks/*/manifest.yaml` files each mirror their benchmark's `type: benchmark` dataset, so `_benchmark_config_paths`'s content-based prefilter (`_is_benchmark_config`) takes every manifest for a second config of the same benchmark. Manifests don't resolve as configs, so the listing drops them and `tests/unit_tests/test_benchmarks.py::TestDiscoverBenchmarksInDir::test_every_repo_benchmark_appears_in_listing` fails on `main`: ``` AssertionError: 218 benchmark config(s) discovered but only 143 appear in the listing ``` `#3535`'s own merge-queue run passed because it was queued against the previous base; the first PR queued after it (#3529) has been ejected twice with "failed status checks". Reproduced locally: fails on `main` (`9164de0e`), passes on its parent (`2581db97`). Fix: `_is_benchmark_config` rejects a `manifest.yaml` by name before looking at content, so the predicate states the whole definition of a benchmark config and every caller of the discovery inherits it. `nemo_gym/registry.py` already filtered the manifest out of the legacy benchmark listing for the same reason; that filter is now redundant and removed, and `MANIFEST_FILENAME` moves to `benchmarks.py` so both modules read one definition (registry imports benchmarks, not the other way round). ## Validation ``` python -m pytest tests/unit_tests/test_benchmarks.py tests/unit_tests/test_registry.py \ tests/unit_tests/test_environment_publication.py tests/unit_tests/test_environment_onboarding.py \ tests/unit_tests/test_environment_manifest.py # all pass, including test_every_repo_benchmark_appears_in_listing (218 == 218) pre-commit run --files nemo_gym/benchmarks.py nemo_gym/registry.py tests/unit_tests/test_benchmarks.py ``` New test `test_prefilter_rejects_the_benchmarks_manifest`: a `config.yaml` and a `manifest.yaml` declaring the same dataset → the prefilter rejects the manifest and only the config is discovered. ## Rollouts N/A — discovery only. ## Compatibility and benchmark impact None to configs or scoring. `gym list benchmarks` output is unchanged from before #3535; the catalog (`registry.py`) reads manifests through its own path as before. ## Checklist - [x] I have read the [contributing guidelines](https://github.com/NVIDIA-NeMo/Gym/blob/main/CONTRIBUTING.md). - [x] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [x] Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable). - [x] Documentation added or updated, or N/A with justification — docstring of `_benchmark_config_paths` explains the exclusion. - [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so CI lint/format checks pass). - [x] New source files include the required Apache-2.0 SPDX header — no new files. - [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check passes). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Ingo Guehring <[email protected]>
…n record (#3529) ## What does this PR do? `gym-job.json` records `gym_version`, which repeats across every commit between two version bumps. A reader that needs to reinstall the exact Gym that wrote a record — to recompose the submission's config with `gym eval submit --resolve-only` (#3524) and compare it against what it expects — cannot pin that from the version alone. This adds `SubmissionRecord.gym_commit`: the commit of the nemo-gym that wrote the record. - A git install (`pip install git+…@<sha>`) records the commit in the distribution's PEP 610 `direct_url.json` as `vcs_info.commit_id`; that is used when present. - Otherwise the checkout the running `nemo_gym` package is tracked in is asked directly (`git ls-files --error-unmatch` on the package, then `rev-parse HEAD` / `status --porcelain`): its HEAD when clean, `<HEAD>-dirty` when it has uncommitted changes. This does not depend on install metadata at all, so an editable install whose venv lacks `nemo-gym` dist-info (uv can produce that) and a plain source tree on `sys.path` both work. - A package no checkout tracks — a wheel in `site-packages`, even when the venv sits inside a clone — yields `None`; so does a missing `git`. Every `None` is logged with its reason. An index wheel needs no commit anyway: a published version is immutable, so `gym_version` already identifies it. Added with a default, as `jobs.py`'s compatibility rule requires of a same-version change: records written before this still load under `schema_version: 1`. `jobs.py` stays executor-agnostic (no new imports from `executors/`). Consumer: NVIDIA's eval-factory certification layer (Evergreen) pins the Gym it recomposes with from this field instead of from its own toolchain pin. ## Validation ``` .venv/bin/python -m pytest tests/unit_tests/test_orchestration_jobs.py tests/unit_tests/test_slurm_executor.py tests/unit_tests/test_cli_eval_submit.py # 62 passed pre-commit run --files nemo_gym/orchestration/jobs.py nemo_gym/orchestration/executors/slurm.py tests/unit_tests/test_orchestration_jobs.py # all hooks pass ``` Against real installs: in a venv created with `pip install "nemo-gym @ git+https://github.com/NVIDIA-NeMo/gym.git@c41584d1…"`, `direct_url.json` reads `{"vcs_info": {"commit_id": "c41584d1…"}}` and the helper returns it; in this editable checkout with local edits it returns `<HEAD>-dirty`, and the same source tree on `PYTHONPATH` in a venv with no `nemo-gym` dist-info (where `distribution("nemo-gym")` raises `PackageNotFoundError`) returns the same. End to end on a Slurm cluster: `pip install "nemo-gym @ git+…gym.git@4636cd3…"` into a fresh venv, `gym eval submit` a real config (job cancelled right after enqueue), `gym-job.json` reads `"gym_commit": "4636cd35d33675551bfb6e3ba91295a1b03874fe"`. Install scenarios exercised for real against this branch's head (`29bf4f61`), beyond the unit tests: | How nemo-gym is running | `direct_url.json` | `gym_commit` | |---|---|---| | `pip install "nemo-gym @ git+…@29bf4f61"` into a fresh venv on a Slurm login node, real `gym eval submit` (job cancelled at enqueue) | `vcs_info.commit_id` | `29bf4f61…` | | `uv pip install -e <clean clone>` | `dir_info.editable` | `29bf4f61…` | | same editable venv, checkout with an uncommitted edit | `dir_info.editable` | `29bf4f61…-dirty` | | clean clone on `PYTHONPATH`, no nemo-gym dist-info at all (`distribution()` raises) | — | `29bf4f61…` | | same, checkout dirty | — | `29bf4f61…-dirty` | | wheel built from the clone, installed into a `.venv` **inside** the clone | `archive_info` | `None` (not tracked in a checkout) | | clone on `PYTHONPATH`, `git` not on `PATH` | — | `None` (git is not available) | ## Rollouts N/A — orchestration metadata only; no environment or agent code. ## Compatibility and benchmark impact Additive, defaulted field on `gym-job.json`; no schema version bump needed and older records load unchanged. No benchmark-result effect. ## Checklist - [x] I have read the [contributing guidelines](https://github.com/NVIDIA-NeMo/Gym/blob/main/CONTRIBUTING.md). - [x] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [x] Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable). - [x] Documentation added or updated, or N/A with justification — the field is documented in `SubmissionRecord`'s docstring, where the other fields are. - [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so CI lint/format checks pass). - [x] New source files include the required Apache-2.0 SPDX header — no new files. - [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check passes). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Ingo Guehring <[email protected]>
<!-- Thanks for contributing to NeMo Gym! Please fill out the sections below. --> ## What does this PR do? <!-- Briefly describe the change and the motivation. Link any related issue, e.g. "Closes #123". --> ## Validation <!-- List the exact commands and checks run against the final diff. --> ## Rollouts <!-- Include representative rollout evidence for behavior-changing environment or agent code, or a justified N/A. --> ## Compatibility and benchmark impact <!-- Describe compatibility, migration, configuration, or benchmark-result effects, or state "None". --> ## Checklist - [ ] I have read the [contributing guidelines](https://github.com/NVIDIA-NeMo/Gym/blob/main/CONTRIBUTING.md). - [ ] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [ ] Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable). - [ ] Documentation added or updated, or N/A with justification. - [ ] Pre-commit checks pass locally (`pre-commit run --all-files`) (so CI lint/format checks pass). - [ ] New source files include the required Apache-2.0 SPDX header. - [ ] All commits have DCO sign-off (`git commit -s`) (so the DCO check passes). --------- Signed-off-by: Brian Yu <[email protected]>
…03 (#3571) ## What does this PR do? `NeMoGymAsyncOpenAI._request_with_retry` treated every 429 as a transient rate limit. When the upstream key was actually spent (`budget_exceeded` / `insufficient_quota`), each request burned all its retries against a dead endpoint, and every later judge or model call on the same client did the same. In long eval jobs this meant hours of rollouts silently scored against a key that would never answer. This PR adds a per-client fail-fast latch to the shared OpenAI client: - A 429 whose parsed `error.code` / `error.type` is `budget_exceeded` or `insufficient_quota` trips the client. Generic "quota exceeded" wording (used by per-minute limits that recover) still retries as before. - A 401/403 whose body names an invalid key (`invalid_api_key`, `invalid_api_token`, `authentication_error`, or "invalid/incorrect api key" text) also trips the client. Other 401/403 responses are returned once, unchanged from today. - Once tripped, every subsequent `_request` / `_request_with_retry` call on that client raises `PermanentEndpointError` without touching the wire. In-flight retry loops re-check the latch before their next attempt, so sibling tasks stop as soon as one trips. - `PermanentEndpointError` subclasses `aiohttp.ClientResponseError`, so existing `except ClientResponseError` handlers (for example the judge paths that read `.status`) keep working. Each raise builds a fresh exception instead of re-raising a cached one, so rejected requests are not retained. - `server_utils.raise_for_status` accepts pre-read `content`, because the retry loop now reads the body before deciding whether to retry. This lets the final attempt raise with the real error body instead of an already-consumed stream. - The `max_http_attempts` row in the OpenAI model-server docs now describes the retryable set and the fail-fast cases accurately. The latch is per `NeMoGymAsyncOpenAI` instance. Session pinning / failover across multiple model-server instances is out of scope here. No GitHub issue: this came out of an internal eval run where a spent inference key was retried for the remainder of the job. Reviewed and approved internally before being moved here. ## Validation Run against the final diff in this branch: ``` uv run --extra dev pytest tests/unit_tests/test_openai_utils.py tests/unit_tests/test_server_utils.py -q # 318 passed uv run pre-commit run --files fern/versions/latest/pages/model-server/openai.mdx nemo_gym/openai_utils.py nemo_gym/server_utils.py tests/unit_tests/test_openai_utils.py tests/unit_tests/test_server_utils.py # all hooks pass (ruff-format made one blank-line fix, folded into the second commit) ``` New tests cover: the quota and auth body classifiers (parametrized over real OpenAI / inference-gateway error shapes), fail-fast on spent-key 429 and invalid-key 401/403, generic-quota and transient 429s still retrying, exhausted transient 429 raising without tripping, auth errors without a key marker being returned once, requests skipping the wire after a trip, an in-flight retry stopping after a sibling trips, `create_chat_completion` surfacing the permanent error's `.status`, and `raise_for_status` accepting prefetched content. ## Rollouts N/A. This changes HTTP retry behavior in the shared client, not environment or agent logic. The behavior is exercised end to end in unit tests with mocked upstream responses. Not exercised against a live spent key. ## Compatibility and benchmark impact - No config changes. `max_http_attempts` semantics are unchanged for transient errors. - Behavior change: after a spent-key or invalid-key response, later calls on that client raise `PermanentEndpointError` (a `ClientResponseError` with the original `.status`) immediately instead of retrying. Callers that previously saw the 429/401/403 after exhausting retries now see it on the first request and without the retry delay. - No benchmark-result impact for healthy endpoints. ## Checklist - [x] I have read the [contributing guidelines](https://github.com/NVIDIA-NeMo/Gym/blob/main/CONTRIBUTING.md). - [x] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [x] Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable). - [x] Documentation added or updated, or N/A with justification. - [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so CI lint/format checks pass). - [x] New source files include the required Apache-2.0 SPDX header. (No new files.) - [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check passes). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: FrontierJam Agent <[email protected]> Signed-off-by: Grzegorz Chlebus <[email protected]> Co-authored-by: FrontierJam Agent <[email protected]> Co-authored-by: Claude Code <[email protected]>
## What does this PR do? Adds a strict offline exporter from completed Gym `ng_trajectory` v1.0 rollouts to ATIF v1.7. It writes one ATIF file per rollout plus a SHA-256-pinned manifest that Gym's ATIF reverification path can consume. Together, #2737 and #2767 establish a file-based interoperability path between NeMo Relay and NeMo Gym. Relay-exported ATIF trajectories can be evaluated in Gym, while Gym-native trajectories can be exported to the same ATIF format for downstream consumers. This does not couple the Relay and Gym runtimes or add Relay as a Gym dependency. This is PR 2 of a two-PR sequence. #2737 owns ATIF ingress and the shared ATIF schema/JSON boundary; this PR owns Gym-to-ATIF egress. Related to #2468. ## Before Gym could store normalized rollout trajectories but could not export them in a portable trajectory format. ## After ```bash gym eval export \ --format atif \ --rollouts results/rollouts.jsonl \ --output-dir results/atif \ --session-id eval-2026-08-25 \ --agent-version 1.2.3 ``` The exporter maps Gym's normalized trajectory, not provider-native payloads. Raw provider request and response copies are retained opaquely in ATIF extension metadata; they are never parsed to fill gaps in the normalized record. ## Initial contract Supported: - one completed root invocation and one initial system/user phase; - exactly one captured model call per agent turn; - text, reasoning, generic function calls, and correlated text results; - normalized turn/model/token/timing/status evidence; and - task/rollout identity plus a hash-pinned manifest. Rejected rather than guessed or dropped: - evidence gaps, subagents, later user/system turns, and multimodal content; - incomplete, failed, or ambiguously correlated model/tool calls; - unsupported Responses item families or namespaced calls; - training token IDs, log probabilities, and routed-expert metadata; and - non-standard JSON. The exporter writes each known per-step usage field without inventing missing values. `reasoning_tokens` and `total_tokens` use the same step-level ATIF extension shape as Relay. A final prompt-, completion-, or cached-token aggregate is emitted only when every captured model call reports that field; an unavailable value is never counted as zero. An export with partial usage can therefore be valid ATIF for another consumer while remaining ineligible for Gym's strict reverify path. Gym reverify requires complete per-step prompt/completion counts whenever supported usage exists because one verifier request cannot represent partial standard usage. This asymmetry is deliberate. The exported `extra.nemo_gym.conversion.status=complete` means every field present in the supported normalized `ng_trajectory` profile was represented without guessing. It does not certify opaque provider request or response copies retained as provenance. ## Out of scope No ATOF parsing, Relay/NAT dependency, live instrumentation, provider-payload reconstruction, or best-effort export of unsupported structural or content fields is included. Preserving known step-level usage while omitting an unprovable aggregate is exact representation, not best-effort conversion. ## Review order This is the egress follow-on to merged PR #2737. Current `main` is merged into this branch, `atif_v1_7.py` has left the diff, and `atif_json.py` retains only the small strict JSON equality helper used by the exporter. The exporter test now exercises the combined egress-to-ingress path through #2737's manifest loader and reverify projection. | Review area | Files | What to verify | | --- | --- | --- | | Export contract | `nemo_gym/atif_export.py` | Exact normalized-trajectory mapping, rejection boundaries, batch atomicity, and manifest hashes | | Shared boundary delta | `nemo_gym/atif_json.py` | Strict JSON equality used by export validation | | Wiring | `nemo_gym/cli/eval.py`, `nemo_gym/cli/main.py`, docs | One-command offline export and documented scope | | Evidence | `tests/unit_tests/test_atif_export.py`, CLI tests | Contract, failure, hash, and round-trip coverage | Suggested pass: review the exporter first, then its small shared-boundary delta and wiring. The test file is intentionally large because unsupported shapes fail closed. ## Validation - Focused exporter, rollout-reverification, and CLI suites: **609 passed**. - Repository-wide pre-commit and `git diff --check`: passed. - Combined local core+sandbox coverage: **95.08%**, above the 95% gate. - The exact cross-PR test exports two Gym trajectories, loads the generated manifest through #2737's loader, and runs the real reverify projection while checking identity, usage, tool correlation, reasoning, and final output. - Manifest SHA verification succeeded, tampering was rejected, parallel tool results were correlated by call ID rather than arrival order, usage survived, and native versus round-tripped MCQA verification both returned reward `1.0`. The complete trusted Linux matrix remains pending on the exact pushed head. A local Enroot cleanup test is Linux-specific and cannot run on macOS because `/proc` is absent. The earlier Codex → Relay → ATIF → Gym live qualification remains evidence for #2737; this offline exporter PR does not claim another provider run. ## Checklist - [x] I have read the contributing guidelines. - [x] Tests were added and pass locally. - [x] Commits have DCO sign-off. --------- Signed-off-by: Alex Fournier <[email protected]>
## summary
- add structured configuration for selecting a nooa agent, entrypoint,
constructor settings, and task-field mappings
- validate agent imports, constructors, asynchronous entrypoints, and
argument mappings when the server starts
- restrict mappings to agent-visible data and provide safe transforms
for common responses api inputs
## data flow
```mermaid
flowchart LR
yaml["nooa yaml config"] --> config["NOOAAgentConfig<br/>NOOAInvocationConfig<br/>NOOAArgumentBinding"]
config --> validate["validate_invocation()"]
validate --> symbols["validated agent_class<br/>and entrypoint"]
row["complete gym row"] --> materialize["materialize_arguments()"]
materialize --> gate{"validate_source_path()"}
gate -->|"allowed source"| resolve["resolve_source()"]
resolve --> transform["get_transform()"]
transform --> kwargs["entrypoint kwargs"]
gate -->|"verifier or routing field"| reject["reject mapping"]
```
Closes #2566
---------
Signed-off-by: Nikhil Deshmudre <[email protected]>
## What does this PR do? Releases Gymnasium subclass state when an episode terminates or is truncated. - Adds one idempotent `_cleanup_session()` path used by terminal release and reset replacement. - Removes Sokoban and Tetris state and closes each environment at most once. - Removes multi-turn example counters together with base session state. - Keeps cleanup safe when called repeatedly or concurrently. - Leaves a single helper for the future #2609 `release_session()` hook to delegate to. Closes #3157. ## Validation - `uv run --extra dev pytest resources_servers/gymnasium/tests/test_app.py resources_servers/example_multi_turn_gymnasium/tests/test_app.py -q` — 15 passed. - `uv run gym env test --resources-server grl_sokoban` — 9 passed. - `uv run gym env test --resources-server grl_tetris` — 8 passed. - Tests cover terminal and truncated episodes, reset replacement, repeated concurrent cleanup, state removal, and exactly-once environment closure. - `uv run pre-commit run --all-files` — passed. ## Checklist - [x] I have read the [contributing guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup). - [x] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [x] Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable). - [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so CI lint/format/copyright pass). - [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check passes). --------- Signed-off-by: Abhishree <[email protected]>
## What does this PR do? Adds the **executable stratum of SciCodePile** as a NeMo Gym benchmark: 200 scientific code-generation tasks harvested from 37,737 public computational-science repositories, each shipping its own test. - Paper: https://arxiv.org/abs/2607.19104 - Dataset: https://huggingface.co/datasets/SciCodePile/SciCode-Runnable-Benchmark-Reviewed - Upstream org: https://huggingface.co/SciCodePile Each task's `test` defines `check(candidate)`. The server looks up `entry_point` and calls `check` with it. Reward is binary. **Not the same artifact as the existing `scicode` benchmark** — different source (`SciCode1/SciCode` vs `SciCodePile`), size (65 problems / 288 sub-steps vs 200 single-shot tasks), and structure (multi-step agent vs single-turn generation). Checking coverage by name alone will read one as the other. ### Verification design `setup_code`, the model's code, and `test` are compiled and executed as **three separate units sharing one namespace** — the `__dict__` of a real module registered in `sys.modules`. The separation is load-bearing, not stylistic: concatenated, a trailing decorator in the model's output binds to the test's own `def check` and replaces the assertions (a solution returning `None` then passed all 200 tasks), and `from __future__` imports are pushed off the top of the file. Execution is out-of-process with a throwaway CWD per task (all 200 tasks carry the upstream `env_sensitive` flag and 117 carry `globals_patch`, so tests mutate global state), an `RLIMIT_AS` cap, pinned BLAS thread pools, and a process-group kill on timeout. **It is not a security sandbox** — see the server README. The dataset revision is pinned, so the benchmark is a fixed protocol rather than whatever the Hub serves today. ### Verification The strongest correctness signal is model-independent: - **All 200 upstream `canonical_solution` values pass** through the runner. This validates the harness with no model involved and cannot be confounded by model quality. Re-run it whenever the runner changes. - Negative controls over **all 200** tasks: a raising implementation fails 200/200; unparseable code errors 200/200; a stub returning `None` fails 197/200; a renamed function and an empty answer each score `entry_point_missing` 199/200. - Two caveats the full-set controls surfaced, both documented in the server README: `alignment/python/144`, `178` and `273` **pass with a stub returning `None`** (their tests only assert the result is `None` or any object — worth ~1.5pp of any score), and `alignment/python/76` defines its own entry point in `setup_code`. - 84 tests, including mutation-checked regression tests for every issue raised in review. ### Prompting The upstream `prompt` is passed through unmodified with **no system message**. That is the only prompting the paper specifies: zero-shot on "HumanEval-style task prompts, each consisting of a function signature and its natural-language specification". The paper publishes no system prompt, no decoding parameters, and no per-task sample count. This costs some tasks where a chat model answers conversationally instead of writing code. Note that the statuses do **not** cleanly isolate those non-attempts: with no fence the extractor returns the whole response, so a refusal compiles and lands as `error`/`syntax_error`, the same status as a real attempt with a syntax error. Counting non-attempts means reading the text. ### Comparison with the published figures Upstream's Table 3 reports Pass@1 / Pass@5 for 15 models. GPT-5.4-mini — the strongest model in that table — was run through this server on all 200 tasks with the shipped config (upstream prompt verbatim, no system message, `max_output_tokens` 131072), 5 repeats: | Model | Metric | Upstream | This server | 95% CI (ours) | | --- | --- | ---: | ---: | :---: | | GPT-5.4-mini | Pass@1 | 12.30% | 9.30% (`pass@1[avg-of-5]`) | [5.80%, 13.20%] | | GPT-5.4-mini | Pass@5 | 15.50% | 13.00% | | The interval describes the precision of our estimate — a bootstrap resampling tasks rather than rollouts, because repeats are clustered within a task. It is not a comparison with upstream: it is wide enough to contain their figure, but containment is not a test, and no test is available here. `harness_failure` was **0.0%** across all 1000 rollouts — no dataset-owned or runner-internal fault fired, so the whole gap is model behaviour rather than harness noise. No test of "ours versus theirs" is offered, because the data to do one does not exist publicly. The paper reports a rounded aggregate with no per-task outcomes and no per-task sample count — 12.30% of 200 is 24.6, so the figure is not a count of tasks and cannot be treated as one. Since both runs cover the same 200 tasks, a paired or cluster-aware analysis would be appropriate if upstream's per-task outcomes were ever published; an independent two-sample test on reconstructed counts would not be. Exact reproduction is not possible from the paper as written: it publishes neither the decoding parameters nor the number of samples per task, both of which the HumanEval Pass@k estimator depends on. The server README therefore records only the paper-reported figures and makes no reproduction claim. **Treat model ranking on this benchmark with caution at these score levels.** The paper's own table puts GPT-5 (5.70%) *below* GPT-4o (7.50%). ### Notes - `example.jsonl` ships 5 rows with `example_metrics.json` and `example_rollouts.jsonl`; `gym env test --resources-server scicodepile +should_validate_data=true` passes. - `code_extraction.py` is duplicated from the bigcodebench server to hold score parity; nothing enforces the two stay identical, which the module docstring states. ## Checklist - [x] I have read the [contributing guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup). - [x] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [x] Tests added or updated and pass locally (84 passed), plus a 200/200 canonical-solution validation. - [x] Pre-commit checks pass locally. - [x] All commits have DCO sign-off (`git commit -s`). --------- Signed-off-by: Rima Shahbazyan <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
## What does this PR do? Adds **FukuyamaBench** to NeMo Gym as both an **environment** and a **benchmark**: step-by-step organic reaction mechanism prediction over 241 graduate- and research-level problems. Given atom-mapped starting reactants and reaction conditions, the model must predict the sequence of elementary mechanism steps through to the final product. Scoring is **fully deterministic** — canonical-SMILES comparison via RDKit against expert-curated mechanisms, matched at ordered checkpoints. There is no judge model and no external service in the scoring path. The environment covers upstream's **sets B and C only**. Set A is reachable via `--sets A` but is a materially easier tier. Tier results are reported separately: the headline metrics are per-tier and the pooled cross-tier reward is removed from them — see "Metrics are reported per tier" below. ## Benchmark identity | | | | --- | --- | | Paper | [arXiv:2607.12771](https://arxiv.org/abs/2607.12771) — "Learning Mechanistic Reasoning for Chemical Reactions with Large Language Models" | | Upstream repo | [HaCTang/ReactionMechanismReasoning](https://github.com/HaCTang/ReactionMechanismReasoning) (Apache-2.0) | | Pinned revision | [`63bb79f912f0b2de593996b80ffeea894f6f1a59`](https://github.com/HaCTang/ReactionMechanismReasoning/tree/63bb79f912f0b2de593996b80ffeea894f6f1a59) | | Hugging Face | **No HF dataset exists for the eval split.** The cases live only as a directory tree in the GitHub repo; `prepare.py` fetches the pinned tarball. The HF repos the paper references hold SFT/RL training data and are not used here. | | Source material | *Fukuyama Mechanism Book*, Kagaku-Dojin, 2005, ISBN 9784759810455 | | Size | 319 upstream (A=78, B=131, C=110); this environment uses B+C = **241** | ### Published baselines — Table 2, pathway & product prediction Top-1 / 3 / 5 / 8, the task this environment implements: | Model | Set B | Set C | | --- | --- | --- | | Gemini-3.0-Pro | **7.8** / 10.7 / 12.3 / 13.7 | **1.0** / 1.2 / 1.5 / 1.8 | | GPT-5 | 4.3 / 5.2 / 5.9 / 6.9 | 0.9 / 0.9 / 0.9 / 0.9 | | Qwen3-235B-A22B | 4.0 / 4.7 / 5.1 / 5.3 | 0.2 / 0.6 / 0.8 / 0.9 | | ChemDFM-R-14B | 3.4 / 4.1 / 4.4 / 4.6 | 0.6 / 0.9 / 0.9 / 0.9 | | FlowER | 0.8 / 1.5 / 2.3 / 2.3 | 0.0 / 0.0 / 0.0 / 0.0 | ## Task and scoring Upstream defines three tasks; this implements **pathway & product prediction**, the paper's headline task and the only one upstream ships an inference harness for. The model receives the starting state and conditions but *not* the final product, and emits a JSON array of steps each carrying a `product_smiles`. Scoring walks the case's **checkpoints** in order. A checkpoint is a group of gold step IDs that are mutually acceptable at that point; upstream builds them so bond-topology changes and functional-group transformations are checkpoints while consecutive trivial proton transfers merge, so there are usually fewer checkpoints than mechanism steps. Products compare as canonical-SMILES sets after atom mapping is stripped. The scan moves **forward only** and consumes a matched step, which lets a model predict finer-grained steps than gold without penalty — the reason checkpoints exist at all. **Reward is all-or-nothing**: 1.0 only if every checkpoint matched. Because a failed checkpoint exhausts the cursor, one miss fails every later checkpoint. `checkpoint_accuracy` is reported as a partial-credit diagnostic, not the reward. Under `lenient` (default, matching upstream) a predicted product set that is a non-empty subset of gold counts as a match, crediting a model that names the main product but omits a leaving group. `--strict` requires exact set equality. ## Metrics are reported per tier `compute_metrics` emits `B/...` and `C/...` keys keyed on `case_set`, and `get_key_metrics` promotes those while **dropping the pooled `mean/reward`**. Both halves are load-bearing. The inherited selection keeps every `mean/*` key, so emitting tier metrics alone still leaves `mean/reward` as the headline consumers read — and since published B and C baselines differ by close to an order of magnitude, that cross-tier average describes no benchmark anyone reports. To be precise about the contract: the pooled reward is removed from `key_metrics`, the headline set. The shared aggregator still records it inside `agent_metrics` by design, so it exists in the aggregate and is simply not presented as a result. ### The benchmark entry supplies the published metric shape `benchmarks/fukuyamabench/` registers the environment as a benchmark and sets **`num_repeats: 8`**. Upstream reports pass@k for k ∈ {1, 3, 5, 8}, which needs at least eight draws per case; the environment config alone defaults to a single draw, which reports a different quantity from the published one. Verified end to end on a three-case slice: 24 rollouts (8 per case), and the aggregate emitted the full `B/pass@1` … `B/pass@8` family, per tier, with the pooled `mean/reward` still absent from `key_metrics`. So a run of this benchmark produces the two columns upstream publishes rather than a single-draw mean. Its `prepare.py` delegates to the environment's preparation script rather than duplicating it, so the benchmark split comes from the same tested path — including the manifest check that refuses to write a short corpus. The split itself is not committed and the dataset is declared `TBD`, consistent with the open rights gate below. ## Three deliberate divergences from upstream Each fixes a case upstream's scorer cannot handle correctly, and each was found by testing rather than by reading code. **1. Gold products are split on `.` as predictions already were.** Upstream splits only the prediction side, so a gold entry written as one dotted string can never be matched by a model writing the same species. Worth 6 of 241 cases. **2. Organometallic gold products are reparsed without valence checking.** RDKit's valence model rejects ligand counts ordinary for Rh, Cr, Ti and Mo, so those species fail the default parse, and unparseable gold makes its checkpoint unmatchable. `canonical_smiles` retries with everything except `SANITIZE_PROPERTIES`, preserving ring and aromaticity perception. Worth the remaining 5 cases (`B042`, `B127`, `C069`, `C081`, `C093`). The retry is a fallback, not the default: the 1,716 strictly-parseable species canonicalise unchanged, 17 species are recovered, and the distinct canonical-form count rises by exactly 17 — so nothing is merged and no false-match risk is introduced. **3. A prediction containing an invalid component fails.** Upstream drops components it cannot read before comparing, so the correct product plus one malformed fragment scored an exact match — under `--strict` too, which made strict mode mean something other than set equality and paid reward for output the model never wrote validly. This covers both unparseable SMILES and list members that are not a supported product representation at all (`["CCO", null]`). Gold is unaffected, so this cannot mask a data problem. Divergence 1 and divergence 2 *on the gold side* add matches. But divergence 2 also applies to predictions, where it can **remove** a match: a species upstream silently discards as unparseable is retained here, so a prediction upstream scored as a subset of gold may no longer be one. Divergence 3 only ever removes credit. Measured on real output the net is slightly **fewer** matches than upstream — see "Scorer agreement". All three are documented at their call sites. ## Verification A published-number match is unavailable for reasons that are upstream's (see "Why reproduction is not claimed"), so correctness is argued **model-free**, which is a stronger signal for harness validity because it cannot be confounded by model quality. Run from the repository root: ```bash python resources_servers/fukuyamabench/scripts/prepare_fukuyamabench.py \ --output /tmp/val.jsonl ``` → `Wrote 241 rows` (B=131, C=110). Completeness is measured over cases that actually **loaded**, not directories that exist, and nothing is written until the corpus validates — so a truncated download, an unreadable case file, or an unrecognised set name fails closed instead of leaving a short split on disk. - **Gold-as-prediction: 241/241.** Every case's gold pathway, fed back as a prediction, scores 1.0. - **Negative controls, 0 exact matches each:** empty pathway (241), wrong-but-valid chemistry (241), wholly unparseable SMILES (241), gold pathway reversed (**233** — the cases with ≥2 checkpoints, the only ones where order can differ). These controls cover named failure classes; they are not proof over every possible wrong output. Divergence 3 above is exactly a wrong-output class none of them caught, which is why it is separately tested. ```bash gym env test --resources-server fukuyamabench +should_validate_data=true ``` → 62 passed; `The data for resources_servers/fukuyamabench has been successfully validated!` Coverage over `app.py` / `metrics.py` / `task_data.py` is **97%** (app 99, metrics 95, task_data 100), meeting AGENTS.md's ≥96% requirement — note that is stricter than `pyproject.toml`'s `fail_under = 95.0`. What remains uncovered is the `run_webserver()` entrypoint and three defensive RDKit `except` branches. Real model rollouts were collected and inspected during development; the tracked five-row example rollouts come from that work. Measured results are in "Comparison with the published figures" below. ## Comparison with the published figures To compare against upstream's own number rather than against our reimplementation of it, **upstream's harness was run directly** — their `run_infer_pathway.py` for inference and `eval_infer_pathway.py` for scoring, at the pinned revision. The only modification was a one-line change to the model identifier, since the endpoint used does not serve the bare upstream name; the base URL came from the OpenAI SDK's own environment variable. On sampling: the current pinned harness computes a per-draw temperature but its OpenAI path never sends it — only `model` and `messages` are passed — so this run used the endpoint defaults observed for this run. That describes the *current public harness*, not the published run: the evaluated commit is unavailable and the paper never reported its sampling configuration, so no claim of identity with it is made. GPT-5, Set B, `--sample_size 8`: 131 cases, **1,048 rollouts, 0 API errors**, 5 extraction errors (0.5%). These figures are **author-reported** and have not yet been verified by an authorized reviewer. The evidence record on SCI2-64 identifies eight artifacts by SHA-256 — the raw run, the upstream scorer output, the candidate scorer and paired-audit outputs, the one-line harness patch and the three analysis scripts — with the exact commands and the Python/RDKit/pytest versions. Every reported number is deterministically derivable from the digested raw run plus the digested scripts. The artifacts themselves are held in a restricted location and are deliberately not published here, since the run file carries external-execution metadata and service identifiers. **Reviewer access is still being arranged**: the artifacts are not yet in a durable permission-scoped store, so the record identifies them but does not yet make them retrievable. Request access via SCI2-64 rather than asking for outputs in this thread. | | pass@1 | pass@3 | pass@5 | pass@8 | | --- | ---: | ---: | ---: | ---: | | Upstream published | 4.3% | 5.2% | 5.9% | 6.9% | | This run (upstream harness + upstream scorer) | 2.8% | 4.9% | 5.7% | 6.1% | The run lands below at pass@1 and converges as k rises. Reported descriptively: a 95% bootstrap interval on this run's pass@1, resampling whole cases (5,000 resamples, seed 0), is **[0.9%, 4.9%]**, which overlaps the published 4.3%. Its estimand is the case-composition variability of *this* run's estimate over a fixed 131-case benchmark — it does not simulate a second stochastic inference run, and containment of a published point is not a hypothesis test. No formal comparison is available at all: the paper reports rounded aggregates with no per-case outcomes and no evaluated configuration, so neither a paired nor a two-sample test can be validly constructed. The difference between the two rows is **inconclusive**. ### Scorer agreement — paired, per output Aggregate proximity alone cannot establish agreement, since opposite per-output disagreements can cancel. So both scorers were run over **the same 1,048 outputs** and compared **per output**: | Outcome | Count | | --- | ---: | | Both correct | 27 | | Both incorrect | 1,014 | | Upstream correct, this server not | **2** | | This server correct, upstream not | **0** | | Unscorable by either (extraction) | 5 | | **Agreement** | **1,041 / 1,043 = 99.81%** | Both discordances are attributable to a documented divergence, individually checked: - One case: the prediction contained a component RDKit cannot read. Upstream dropped it and matched on the remainder; this server rejects it (divergence 3). - One case: the prediction contained a species upstream discards as unparseable but this server's permissive retry accepts. Retaining it makes the prediction no longer a subset of gold, so the lenient match upstream granted does not apply (divergence 2). The resulting aggregates: | | pass@1 | pass@3 | pass@5 | pass@8 | | --- | ---: | ---: | ---: | ---: | | Upstream scorer | 2.8% | 4.9% | 5.7% | 6.1% | | This server's scorer | 2.6% | 4.6% | 5.5% | 6.1% | Note the direction: this scorer is marginally **stricter** on real model output, not more generous — both discordances go that way. Divergences 1 and 2 add matches on the *gold* side but fire only on gold-side defects in 11 cases, and divergence 2 applied to *predictions* can remove a match by retaining a species upstream silently discarded. Divergence 3 only ever removes credit. The net is slightly fewer matches. ### Why this is still not called a reproduction Even matching the harness, scorer, parameters and estimator, four differences remain and none is removable: 1. The paper states its results correspond to commit `7c1cb69`, which **does not exist** in the public repo (`GET /commits/7c1cb69` → 422). The evaluated code and data state is unrecoverable; this pins current `main` as a proxy. 2. The model was reached through a different route than upstream used, and the served snapshot may differ from theirs. 3. The paper never states the sampling parameters behind its table — upstream's code passes none, so "API defaults" is inferred from the code, not documented. 4. `--workers` was raised for wall-clock; this changes scheduling only, not the requests. Treat the table above as a **comparison**, not a reproduction, and read model ranking at these score levels with caution. ## Data and licensing - **Code**: Apache-2.0. `metrics.py` is a port of upstream's Apache-2.0 scorer and the prompt constants are copied from its Apache-2.0 prompt file — the user template byte-identical, the system prompt content-preserving with trailing whitespace stripped by this repository's hook. Recorded in `ATTRIBUTIONS.md`. - **No benchmark data is redistributed.** `prepare.py` downloads at runtime. `data/example.jsonl` is generated from five **hand-authored synthetic mechanisms** in `tests/fixtures/synthetic_mechanisms/` (aldol, SN2, E1, acid-catalysed hydration, ester saponification), emitted in the upstream directory layout and passed through the same `prepare.py` path. ## Dependencies The scorer needs a chemical-graph parser and canonical-SMILES writer; the standard library has neither. **RDKit is selected** — it is the toolkit upstream's scorer uses (so parity is a property of the choice), is BSD-3-Clause, ships CPython 3.13 wheels, is on conda-forge, and depends only on NumPy and Pillow. **Open Babel 3.2.1** is the strongest alternative and supports canonical SMILES on Python 3.13, but is **GPL-2.0**, which CONTRIBUTING forbids introducing into the main tree. Version `2025.9.6` is pinned rather than the current `2026.3.6` (released 2026-09-03): every control above was measured on it, canonical SMILES output can change across RDKit releases, and it matches the sibling MolDeTox server. Moving it requires re-running the controls, not just bumping the pin. Assessed 2026-09-15; no PyPI or deps.dev advisory for the pinned version. ## Checklist - [x] I have read the [contributing guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup). - [x] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [x] Tests added or updated and pass locally (62 passed), plus a 241/241 model-free corpus validation. - [x] Pre-commit checks pass locally. - [x] All commits have DCO sign-off (`git commit -s`). ### New-environment gates (CONTRIBUTING.md) - [x] At least one test — `tests/test_app.py`, 62 tests - [x] Copyright header on every new file (NVIDIA SPDX form) - [x] `data/example.jsonl` with exactly 5 rows - [x] `data/example_metrics.json` reporting 5 examples - [x] `data/example_rollouts.jsonl` with exactly 5 rollouts - [x] No merge-conflict artifacts in `data/` - [x] Config sets `domain` (`knowledge`) - [x] Datasets carry a `license` field (`Apache 2.0` for the synthetic example; `TBD` for validation, see above) - [x] `verified: false` - [x] Registered as a benchmark (`gym list benchmarks`), not only an environment --------- Signed-off-by: Rima Shahbazyan <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]>
## What does this PR do? Adds **MolDeTox** as a NeMo Gym environment: toxicity-aware molecular editing built on *toxicity cliffs* — pairs of structurally similar molecules with opposite measured toxicity for the same endpoint. Given a toxic molecule and an endpoint, the model must produce the minimally-edited non-toxic partner. Scoring is **fully deterministic** — canonical-SMILES and SAFE-fragment comparison via RDKit. There is no judge model, no external service, and no toxicity predictor anywhere in the scoring path; the gold answers are experimentally measured pairs. All **eight** upstream QA configs are covered: three tasks × single/multi, with Task 3 in both SMILES and SAFE output form. ## Benchmark at a glance | | | | --- | --- | | Paper | [arXiv:2605.12181](https://arxiv.org/abs/2605.12181) — "MolDeTox: Evaluating Language Model's Stepwise Fragment Editing for Molecular Detoxification" | | Upstream repo | **None exists.** The paper's only availability statement is the HF dataset; the sole GitHub link anywhere in it is [datamol-io/safe](https://github.com/datamol-io/safe), a third-party library. Appendix D repeatedly says "the code", so an implementation exists internally — it was not released. | | Hugging Face | [`MolDeTox/MolDeTox`](https://huggingface.co/datasets/MolDeTox/MolDeTox), CC-BY-4.0, ungated | | Pinned revision | `059e1926fa62a07c3f01afadadf72cce154cfb7f` — upstream revised the files on 2026-08-27 and split sizes changed, so the name alone is not a stable reference | | Source material | Therapeutics Data Commons, FDA, SIDER | | Size | 8 QA configs, **7,904** test rows; upstream also ships ~202k train rows, which nothing here reads | ### Configs | Config | Test rows | `scoring_mode` | Model must produce | | --- | --- | --- | --- | | `task1_single` | 1,026 | `fragments_task1` | The one fragment driving toxicity | | `task1_multi` | 950 | `fragments_task1` | Two or more toxic fragments | | `task2_single` | 943 | `fragments_task2` | The one replacement fragment | | `task2_multi` | 1,033 | `fragments_task2` | Two or more replacement fragments | | `task3_smiles_gen_single` | 943 | `smiles` | Whole detoxified molecule, as SMILES | | `task3_smiles_gen_multi` | 1,033 | `smiles` | Same, multi-fragment edit | | `task3_safe_gen_single` | 943 | `safe` | Whole detoxified molecule, as SAFE | | `task3_safe_gen_multi` | 1,033 | `safe` | Same, multi-fragment edit | `single` and `multi` are a property of the item — how many fragments must change — not a multi-turn protocol. Every config is one-shot. The ninth upstream config, `toxicitycliff`, is the source pair table rather than a task; it is used only to join the toxic input molecule onto each row. ### Published baselines — GPT-5.2, zero-shot, mean ± std over three runs Tables D and E. Zero-shot is upstream's **baseline** reporting mode; its 4-shot columns are a labelled variant that retrieves demonstrations from the train split. | Config | Acc. (%) | | --- | --- | | `task1_single` | 41.09 ± 0.28 | | `task2_single` | 7.92 ± 0.15 | | `task3_safe_gen_single` | 4.00 ± 0.11 | | `task3_smiles_gen_single` | 3.50 ± 0.30 | | `task1_multi` | 3.85 ± 0.10 | | `task2_multi` | 0.23 ± 0.08 | | `task3_smiles_gen_multi` | 0.21 | | `task3_safe_gen_multi` | 0.15 | Only four models appear under SMILES generation; the full 13-model roster appears only under SAFE generation. ## Task and scoring Reward is exact match in every mode. What "exact" means differs: - **`smiles`** — canonical SMILES equality via RDKit. - **`safe`** — the prediction is decoded to SMILES with the datamol SAFE decoder, then compared canonically. A failed reconstruction counts invalid, matching upstream's Appendix D, rather than being masked. - **`fragments_task1`, `fragments_task2`** — string multiset over dot-separated SAFE fragments. Order does not matter, multiplicity does. Individual SAFE fragments carry unmatched attachment digits (`Cc1cccc6c1`, `C46`) and genuinely **do not parse as molecules** — verified, RDKit returns `None` for every one — so canonicalisation is impossible there and comparison is verbatim. The two fragment modes share that reward and differ only in auxiliary metrics, because Appendix D defines different ones per task. Splitting them means the scoring mode alone determines what is produced. | Mode | Auxiliary metrics | | --- | --- | | `smiles`, `safe` | `validity`, `tanimoto_rdk/maccs/morgan`, `levenshtein` | | `fragments_task1` | `fragment_f1`, `n_fragments_predicted` | | `fragments_task2` | `fragment_f1`, `n_fragments_predicted`, `levenshtein` | Two definitions follow the paper rather than the obvious reading. `fragment_f1` is over fragment **sets**, as Appendix D.1 writes it, so a repeated fragment neither helps nor hurts. The Task 2 `levenshtein` is **not** a whole-string edit distance; Appendix D.2 says so outright and takes each predicted fragment's minimum distance to any gold fragment, averaged. Appendix D.1 defines no distance for Task 1, so none is emitted there. Metrics a mode does not produce are `None` rather than `0.0`, so an absent metric is never averaged in as a zero. Only `mean/reward` and token counts are promoted to `key_metrics`; the similarity metrics stay in `agent_metrics` for diagnosis, for the reason under Harness validation. **The user message is upstream's, verbatim.** The shipped `question` field is a complete zero-shot prompt that already states the JSON output contract, so `prepare` applies no template. **The system prompt is upstream's too, and is sent.** The paper publishes one per task family (Tables H, I, J, K); `prompts.py` carries them verbatim and the preparer prepends the one matching the config. They restate the JSON contract the `question` already carries, but add role framing and a HARD CONSTRAINTS block ("Output ONLY the JSON object. Do not include explanations, markdown, or extra text."). An earlier version sent none; `--no-system-prompt` reproduces that, for measurement rather than for reporting. ## Reproducing ```bash # Setup — this server needs its own venv; rdkit and safe-mol are not in Gym's base cd resources_servers/moldetox uv venv --python 3.13.14 uv pip install -r requirements.txt cd ../.. source resources_servers/moldetox/.venv/bin/activate # Prepare a full split (test only; any of the eight configs) python resources_servers/moldetox/scripts/prepare_moldetox.py \ --config task3_smiles_gen_single \ --output resources_servers/moldetox/data/val.jsonl # Start servers (leave running) gym env start \ --resources-server moldetox \ --model-type openai_model \ --model "<model id>" \ --model-url "<openai-compatible base url>" \ --model-api-key "$API_KEY" # Collect rollouts gym eval run --no-serve \ --agent moldetox_simple_agent \ --input resources_servers/moldetox/data/val.jsonl \ --output resources_servers/moldetox/data/val_rollouts.jsonl ``` All commands run from the repository root with that environment active. Note `gym eval run` accepts `--input` only together with `--no-serve`, and `--split example` is rejected end-to-end because example files are committed smoke samples. Tests: `ng_test +entrypoint=resources_servers/moldetox` (78 tests). ## Harness validation Model-free, and stronger than any model comparison: - **Gold-as-prediction**: feeding each gold answer back through `verify()` scores `reward=1.0` on **7,904 / 7,904** rows across all eight configs, every row status `scored`, zero exceptions. - **Negative controls**: echoing the toxic input unchanged scores **0 / 943** on `task3_smiles_gen_single`; an undecodable SAFE string scores `validity=0`; an invalid SMILES is scored rather than silently dropped; fragment reordering and SAFE attachment-digit relabelling both still score 1.0, which is correct for a representation whose digits are arbitrary labels. Echoing the toxic input is worth dwelling on: it scores **0.0 accuracy at mean Morgan Tanimoto 0.711**, because cliff pairs are similar by construction. A do-nothing baseline looks strong on every similarity metric, so accuracy is the only headline-safe number here. `get_key_metrics` enforces that rather than leaving it to the reader: only `mean/reward` and token counts are promoted. ## On comparing against the published numbers Unlike most benchmarks in this repo, a run here **is** directly comparable in protocol. Zero-shot is upstream's baseline mode, the prompts are upstream's verbatim, the model (GPT-5.2) is on its roster, and Section 3.2 gives the sampler: **temperature 0.7, three runs per model**. That makes the residual gaps meaningful rather than expected, and they are real. `openai/openai/gpt-5.2` via `inference-api.nvidia.com/v1`, zero-shot, **temperature 0.7, three runs**, on the four single-step configs, with upstream's published system prompts sent. 11,565 completions, 0 API errors. Temperature was confirmed honoured rather than silently ignored before the runs: eight completions of one prompt give 2 distinct outputs at temperature 0.0, 5 at 0.7, and 6 at 2.0. | Config | Mode | Ours (3 runs) | Upstream (3 runs) | Diff | Welch *t* | *p* | | --- | --- | --- | --- | ---: | ---: | ---: | | `task1_single` | fragments | 39.05 ± 0.50 | 41.09 ± 0.28 | −2.04 | −6.16 | 0.008 | | `task2_single` | fragments | 8.34 ± 0.27 | 7.92 ± 0.15 | +0.42 | +2.39 | 0.093 | | `task3_smiles_gen_single` | smiles | 4.38 ± 0.31 | 3.50 ± 0.30 | +0.88 | +3.57 | 0.023 | | `task3_safe_gen_single` | safe | 3.39 ± 0.46 | 4.00 ± 0.11 | −0.61 | −2.21 | 0.145 | **Two of four now differ, down from three.** Two configs moved into agreement and one moved out of it by overshooting. Welch's t-test is the instrument because both sides estimate accuracy on the *same fixed task set*, so task sampling is not a source of disagreement; what varies is decoding, across runs. An earlier pass here used a Wilson binomial interval and appeared to agree on all eight configs. That interval answers a different question and is much wider, which is why it agreed. This table supersedes it. ### The two protocol corrections, measured Two protocol errors were found and fixed, each by re-running rather than by argument. Neither closed the gap on its own, and together they changed which configs disagree rather than removing disagreement. **Temperature.** The first runs set none, which the API resolved to 1.0; Section 3.2 specifies 0.7. Matching it moved every config by under 0.4 points. **The system prompt.** The paper publishes one per task family, as Tables H, I, J and K, and the first runs sent none. Sending them raised three of four configs by 0.4 to 1.3 points. | Config | No system prompt | With system prompt | Upstream | Verdict before | Verdict after | | --- | --- | --- | --- | --- | --- | | `task1_single` | 39.21 ± 0.50 | 39.05 ± 0.50 | 41.09 ± 0.28 | differs | differs | | `task2_single` | 7.00 ± 0.21 | 8.34 ± 0.27 | 7.92 ± 0.15 | differs | **agrees** | | `task3_smiles_gen_single` | 3.89 ± 0.32 | 4.38 ± 0.31 | 3.50 ± 0.30 | agrees | **differs, above** | | `task3_safe_gen_single` | 2.90 ± 0.06 | 3.39 ± 0.46 | 4.00 ± 0.11 | differs | **agrees** | The effect is real and in the predicted direction on three configs, and the mechanism is visible in the outputs: with the HARD CONSTRAINTS block the model returns bare JSON instead of fenced or narrated answers, so less depends on our extractor. But it is not the whole explanation. `task1_single` is untouched by it and remains two points low, and `task3_smiles_gen_single` moved from agreement to significantly *above* upstream, which no single systematic deficit explains. Sending the published system prompt is now the shipped default regardless of its effect on the numbers, because it is what upstream specifies. The four `multi` configs were run once each at unset temperature and are reported for completeness only. They resolve 0 to 2 correct answers out of about 1,000, so they discriminate essentially nothing: | Config | Ours (1 run) | Correct | Upstream | | --- | --- | --- | --- | | `task1_multi` | 4.53% | 43 | 3.85% | | `task3_smiles_gen_multi` | 0.19% | 2 | 0.21% | | `task2_multi` | 0.10% | 1 | 0.23% | | `task3_safe_gen_multi` | 0.00% | 0 | 0.15% | Auxiliary Task 3 metrics track closely, and were computed from the paper's prose definitions with no upstream code to fit against, which is what makes the agreement informative (ours / upstream, from the unset-temperature round): | Config | Validity | Morgan | MACCS | RDK | Levenshtein | | --- | --- | --- | --- | --- | --- | | `task3_smiles_gen_single` | 0.913 / 0.930 | 0.565 / 0.557 | 0.758 / 0.753 | 0.678 / 0.702 | 7.39 / 7.29 | | `task3_safe_gen_single` | 0.926 / 0.936 | 0.570 / 0.583 | **0.7625 / 0.7625** | 0.682 / 0.720 | 7.04 / 6.70 | ### Candidate causes for the residual gap Temperature and the system prompt are now controlled, and two configs still disagree. What is left: 1. **`task1_single` is unmoved by either correction** and sits two points low across six runs. It is the largest and most reliable disagreement, and the system prompt changed it by 0.16 points, which is inside run-to-run noise. Whatever drives it is not prompting. 2. **`task3_smiles_gen_single` now overshoots.** A harness that were simply lenient would overshoot everywhere; it does not. A plausible reading is that our extractor recovers answers upstream's would have discarded, which would raise us on the config where free-form SMILES is easiest to emit. 3. **"GPT-5.2" may not be the same deployment.** Ours routes through NVIDIA's gateway, and `top_p`, the token budget and the endpoint style are unstated. 4. **Fragment-mode verbatim matching is plausibly too strict for Task 2** — see Known limitations. Note this predicts we score *low* on Task 2, and after the system-prompt fix we no longer do. The most informative next measurement is a second model from upstream's roster; GPT-4o and Llama-3.1-8B-Instruct are both reachable. A constant offset across models points at the harness, a varying one at the deployment. Causes 1 and 2 point in opposite directions, which a single systematic harness deficit does not explain, so the deployment is the more likely common factor. ## Deliberate divergences from upstream - **BLEU-1 is not computed.** Upstream reports bare clipped unigram precision, which is degenerate on SMILES: the invalid string `C1CC` scores a perfect 1.0 against a 35-character gold, since every character occurs in it. Adding a brevity penalty fixes that but moves the figure ~0.05 off upstream's, so the metric is dropped rather than reported in a form that is either misleading or incomparable. - **`levenshtein` is `None` when the prediction is not a usable molecule**, so those rows are excluded from the mean rather than charged the full gold length. Charging them measured 10.07 against upstream's 6.70 on `task3_safe_gen_single`, where ~7% of predictions do not decode and therefore have no string to compare at all. Excluding them gives 7.04. - **PRS is not implemented.** Appendix D.3 names the six properties (MW, logP, HBA, HBD, PSA, RotB) and states the reference molecule is the toxic input, but leaves the per-property desirability functions and weights unstated as "QED-inspired", with no implementation to check against. Those curves determine the value entirely. `toxic_smiles` is carried in `verifier_metadata` so PRS can be added later without re-preparing data. - **`datasets` is not a direct dependency.** The eight configs are plain `.jsonl` files at a pinned revision, and `hf_hub_download` plus `json.loads` reads them directly. Both paths were compared over all eight configs of the pinned revision and produce identical rows. The dataset card is not honoured by the builder in any case: `load_dataset` reports `Some datasets params were ignored: ['type']` and picks the JSON builder for the CSV config, which then fails. **This does not shrink the install.** An earlier version of this description claimed it dropped PyArrow and Pandas; that was wrong. `nemo-gym` declares `datasets` in its own base dependencies, so those packages arrive regardless. What goes away is a duplicate direct declaration and a builder that mis-selects here. ## Known limitations - **Task 2 fragment scoring is plausibly too strict, and the fix is available.** Task 1 asks the model to *select* fragments from the decomposition printed in its own prompt — verified: the gold appears verbatim on 1026/1026 and 950/950 rows — so verbatim comparison is correct there. Task 2 asks it to *invent* a replacement, so its writing (ring-closure digits, atom order) is model-chosen and a chemically identical answer can score zero. Splicing the prediction into `common_safe_fragments` and decoding reconstructs the corresponding Task 3 gold on **943/943** and **1033/1033** rows, so a canonical comparison is available. Not done here because it changes the estimand away from upstream's, which defines Task 2 accuracy over the raw fragment multiset. `task2_single` remains significantly below upstream at matched protocol (*t* = −6.14), consistent with this being a contributing cause. Tracked, not silently ignored. - **The four `multi` configs are near the floor** (0–2 correct out of ~1,000). They are implemented and validated but carry almost no discriminative signal. ## Data and licensing - **Code**: Apache-2.0. No upstream code was ported — there is none to port — so `metrics.py` and the scorer are original work implementing the paper's prose definitions. - **Data**: CC-BY-4.0, ungated, derived upstream from Therapeutics Data Commons, FDA, and SIDER. `prepare_moldetox.py` downloads at runtime at a pinned revision; only the 5-row `data/example.jsonl` smoke sample is committed, which CC-BY-4.0 permits with attribution. - **Dependencies**: `rdkit` (BSD-3) and `safe-mol` (Apache-2.0). Neither is a discretionary choice — RDKit is the cheminformatics toolkit upstream's metrics are defined against, and `safe-mol` is the SAFE decoder the paper cites by URL as the one it uses. Both pinned (`rdkit==2025.9.6`, `safe-mol==0.2.1`) because installing `safe-mol` downgrades rdkit; the full validation and test suite were re-run under the downgrade and are clean. - Only the `test` split is used. The ~202k-row train split is never read, and `--split` is constrained to `test` so that stays true rather than resting on the caller. ## Checklist - [x] I have read the [contributing guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup). - [x] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [x] Tests added or updated and pass locally (78 tests). - [x] Pre-commit checks pass locally — on the first pass `update-readme-table` rewrote `README.md` to add the environment row, as CONTRIBUTING describes; the second pass is clean. - [x] All commits have DCO sign-off (`git commit -s`). ### New-environment gates (CONTRIBUTING.md) - [x] At least one test — `tests/test_app.py`, 78 tests - [x] Copyright header on every new file - [x] `data/example.jsonl` exists with exactly 5 rows - [x] `data/example_metrics.json` reports `"Number of examples": 5` - [x] `data/example_rollouts.jsonl` exists with exactly 5 rollouts - [x] No merge-conflict artifacts in `data/` - [x] Config sets `domain` (`knowledge`) - [x] Train/validation datasets carry a `license` field - [x] `verified: false` Verified directly: `gym env test --resources-server moldetox +should_validate_data=true` exits 0. --------- Signed-off-by: Rima Shahbazyan <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]>
CritPt currently reports only the formatting turn's token usage, dropping the solve turn. Sum both turns into the existing response `usage` so the standard input, output, and total token metrics cover the complete task. This follows [Artificial Analysis's methodology](https://artificialanalysis.ai/methodology/intelligence-benchmarking#critpt), which includes both solving and answer parsing. The change reuses the shared usage accumulator and adds no metrics or configuration. If either turn omits usage, report `null` rather than a partial total. The second-turn output still goes to the same verifier; prompts and scoring are unchanged. Existing saved rollouts retain their old counts, so historical second-turn-only token metrics are not directly comparable. No separate issue is needed for this focused accounting bug. The original integration and discussion in #1588 were reviewed. The agent README documents the corrected usage semantics. Validation (server-only change): - `gym env test +entrypoint=responses_api_agents/critpt_agent +should_validate_data=true` — 27 passed. - `python -m pytest tests/unit_tests/test_openai_utils.py -o addopts= -q` — 242 passed. - `python -m pytest resources_servers/critpt/tests -o addopts= -q` — 57 passed outside the sandbox (the sandboxed TestClient hung). - `pre-commit run --all-files` and `git diff --check` — passed. - New regression cases checked against the original agent: six fail on the original behavior and all pass with the fix. Coverage includes combined counts, absent usage, optional detail counts, and preservation of the second-turn answer. - Live two-turn synthetic physics smoke through the agent, model adapter, resource verifier, and standard token extraction: output tokens **64 + 29 = 93**, input tokens **40 + 165 = 205**, total tokens **104 + 194 = 298**. Inspected the formatted answer and verified the returned output matches turn two. The official AA scoring call was replaced with a local synthetic-answer stub; no official grading quota or full benchmark run was used. Signed-off-by: Igor Gitman <[email protected]>
## What does this PR do? - Adds public async and sync `pause()` / `resume()` methods behind an optional sandbox-provider capability. - Implements snapshot-backed OpenSandbox pause/resume, including paused status mapping, per-sandbox PTY detachment, and SDK handle refresh after endpoints are rebuilt. - Supports descriptor handoff across processes: reconnect accepts a paused sandbox without probing its suspended exec daemon, while `resume()` keeps health checks enabled and returns an exec-ready sandbox. - Adds lifecycle timeout configuration and focused API, provider, and PTY regression coverage. - Adds a snapshot management helper to the OpenSandbox provider (`python -m nemo_gym.sandbox.providers.opensandbox.snapshots` with `list` / `delete` / `cleanup [--kill-paused] [--dry-run]`) to inventory and reclaim snapshots and paused sandboxes left behind by interrupted runs; validated live against an OpenSandbox deployment. ## Test plan - `.venv/bin/pytest -q tests/unit_tests --ignore=tests/unit_tests/test_enroot_provider.py` — 2,516 passed, 4 skipped, 15 subtests passed. - `.venv/bin/pytest -q tests/unit_tests/test_enroot_provider.py -k 'not test_create_start_timeout_cleans_up'` — 60 passed, 1 deselected. The deselected macOS `/proc`-dependent test fails identically on untouched `main`. - `.venv/bin/pre-commit run --all-files` — all hooks passed. - Live OpenSandbox E2E against the supplied deployment in two separate OS processes with default health checks: process A created a sandbox, wrote proof state, paused, serialized its descriptor, and exited; process B connected while paused, resumed, and its first exec immediately read the exact preserved proof before stopping the sandbox. ## Checklist - [x] I have read the [contributing guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup). - [x] The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs. - [x] Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable). - [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so CI lint/format/copyright pass). - [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check passes). --- Generated with [Claude Code](https://claude.ai/code) --------- Signed-off-by: Hemil Desai <[email protected]> Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
…l Playwright + remote CDP backends) (#1865) ## Summary Addresses #644 (*integrate Browser Gym*), which asks for BrowserGym-style interactive web-task environments — an agent navigating and acting on a live page — in the Gym ecosystem. This PR delivers one natively as `interactive_browser`: one isolated browser per rollout, driven by tool calls, scored by `verify()`. Existing web envs (`google_search`, `browsecomp`) only read pages; this one *operates* them. Where the browser runs is a config choice. The remote backend runs it **off the training node**, so browser RAM does not scale on the GPU node. > **Updated per review feedback.** The environment is now vendor-neutral: `InteractiveBrowserResourcesServer` + `LocalPlaywrightBackend` + `RemoteCDPBackend`, with hosted browser services plugged in as **session providers**. The Lexmount integration ships as an example provider in `providers/lexmount/`, which holds its code, its config and its README — the environment directory contains no vendor-specific file outside `providers/`. <img width="1460" height="720" alt="lexmount_gym_arch" src="https://github.com/user-attachments/assets/4d751c77-da84-49c6-8b27-21bba69828ef" /> ## What it is - A stateful Resources Server: browser tools (`browser_navigate` / `browser_click` / `browser_type` / `browser_observe` / `browser_finish`) + `verify()`, with one isolated browser context per `session_id`. - Reuses the standard `simple_agent` harness — the model's function calls are dispatched by name to the tool endpoints; no custom harness needed. - Two shipped backends behind a small `BrowserBackend` contract (`open / goto / click / type / observe / current_url / text / close`): | `backend:` | Browser runs | Notes | |---|---|---| | `local_playwright` (**default**) | A Chromium launched on this machine, one per rollout | No account, no quota, no network. Grades the bundled offline `site/` tasks in CI. | | `remote_cdp` | Anywhere reachable over CDP, supplied per rollout by a **session provider** | Keeps browsers off the training node. | - A session provider answers one question for `remote_cdp` — *where is this rollout's browser, and how do I give it back?* ```python class BrowserSessionProvider(Protocol): name: str async def acquire(self, spec: BrowserSessionSpec) -> BrowserSessionHandle: ... # a live cdp_url async def release(self, handle: BrowserSessionHandle) -> None: ... # idempotent ``` | Provider | What it does | |---|---| | `static_cdp` (built in) | Uses an endpoint that already exists — `chromium --remote-debugging-port=9222`, a browser container, another host. **No third-party dependency**, and what CI tests `remote_cdp` against. | | `lexmount` (example) | Creates one isolated cloud browser session per rollout and deletes it afterwards. SDK is operator-installed and optional; the environment itself depends on `playwright` and nothing else. | Selection mirrors `nemo_gym.sandbox`: single-key `{name: {kwargs}}` mappings, providers imported only when selected, and out-of-tree providers publishable through the `nemo_gym.browser_session_providers` entry-point group (no fork needed). ## Key result — browser off-node Browser RAM on the training node, measured (PSS), by concurrency model: | Backend | node RAM @ 1000 concurrent rollouts | |---|---| | Local Chromium, one process per rollout | ~40–50 GB | | Local Chromium, one browser + N contexts | ~16 GB | | **Remote over CDP** (measured with the `lexmount` provider) | **~0.14 GB — flat in concurrency** | The browser engine runs off the node, so training-node RAM stays flat as concurrency grows and is free for vLLM / the model. *(Measured on a single host with a simple-page workload, characterizing each backend's browser engine — PSS of the chrome\* process tree for the local backend vs node-side client PSS for the remote one.)* ## Session lifetime A browser is released when the rollout is scored (`verify`) or when the same `session_id` is re-seeded. There is no independent episode TTL and no client-side cap on concurrent sessions, so a metered provider needs its account quota sized above the rollout concurrency (documented in the env README and the provider README). Every acquired provider session is released **exactly once** — including when the CDP connect fails after the session was created, and however often `close()` is called. Both are covered by tests. ## Integration path - **A (this PR):** native `SimpleResourcesServer` with custom tool endpoints; upgradeable to `MCPResourcesServer` (`@gym_tool` on `/mcp`) if an MCP-native harness is preferred. - **B (follow-up):** wrap the environment as an OpenEnv `Environment` so it runs through the existing `openenv` adapter (`OpenEnvResourcesServer`, which discovers tools at startup via `ListToolsAction`). This is the config-selected, backend-agnostic path for the third-party-environment integration tracked in #1701. - Reward is settled once in `verify()` (not per-step accumulation), which sidesteps the `TODO(ahmadki)` cumulative-reward limitation in the OpenEnv adapter's step-wise `accumulated_reward` summation. ## Status - [x] Environment (`app.py`, `browser/`, configs, offline test site, `generate_data.py` + example tasks, tests) - [x] Runs end-to-end via a `gym env start` + rollout (local backend, offline site): reward 1.0 on the navigate task - [x] One contract test suite run against **both** backends — `remote_cdp` against a Chromium the suite starts with `--remote-debugging-port`, so the remote path is covered in CI with no third-party service (22 tests, no GPU, no serving stack, no account) - [x] Off-node concurrency benchmark (per-backend browser-engine RAM) - [x] `lexmount` example provider implemented + smoke-validated on a live cloud session - [x] Remote path validated at training scale - [x] Pre-generated `example_rollouts.jsonl` - [x] GRPO training-signal run + reward curve on a web benchmark Feedback welcome on the interface (A vs B), and on where you would like the example provider to live — it currently sits in-tree as a self-contained `providers/lexmount/` (code + config + docs), mirroring how named sandbox providers ship under `nemo_gym/sandbox/providers/`. Loaded by path: ```bash gym env start --config resources_servers/interactive_browser/providers/lexmount/configs/lexmount.yaml ... ``` --------- Signed-off-by: waple0820 <[email protected]> Signed-off-by: waple0820 <[email protected]> Co-authored-by: waple0820 <[email protected]>
## What does this PR do?
Adds only the shared episode identity and envelope in
`nemo_gym/episode_types.py`: `EpisodeId`, minimal `TaskId`,
`MaterializedTask`, base request/response, and handled failure.
`TaskId` contains only `taskset` and `task_id`. Taskset names use the
`<environment>:<taskset>` convention when a run blends tasksets.
## Single-agent interaction flow
This diagram shows the built-in single-agent use case. Other Environment
Server protocols may coordinate different participants and use different
request, result, and lifecycle flows.
```mermaid
sequenceDiagram
participant C as Rollout collector
participant E as Environment Server
participant R as Task / Resources Server
participant A as Agent Server
participant M as Model Server
participant S as Task sandbox
C->>E: POST /run
E->>R: Seed task session
R-->>E: Tool access and optional SandboxAccess
E->>A: Seed agent session
A->>S: Connect as borrower when supplied
E->>A: Invoke /v1/responses
A->>M: Model and capture requests
A-->>E: Agent response
E->>A: Close agent session
E->>R: Verify response
E->>R: Close task session
E-->>C: Episode result
```
The Environment Server coordinates ordering and the final result. Agent
and Task/Resources Servers retain ownership of the state and resources
they create.
This is part 2 of 14 in the Environment Server stack. Previous:
[#3482](#3482). Next:
[#3484](#3484).
## Validation
- `uv run pytest tests/unit_tests/test_episode_types.py -q`
## Rollouts
See the final PR for end-to-end rollout evidence.
## Compatibility and benchmark impact
No agent, resources, tool, or sandbox lifecycle contract is included.
Signed-off-by: Ananth Subramaniam <[email protected]>
## What does this PR do?
Adds `BaseEnvironmentServer`, a narrow `CleanupContext`, concrete
`run_request()`, abstract `run(request, cleanup)`, admission, an opt-in
episode deadline, typed failure conversion, aggregation, and
cancellation-resistant cleanup.
Cleanup is bounded and LIFO. Explicit cleanup and final unwinding share
a per-entry lock, and AnyIO cancellation is shielded without
busy-spinning. Internal `TimeoutError` and unexpected protocol
exceptions become distinct typed failures.
## Single-agent interaction flow
This diagram shows the built-in single-agent use case. Other Environment
Server protocols may coordinate different participants and use different
request, result, and lifecycle flows.
```mermaid
sequenceDiagram
participant C as Rollout collector
participant E as Environment Server
participant R as Task / Resources Server
participant A as Agent Server
participant M as Model Server
participant S as Task sandbox
C->>E: POST /run
E->>R: Seed task session
R-->>E: Tool access and optional SandboxAccess
E->>A: Seed agent session
A->>S: Connect as borrower when supplied
E->>A: Invoke /v1/responses
A->>M: Model and capture requests
A-->>E: Agent response
E->>A: Close agent session
E->>R: Verify response
E->>R: Close task session
E-->>C: Episode result
```
The Environment Server coordinates ordering and the final result. Agent
and Task/Resources Servers retain ownership of the state and resources
they create.
This is part 3 of 14 in the Environment Server stack. Previous:
[#3483](#3483). Next:
[#3543](#3543).
## Validation
- `uv run pytest tests/unit_tests/test_environment_server.py -q` (11
passed)
- scoped Ruff and pre-commit checks
## Rollouts
See the final PR for end-to-end rollout evidence.
## Compatibility and benchmark impact
The external route remains `POST /run`.
Signed-off-by: Ananth Subramaniam <[email protected]>
## What does this PR do?
Defines named direct-HTTP and streamable-HTTP MCP access independently
of any session lifecycle. These contracts carry episode-scoped
connectivity and authorization data; locally launched MCP processes
remain Agent Server configuration.
## Single-agent interaction flow
This diagram shows the built-in single-agent use case. Other Environment
Server protocols may coordinate different participants and use different
request, result, and lifecycle flows.
```mermaid
sequenceDiagram
participant C as Rollout collector
participant E as Environment Server
participant R as Task / Resources Server
participant A as Agent Server
participant M as Model Server
participant S as Task sandbox
C->>E: POST /run
E->>R: Seed task session
R-->>E: Tool access and optional SandboxAccess
E->>A: Seed agent session
A->>S: Connect as borrower when supplied
E->>A: Invoke /v1/responses
A->>M: Model and capture requests
A-->>E: Agent response
E->>A: Close agent session
E->>R: Verify response
E->>R: Close task session
E-->>C: Episode result
```
The Environment Server coordinates ordering and the final result. Agent
and Task/Resources Servers retain ownership of the state and resources
they create.
This is part 4 of 14 in the Environment Server stack. Previous:
[#3484](#3484). Next:
[#3545](#3545).
## Validation
- `uv run pytest tests/unit_tests/test_tool_access.py -q`
## Rollouts
See the final PR for end-to-end rollout evidence.
## Compatibility and benchmark impact
Additive contract definitions only. Static stdio MCP configuration
remains owned by individual Agent Server implementations.
Signed-off-by: Ananth Subramaniam <[email protected]>
## What does this PR do?
Defines `SandboxAccess` in the sandbox subsystem and adds borrower
disconnect support. Task/Resources Servers retain owner shutdown
authority.
## Single-agent interaction flow
This diagram shows the built-in single-agent use case. Other Environment
Server protocols may coordinate different participants and use different
request, result, and lifecycle flows.
```mermaid
sequenceDiagram
participant C as Rollout collector
participant E as Environment Server
participant R as Task / Resources Server
participant A as Agent Server
participant M as Model Server
participant S as Task sandbox
C->>E: POST /run
E->>R: Seed task session
R-->>E: Tool access and optional SandboxAccess
E->>A: Seed agent session
A->>S: Connect as borrower when supplied
E->>A: Invoke /v1/responses
A->>M: Model and capture requests
A-->>E: Agent response
E->>A: Close agent session
E->>R: Verify response
E->>R: Close task session
E-->>C: Episode result
```
The Environment Server coordinates ordering and the final result. Agent
and Task/Resources Servers retain ownership of the state and resources
they create.
This is part 5 of 13 in the Environment Server stack. Previous:
[#3543](#3543). Next:
[#3485](#3485).
## Validation
- `uv run pytest tests/unit_tests/test_sandbox_access.py
tests/unit_tests/test_docker_provider.py -q`
## Rollouts
See the final PR for end-to-end rollout evidence.
## Compatibility and benchmark impact
Existing sandbox owner lifecycle remains unchanged.
Signed-off-by: Ananth Subramaniam <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
Declares a legacy-agent environment server beside every bound agent instance. Idempotent, with a --check mode. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
…o entrypoint Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
Benchmarks that landed after the last sweep declare an agent with no environment server, which rollout collection cannot reach. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
…an environment server Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Marta Stepniewska-Dziubinska <[email protected]>
This was referenced Sep 28, 2026
ananthsub
changed the base branch from
ananthsub/episode-orchestration-07-swe-pro-sessions
to
ananthsub/episode-orchestration-05-sandbox-reconnection
September 28, 2026 15:33
Contributor
Author
|
Closing to recreate the remaining Environment Server work as one correctly ordered GitHub Stack. Branch commits are preserved; a replacement PR will follow. |
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do?
Adds compatibility Environment Servers for existing agents while migration to native episode protocols is in progress:
legacy_agentrelays the existing Agent/runand/aggregate_metricscontracts without interpreting them.single_agent_turn_legacyconverts legacy flat rows to the native single-agent-turn protocol and projects native responses back to the legacy result shape.This is now before Hermes sandbox execution in the stack so compatibility infrastructure lands before a migrated agent implementation. Previous: #3488. Next: #3489.
No issue is linked because this is one layer of the existing Environment Server PR stack.
Validation
uv run pytest tests/unit_tests/test_global_config.py -q— 160 passeduv run pytest tests/unit_tests/test_rollout_collection.py -q— 212 passed before native result follow-upsuv run pytest environment_servers/single_agent_turn_legacy/tests/test_app.py -q— 4 passedRollouts
N/A for this compatibility layer; end-to-end rollout evidence is recorded on the final integration PR.
Compatibility and migration impact
This intentionally changes configuration requirements: every runnable Agent instance must have an Environment Server in front of it. Out-of-tree configurations, including NeMo RL configurations, must add a
legacy_agentdeployment or runscripts/add_legacy_agent_environment_servers.py. Request and result bodies remain unchanged for legacy agents.