Repository navigation
feat(chemreason_bench): add ChemReason-Bench environment - #3618
Conversation
… server Ports the six primary metrics from upstream's eval/eval.py (Apache-2.0, commit c0b9ac2) that produce the published Primary-Overall macro-average, plus the response post-processing upstream applies before scoring: step-token canonicalization, de-duplication, partial-order completion in presentation order, contrastive-choice recovery from raw text, and the refusal to default an out-of-range index to option 0. Two upstream inconsistencies are resolved in favour of code and paper over config: eval_config.yaml states step completion as 0.5*action_em + 0.5*slot_f1 while eval.py and the paper both use 0.8/0.2 with a format-error penalty; and a reply that is not a JSON dict forces label=False while a dict merely missing `score` falls through to 0.5 >= 0.5 and counts positive. compute_metrics reduces per-row contributions into the published metrics rather than averaging rewards, because f1_positive needs the whole confusion matrix and the step-completion format penalty is corpus-level. It also averages the gen and lm protocols for the three discriminative tasks, as the paper's appendix F.3.4 defines. get_key_metrics is overridden so mean/reward, which matches no published quantity, cannot become the dashboard headline. Upstream's secondary metrics are deliberately omitted: none enters the headline, and bert_score alone would pull a neural model into an otherwise dependency-free, judge-free scorer. Signed-off-by: Levon Grigoryan <[email protected]>
prepare.py fetches upstream's two JSONL files at pinned commit c0b9ac2 and joins them on task_id. Upstream publishes no tagged release and its default branch is mutable, so an edit preserving the row count would otherwise move every score with nothing failing. Preparation fails closed on the total and the per-task counts, counting rows that parsed rather than bytes downloaded, and validates --limit at parse time before any fetch. The paper's Primary-Overall averages two protocols for the three discriminative tasks. `lm` is a different PROMPT -- a bare YES/NO or a bare option index instead of JSON -- not the same request with logprobs, so both are emitted: 7,306 gen + 3,342 lm = 10,648 rows. The lm rows trail the gen rows so --limit stays a gen-only subset; --protocol reaches them for a smoke test. All 10,648 rendered prompts are byte-identical to the ones upstream's predict.py builds, verified row by row and re-verified after formatting touched the f-strings that produce them. The system prompt is verbatim from predict.py, including the fact that upstream sends its JSON-mode instruction on lm rows whose user prompt says "No JSON"; that contradiction is upstream's own and is reproduced rather than corrected. Rows also carry the question-side vocabulary upstream's post-processors need -- expected_step_ids for ordering, options for contrastive choice. Neither is gold and neither is rendered into the prompt. Signed-off-by: Levon Grigoryan <[email protected]>
…t the environment
126 tests at 98.5% coverage, and a model-free validation record.
Gold answers replayed as predictions score identically under this port and under
upstream's own eval/eval.py on all six primary metrics and on Primary-Overall
(0.988983) to six decimal places, across bare, think-wrapped and fenced replies
and across both protocols.
That gate also surfaced an upstream data defect the port reproduces exactly
rather than papering over: gold cannot reach 1.0 on step_completion, which caps
at 0.9339, because 460 of 1,483 rows carry empty gold slots and slot_f1({},{})
is 0 by construction, 2 rows use slot keys outside the schema, and 6 carry
duration_unit "day" which upstream's own legality check rejects. Published
SC-Scores sit against that ceiling.
Negative controls run over all 7,306 items rather than a sample. An empty
prediction scores 0.00 Primary-Overall, but a fixed constant answer scores 27.54,
because f1_positive pays 0.627 and 0.729 on the two validation tasks when 46-57%
of gold labels are positive. That floor is documented prominently: Primary-Overall
must not be read as a correctness rate.
The README also records the composite licence chain the upstream CC BY 4.0 card
does not cover (OpenExp/ChemTrans <- USPTO/ORD/OrgSyn), and the one divergence
that cannot be closed from this component: Gym's responses converter builds the
output text without populating its logprobs field, so lm labels come from parsing
generated text instead of an argmax over decision-token logits. The argmax path
is implemented and reports status ok_logprobs the moment logprobs arrive.
Signed-off-by: Levon Grigoryan <[email protected]>
|
Verdict: HOLD (Gym Reviewed at head The six primary metric formulas match upstream line for line, both Findings1. BLOCKER — step-completion slots skip upstream's 2. BLOCKING (contracts) — a shipped file cites a test that does not exist; 3. RISK — rationalization replies without a JSON dict score 0 here but not upstream. 4. RISK — wrong-typed row fields become a 422, not a 5. NOTE — JSON extraction rule differs from upstream. 6. NOTE — 7. NOTE — small contract gaps. Checked and OK
Limitations
|
…w findings Addresses the review on #3618. BLOCKER 1 — upstream runs canonicalize_slots(slots, legend) at predict.py:953 before a step-completion prediction reaches the scorer, and it was not ported. Alias keys collapse to `reagent`, blobs like "10 mL" split into value+unit, reagent names resolve to $n$ placeholders through the legend, units normalise and migrate between groups, #n#/@n@ tokens lift out, and anything outside the whitelist is dropped. Without it a matched reagent read as an unrecognised key. prepare.py now carries `legend` on step-completion rows; it is question-side vocabulary, not gold, and is not rendered into the prompt. Validated as the review asked, by replaying stored rollouts through both implementations: 1483/1483 paired agreement with upstream on real model output for BOTH evaluated models, and 1483/1483 on gold. step_completion moves 5.20 -> 6.95 for Qwen (paper 7.25) and 10.08 -> 12.03 for Llama (paper 9.23). Hand-copying upstream's unit table had dropped six entries (liter, litre, ltrs, mole, moles, ul.), which alone caused 59 rows of disagreement; the table is now asserted equal to upstream's. This also corrects a documented number. Gold has TWO ceilings on step_completion: 0.9339 under eval.py alone, which is what the six-decimal agreement is measured against, and 0.9272 through the real pipeline, because canonicalization alters 297 of 1,483 gold slot sets. A model run takes the second path. Both are now in the README. BLOCKER 2 — paper.yaml cited tests/test_prepare.py, which did not exist, and prepare.py had no coverage at all. Adds it with the fetch stubbed to local fixtures: golden prompts per task family and protocol, the join, every count gate, the no-partial-write guarantee, --limit/--protocol ordering, and a check that gold never leaks into a prompt. RISK 3 — rationalization now falls back to the raw reply, as upstream's post_rationalization does via _raw, instead of scoring a prose-only answer 0. RISK 4 — row fields are typed Any and shape-checked inside verify(). A narrow annotation turned a wrong-typed row into a 422 during request validation, which simple_agent's raise_for_status would have turned into an aborted run rather than the harness_failure status the docstring promises. NOTES — REVERIFY_MODE STATELESS declared on the config as the siblings do; task_data declares protocol/question/expected_step_ids/options/legend so rows no longer report unknown keys; the rightmost-JSON-object departure is now in the README's list rather than only in a docstring; and metrics.py no longer claims a whole run is "comparable by construction" when that holds only of the scorer. 166 tests, 97.46% coverage. Two tests changed to assert measured behaviour rather than my assumption: an unknown amount_unit is scrubbed by canonicalization and is NOT fatal, while duration_unit/temperature_unit are normalised but never dropped and remain the only route to the format-error flag. Signed-off-by: Levon Grigoryan <[email protected]>
Follow-up: changes since the review at
|
| paired agreement | step_completion before → after |
paper | |
|---|---|---|---|
| Qwen2.5-7B | 1483/1483 | 5.20 → 7.02 | 7.25 |
| Llama-3.1-8B | 1483/1483 | 10.08 → 11.99 | 9.23 |
Gold slots agree 1483/1483 as well. Both models were then rerun in full.
This did not move both models toward the paper, and the comment as first posted glossed
over that. Qwen improved; Llama got further away. Mean absolute per-task error against the
published per-task values, and the Primary-Overall gap:
| mean per-task |error| before | after | Primary-Overall |Δ| before | after | |
|---|---|---|---|---|
| Qwen2.5-7B | 0.50 | 0.27 | 0.42 | 0.25 |
| Llama-3.1-8B | 1.97 | 2.27 | 1.88 | 2.21 |
Qwen's per-task error roughly halved, driven by step_completion going from 2.05 off to 0.23
off. Llama's regression is almost entirely the same task in the other direction: 0.85 off to
2.76 off, because canonicalization rescues slots for both models and Llama overshoots the
published 9.23 to 11.99.
I am not reverting it to recover that number. The change makes our pipeline perform a step
upstream demonstrably performs, verified at 1483/1483; omitting it because omitting it scores
better would be fitting to the target rather than measuring against it. Llama was already the
worse-matching model before this change, and its two largest residual errors — step_val 3.48
and cond_val 4.02 — are precisely the two tasks whose published metric averages in the lm
protocol we cannot reproduce (finding 6). Its model snapshot is also unspecified upstream
("LLama-3.1 8B", no revision, no base-vs-instruct; we used Instruct).
Two things this surfaced that the review could not have seen:
- Hand-copying upstream's unit table had silently dropped six entries (
liter,litre,
ltrs,mole,moles,ul.), which alone caused 59 rows of disagreement. The table is now
asserted equal to upstream's in a test. - A number I had published was wrong. Gold has two ceilings on
step_completion: 0.9339
undereval.pyalone — which is what the six-decimal agreement is measured against — and
0.9272 through the real pipeline, because canonicalization alters 297 of 1,483 gold slot
sets. A model run takes the second path. Both are now documented with which applies when.
2. BLOCKING — missing test, untested prepare.py — fixed
tests/test_prepare.py added with the fetch stubbed to local fixtures: golden prompts for
every task family and protocol, the join, every count gate, the no-partial-write guarantee,
--limit/--protocol ordering, non-positive --limit rejected at parse time, validation
before any fetch, and a check that gold never leaks into a prompt. paper.yaml now cites the
file that exists and states precisely what it pins.
3. RISK — rationalization _raw fallback — fixed, with evidence
Now falls through to the raw reply as upstream's post_rationalization does. The review asked
for the rate of non-JSON rationalization replies in stored runs: 0 of 1,215 for both models,
so coverage_f1 is unchanged at 18.03 / 22.67. The fix is correct for a model that does not
comply, but it has no measured effect on either model evaluated here.
4. RISK — wrong-typed fields became a 422 — fixed
Row fields are typed Any and shape-checked inside verify(), so a wrong-typed row reports a
harness_failure status rather than failing Pydantic before verify() runs. Tests cover
wrong types, not just None.
5–7. NOTES — fixed, except one
- Rightmost-JSON-object departure is now in the README's departures list, not only a docstring.
REVERIFY_MODE: STATELESSdeclared on the config, as the siblings do.task_datadeclaresprotocol,question,expected_step_ids,options,legend.metrics.pyno longer claims a whole run is "comparable by construction"; that property is
scoped to the scorer, with the remaining divergence pointed at the README.- Not fixed, and cannot be from this component: upstream's
lmrule sums probability mass
over every vocabulary token ending inYES/NOand abstains when one side has no mass — not
a top-k argmax. The README now says this explicitly rather than implyingok_logprobswould
match upstream. Two attempts to obtain logprobs both failed against live runs (logprobs: trueis not a Responses API field and sent everylmrow to the failure sidecar;
top_logprobsalone returns an empty completion truncated atmax_output_tokens), and
neither would have helped:nemo_gym/responses_converter.pybuilds the output text without
populating itslogprobsfield, so the values are discarded before any verifier sees them.
That is a shared-code change and belongs in its own issue — happy to file it. - Apache-2.0 attribution for the ported metric code is recorded in the module docstrings and
the README rather than asserted as a legal determination, as the review suggested.
Reviewer limitations now closed
- Tests, pre-commit and coverage were run against the final diff: 166 passed, 97.46%
coverage, pre-commit clean. - The byte-identical prompt claim is now reproduced, not just inspected — pinned by goldens
intests/test_prepare.py.
Two tests changed to assert measured behaviour rather than my assumption: an unknown
amount_unit is scrubbed by canonicalization and is not fatal, while
duration_unit/temperature_unit are normalised but never dropped and remain the only route
to the format-error flag — which is exactly why the six gold rows carrying "day" trip it.
|
Re-review at head Verified closed
New — introduced by the fix to 4Widening Claims in the follow-up the diff does not support
Residual notes
LimitationsNothing executed. The "166 passed, 97.46%" figure, the 1483/1483 paired-agreement table and the rerun rollout numbers in the PR body are inspected, not reproduced. |
Tests. Three assertions were weak enough to pass regardless of behaviour:
- test_oversized_reply_is_bounded_before_parsing asserted `status in
("no_json_found","ok")` and `obj is None or isinstance(obj, dict)`, which
every possible outcome satisfies. Rewriting it to compare JSON before and
after the cap was ALSO not falsifiable, because it built the filler from the
imported MAX_RESPONSE_CHARS and so grew with it. Split in two: the mechanism
is tested with the cap monkeypatched small, and a second test pins the shipped
value. Mutation-checked -- raising the constant now fails the suite, which it
did not before.
- test_malformed_output_never_raises asserted only 0 <= reward <= 1. It now
asserts the property that matters: a junk reply is charged to the model
(harness_failure False, a named status, contributions present) rather than to
the harness. Mutation-checked: flipping harness_failure fails 38 cases.
- The prepare row-contract test asserted isinstance for the carried
question-side vocabulary; it now asserts the values equal the source row's.
Mutation-checked: dropping `legend` fails it.
Comments. Density was 28% overall and 43% in prepare.py, much of it restating
the README or narrating the code. Trimmed to 22% by cutting the restatements and
keeping the one-line notes that record a trap or a deliberate divergence.
Behaviour unchanged: 167 tests, 97.48% coverage.
Signed-off-by: Levon Grigoryan <[email protected]>
Update — head
|
| Model | This environment | Paper | Δ |
|---|---|---|---|
| Qwen2.5-7B-Instruct | 53.69 | 53.94 | −0.25 |
| Llama-3.1-8B-Instruct | 51.66 | 49.45 | +2.21 |
For Qwen, four of six tasks are within 0.25 of the paper.
One caveat I don't want to drop: this is a comparison, not a reproduction. Upstream
publishes point estimates with no spread, no run count and no model snapshot ids, so no
significance test is constructible — and Llama's gap is wider than Qwen's for the reason in the
previous comment (the lm protocol we cannot reproduce from this component).
All four were real. Two are behavioural bugs, two were claims my own commit messages made that the tests did not support. 1. Non-string task_id crashed verify(). This was a regression I introduced: the round-1 fix widened task_id to Any so a wrong-typed row would report a status instead of a 422, but _sanitize still assumed str, so an int raised AttributeError inside verify() -- a 500, which aborts the run, and strictly worse than the 422 it replaced. _sanitize now coerces. 2. The rationalization _raw fallback used the UNSTRIPPED output_text, so a reasoning model's whole <think> trace was scored by token_f1. Upstream's _raw holds post-extraction text. Added clean_text() and used it for the fallback. Measured on one trace: coverage_f1 0.2667 with the trace vs 0.4000 without. 3. "Tests cover wrong types, not just None" was false -- only None was tested. Now parametrized across None/list/str/int/bool for ground_truth, wrong types for task_type, non-string task_id, and wrong-typed question-side vocabulary. Writing them found a third bug, in the test helper rather than the server: QUESTION_SIDE.get(task_type) raised on an unhashable task_type. 4. "The table is now asserted equal to upstream's" was also false -- the test spot-checked three entries. It now pins all 53, and a second test pins that the canonicalization and scoring tables stay separate. All three fixes mutation-checked: reverting each fails the suite. 187 tests, 97.48% coverage. Signed-off-by: Levon Grigoryan <[email protected]>
Round-2 items — all four addressed at
|
|
Round 3 at head Verified — the test changes are good
Still open from round 2 — none addressed at this head1. RISK — 2. No wrong-type tests. 3. Prose-only rationalization fallback is untested and reads the unstripped reply. No test sends a non-JSON rationalization reply, and the fallback in 4. Follow-up wording. "The table is now asserted equal to upstream's in a test" still describes an assertion that does not exist ( Checked and OKRollout table and comparison caveat now in the PR body; "comparison, not reproduction" is the right framing. 167 tests / 97.48% is author-reported. Still open
LimitationsNothing executed. |
|
Round 4 at head Verified closed
New — introduced by the fallback fix (NOTE, non-blocking)A parsed dict with no rationale key now scores the raw text; upstream scores it as empty. Upstream sets Also: the new comment says upstream's Checked and OKThe Still open
LimitationsNothing executed. |
|
Round 5 at head New1. RISK (low) — the committed example artifacts predate the scorer changes. 2. NOTE — README dataset-format table omits 3. NOTE — ordering/contrastive raw-text fallbacks read the unstripped reply. Carried from round 4, still open
Re-verified on the final files
Still open outside the code
LimitationsNothing executed. |
…ng rule; refresh examples
Round 4 and 5 review items.
1. The _raw fallback was applied too broadly. Upstream sets _raw ONLY when JSON
parsing fails (predict.py:303), so a dict that parsed but lacks every
rationale key scores "" there. The previous fix fell back for both cases, so
a reply like {"note": "..."} was scored by token_f1 on its own JSON text.
Now scoped to no_object; a parsed dict without the key scores 0.
2. One cleaning rule. All three raw-text fallbacks -- ordering, contrastive
choice, rationalization -- now receive the think-stripped reply. Upstream's
_raw is the whole answer, so this is a DEPARTURE rather than parity, and is
now labelled as one instead of being claimed as a port. It is applied
uniformly because a reasoning trace can otherwise feed digits to the ordering
recovery or an option string to the contrastive recovery.
3. The clean_text docstring called upstream's _raw "post-extraction" text. It is
the whole answer; corrected.
4. Example artifacts predated the scorer changes. Regenerated all three: the
step_completion example row now carries `legend` so the smoke row exercises
canonicalization rather than the degrade-to-empty branch, and the rollouts
were re-scored through the current verifier (0 rewards changed).
5. README dataset-format table now lists `legend`, and the departures section
records both the cleaning rule and the _raw-only-on-parse-failure behaviour.
191 tests, 97.60% coverage.
Signed-off-by: Levon Grigoryan <[email protected]>
Rounds 4 and 5 — addressed at
|
|
Round 6 at head Verified closed
The "unexplained discrepancy": two tests are vacuous by construction, not an environment problem1. 2. The contrastive case discriminates because NOTE —
|
Round 6 diagnosed the "unexplained" mutation-check failure from the last round:
both tests were vacuous by construction, and the environment was fine.
1. test_parsed_dict_without_a_rationale_key_scores_empty sent {"note":"unsure"},
which shares no tokens with the gold rationale, so the reverted code also
scored 0.0. The payload now carries text OVERLAPPING the gold, which is what
separates the branches.
I had written exactly this payload during the previous round, then destroyed
it with one of my own `cp` restores while debugging, and spent the rest of
that investigation testing the old input and blaming the environment.
A second attempt to restore it silently no-opped because ruff had reflowed
the call across more lines than the replacement target matched -- the same
silent-replace failure. This edit was made by line number and verified.
2. test_ordering_recovery_ignores_a_reasoning_trace sent a reply with no JSON,
so `got` defaulted to [] -- already a list -- and post_ordering's raw-text
scan never ran. It now sends `predicted_order` present but not a list, which
is the only input that reaches the scan.
Both are now mutation-checked for real: reverting the fallback scope fails the
first, reverting the single cleaning rule fails both cases of the second.
example_metrics.json: the round-6 note is right that it was not rewritten, but
it is not stale -- collate regenerates it byte-identical, because the metrics
measure responses_create_params (prompt words, turns, tools) and `legend` lives
in verifier_metadata. The "all three regenerated" claim was loose; two changed.
191 tests, 97.60% coverage.
Signed-off-by: Levon Grigoryan <[email protected]>
Round 6 — both diagnoses correct, fixed at
|
|
Round 7 at head Verified closed
Correction to my round 6I said CheckedFull test-file delta read; no other PR path changed; no merge from Still open outside the code
LimitationsNothing executed. |
main now requires every shipped server class to declare its Ray usage (test_shipped_server_classes_declare_ray_usage). Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Levon Grigoryan <[email protected]>
yuhezhang-ai
left a comment
There was a problem hiding this comment.
Thanks for the update! I re-reviewed the latest commit and have no remaining code-review concerns. All 375 targeted benchmark, converter, and Ray tests pass. The remaining CI failures also reproduce on main and are being handled separately (#4054 covers the HTTP test-client compatibility failures). The normal required CI checks still need to pass before merging.
…eMo#4054) Fresh server environments can select Starlette's `httpx2`-based TestClient while Gym's OpenAI SDK still requires `httpx`. This breaks the session tests when they inject an `httpx.Cookies` object into that client, and the GDPVal judge-routing test when it passes TestClient directly to the SDK. The failures also reproduce on unchanged main (`b0e3fa6cf`); they were observed in [the full CI run for NVIDIA-NeMo#3618](https://github.com/NVIDIA-NeMo/Gym/actions/runs/37337581691). Use a standard-library cookie jar in the two session test fixtures, preserving explicit-cookie session isolation. Forward the SDK's HTTP requests through an `httpx.MockTransport` into the real TestClient in the GDPVal test, preserving its proxy/model/credential assertions. Only test code changes; benchmark behavior and results are unaffected. A separate issue is unnecessary for this focused, reproduced CI repair. Validation: - Before the fix on main with fresh server dependencies: 18 failed, 17 passed across the affected tests. - After the fix: 35 passed with fresh dependencies (Starlette 1.7.0, httpx2 2.13.1, httpx 0.28.1), and 35 passed in the locked development environment. - Commands: `pytest resources_servers/example_session_state_mgmt/tests/test_app.py resources_servers/openenv/tests/test_app.py --import-mode=importlib -q`; `pytest resources_servers/gdpval/tests/test_judge_panel.py -q -k test_benchmark_panel_reaches_intended_upstream_models_and_credentials`. - `pre-commit run --all-files` and `git diff --check` passed. - Model rollouts: N/A, test-harness compatibility only; no runtime environment/agent behavior changes. The separate Aviary dependency failure from that CI run is addressed in NVIDIA-NeMo#4055. Signed-off-by: Yuhe Zhang <[email protected]>
…Mo#4055) An unconstrained `datasets` requirement lets a fresh Aviary environment resolve `datasets==1.2.1` with current PyArrow. Importing the server then fails with `AttributeError: module 'pyarrow' has no attribute 'PyExtensionType'`, before any Aviary tests run. This reproduces on main (`b0e3fa6cf`) and appeared in [the full CI run for NVIDIA-NeMo#3618](https://github.com/NVIDIA-NeMo/Gym/actions/runs/37337581691). Require `datasets>=4.4.1`, matching the modern version already used by Gym's locked development environment. A fresh server install now chooses a compatible dataset stack instead of backtracking to the legacy release. This is scoped to Aviary; a separate issue is unnecessary for this focused, reproduced dependency repair. Validation: - Before: the standard server test failed during collection on unchanged main. - After, from a fresh server environment: `gym env test --resources-server aviary +should_validate_data=true` passed (4 passed, 1 existing Docker-dependent test skipped); example-data validation passed. - The tests load the real GSM8K dataset and exercise environment creation, a calculator tool step, and the dataset-server/client lifecycle. - `pre-commit run --all-files` and `git diff --check` passed. - Model-generated rollouts: N/A for this dependency-compatibility constraint; no agent, prompt, verifier, or scoring code changes. The real dataset/tool lifecycle tests above ran; no model-generated answers were tested. The separate HTTP test-client failures are addressed in NVIDIA-NeMo#4054. Signed-off-by: Yuhe Zhang <[email protected]>
|
/ok to test d376908 |
|
/ok to test 552c89c |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/37477811564 |
|
Thanks a lot for the review! @yuhezhang-ai |
…s lists (NVIDIA-NeMo#4323) ## What changed No public request or response model in `nemo_gym/openai_utils.py` keeps a field that Pydantic validates into a lazy iterator. Each change follows the existing Iterable overrides in that file, such as the ones for `annotations`, `content`, `summary`, and `tools`. The first commit fixes model output that the agent sends back as input. `NeMoGymResponseOutputText.logprobs` now uses Gym copies of the OpenAI `Logprob` and `LogprobTopLogprob` types, with `List` in place of `Iterable` for `bytes` and `top_logprobs`. The second commit fixes request configuration. It adds Gym copies with `List` fields for these SDK types: | Request model | Field path | | --- | --- | | Responses | `tool_choice` allowed tools: `tools` | | Responses | namespace tool: `tools` | | Responses | file search tool: compound filter `filters` | | Responses | shell tool: `container_auto` and `local` environment `skills` | | Responses | shell and code interpreter tools: container allowlist network policy `domain_secrets` | | Chat Completions | `prediction.content` | | Chat Completions | `tool_choice` allowed tools: `allowed_tools.tools` | The request models now use Gym copies of the SDK `ToolParam`, `ToolChoice`, and `ChatCompletionToolChoiceOptionParam` unions. Each copy keeps the SDK members in the SDK order and swaps in a `List` subclass only where the SDK member has an `Iterable` field. Because the member order is the same, union validation picks the same member as before. `NeMoGymResponse` and `NeMoGymChatCompletion` had no remaining lazy fields. ## Why the agent's next request fails Since NVIDIA-NeMo#3618, the vLLM model server copies chat-completion logprobs into `output_text.logprobs`. The OpenAI `Logprob` type declares `bytes` and `top_logprobs` as `Iterable`, and Pydantic validates an `Iterable` field into a lazy iterator that can be read only once. When the model writes text and a tool call in the same turn, `simple_agent` sends that assistant message back as input on the next turn. `ServerClient.request` dumps the request body with `model_dump(exclude_unset=True)` in Python mode, which leaves the lazy iterator in the output as a `SerializationIterator`. orjson cannot encode that object, so the post to the model server fails and the agent's `/run` returns HTTP 500: ``` TypeError: Type is not JSON serializable: pydantic_core._pydantic_core.SerializationIterator ``` This happened in step 1 of a 2-step NeMo-RL GRPO smoke run with Qwen3-0.6B, vLLM with the `hermes` tool parser, and the workplace_assistant environment with `simple_agent`. An earlier run with the same code and data passed, because the failure only occurs when an assistant text message with logprobs is followed by another turn. The lazy type also loses data without an error. Serializing the same response object a second time returns empty `bytes` and `top_logprobs` lists, and `model_copy(deep=True)` cannot copy the object at all because the iterator cannot be pickled. ## Why the fix is in the type and not in `ServerClient.request` Switching `ServerClient.request` to `model_dump(mode="json")` would make the first encode succeed, but the dump would still read the iterator to the end. Every later turn would then send empty logprobs to the model server. Storing the values as lists keeps them complete for every serialization. ## Wire format The encoded request bytes are unchanged. For a request with a user message, an assistant message with logprobs, a function call, and a function call output, the new Python-mode dump encoded by orjson is byte-identical to the previous `mode="json"` encoding of the same body. ## Related issue No issue is filed, because the bug was found in a smoke run and the fix is contained in one type. ## Request configuration fields The request configuration fields fail the same way when a dataset sets them. For example, this request cannot be encoded by orjson after validation: ```python NeMoGymResponseCreateParamsNonStreaming.model_validate( {"input": "q", "tools": [{"type": "namespace", "name": "ns", "description": "d", "tools": [{"type": "function", "name": "f", "parameters": {}}]}]} ) ``` Its `model_copy(deep=True)` raises `cannot pickle 'ValidatorIterator'`, and a second `model_dump(mode="json")` returns an empty `tools` list in the namespace tool. ## Validation - `tests/unit_tests/test_openai_utils.py` builds a next-turn request the way `simple_agent` does. It validates a model response with output text logprobs and a function call, deep-copies the request body, and appends the output and a function call output. The test checks that orjson encodes the request with complete logprobs on repeated serializations. - `tests/unit_tests/test_server_utils.py` sends a request that replays an assistant message with logprobs through `ServerClient.post` and checks the encoded request data. - `tests/unit_tests/test_openai_utils.py` walks the Pydantic core schemas of `NeMoGymResponseCreateParamsNonStreaming`, `NeMoGymResponse`, `NeMoGymChatCompletionCreateParamsNonStreaming`, and `NeMoGymChatCompletion`, and fails if any field path reaches a `generator` schema. The failure message names each path. This test also catches lazy fields that a future OpenAI SDK upgrade adds. - A parametrized test validates a request for each fixed request configuration path. It checks that orjson encodes the Python-mode dump, that repeated dumps stay complete, and that a deep copy works. - A test pins each Gym union copy to its SDK union, member by member and in order, so an SDK upgrade that adds a tool or tool-choice type fails the test instead of being rejected silently. - All of these tests fail on the code before the matching commit. On the code before the second commit, the schema walk names the request configuration paths, and every encode, copy, and dump case fails. - For each fixed request configuration path, plus unchanged cases such as a code interpreter container ID and a named function tool choice, a script compared the orjson encoding of the new Python-mode dump with the previous code's first `mode="json"` dump. The bytes were identical, including key order. Requests that leave out a required key in the new copies still fail validation. Commands: ```bash uv sync --extra dev --extra sandbox --extra openshell --extra mlflow --extra wandb pytest tests/unit_tests -n 16 pytest responses_api_agents/simple_agent/tests responses_api_models/vllm_model/tests pre-commit run --all-files ``` ## Rollout evidence Pending: the 2-step NeMo-RL GRPO smoke run on workplace_assistant will be repeated before this PR is marked ready for review. --------- Signed-off-by: Ananth Subramaniam <[email protected]>
What does this PR do?
Adds ChemReason-Bench as a NeMo Gym environment: action-grounded reasoning over real
experimental procedures. 500 curated reactions become 7,306 instances across six task families —
order the steps, judge whether a step or a condition is valid, fill a missing step, pick the
right reagent, explain why.
Scoring is fully deterministic — pure Python over the standard library. There is no judge
model, no external service and no network call in the scoring path; gold comes from the source
procedures.
It complements the existing
bunsenbench_chemistry_mcq, which is multiple-choice chemistryknowledge. This measures procedural reasoning, and five of its six tasks are not
multiple-choice.
No issue filed — a self-contained new environment touching no shared code. Happy to open one.
Benchmark at a glance
Khadaz/ChemReason-Bench— harness, data and scorer all releasedc0b9ac2933708fcca47b1795492952cbf280e194(2026-05-08). No tagged release exists and the default branch is mutable, so an edit preserving row count would move every score with nothing failingtestsplit. Prepared as 10,648 rows — see Two protocols. Upstream also ships a >120k-row training pool, which nothing here readsDATA_LICENSE, commercial use explicit)Task families
step_completionstep_completion_scoreorderingpairwise_accuracyrationalizationcoverage_f1step_validationf1_positivecondition_validationf1_positivecontrastive_choicetop1_accuracyprepare.pyrefuses to write anything but these counts, and counts rows that parsed ratherthan bytes downloaded.
Upstream's secondary metrics are deliberately not implemented: none enters the published
headline, and
bert_score_f1alone would pull a neural model into an otherwise dependency-freescorer.
eval.pyalso reportsrange_1_400/range_401_500slices;benchmark_idis carriedon every row so they can be reconstructed.
Two protocols
For the three discriminative tasks the published primary metric is the mean of two protocols
(appendix F.3.4,
m_t = (m_gen + m_lm) / 2):genasks for JSON, as the other three tasks do.lmasks for one bare decision token —YES/NO, or an option index. It is a differentprompt, not the same request with logprobs.
prepare.pyemits both (7,306 + 3,342 = 10,648) andcompute_metricsreduces each separatelybefore averaging, so one run yields the paper-comparable number. Scoring
genalone and callingit Primary-Overall is not the published quantity. A dataset carrying one protocol falls back
to it rather than being halved, so
--protocol genstill scores.Published baselines — Primary-Overall, temperature 0, one pass
Open-weight rows, Figure 5. Best proprietary is GPT-5.2 at 70.30.
Task and scoring
rewardis a per-row signal in [0, 1]. It is not the benchmark's metric. Four of the sixpublished metrics are only defined over a corpus —
f1_positiveneeds the whole confusionmatrix,
step_completion_scoreapplies a corpus-level format-error penalty — socompute_metricsreduces per-row contributions rather than averaging rewards, andget_key_metricskeepsmean/rewardout of the headline set.Model output passes through upstream's post-processors before scoring: step tokens are
canonicalised (
id2andstep_2both mean2), repeats dropped, and once one legal id hasmatched the unmentioned ids are appended in presentation order — while an answer matching
nothing yields
[]rather than a fabricated order. A contrastive choice is recovered from rawtext when the index is missing, and an out-of-range index becomes
-1rather than defaulting tooption 0. Step-completion slots additionally pass through
canonicalize_slots, which resolvesalias keys, splits blobs like
"10 mL", maps reagent names to$n$through the row's legend anddrops anything outside the whitelist.
Prompts are upstream's, verbatim. All 10,648 rendered prompts are byte-identical to what
predict/predict.pybuilds, checked row by row and re-checked after formatting touched thef-strings that produce them. The three-line system prompt is verbatim too — including the fact
that upstream sends its JSON-mode instruction on
lmrows whose user prompt says "No JSON",a contradiction reproduced rather than corrected.
Four upstream inconsistencies were resolved deliberately:
eval_config.yamlstates step completion as0.5*action_em + 0.5*slot_f1;eval.pyand thepaper both use
0.8/0.2with a format-error penalty. The config is stale; code and paperproduced the published numbers.
label=False; a dict merely missingscorefallsthrough to
0.5 >= 0.5and counts positive._rawonly when parsing fails, so a dict that parsed but lacks the requestedkey scores empty rather than being scored on its own JSON text.
predict.pyandeval.pyship different unit tables; they are kept separate, becausemerging them changes scores.
Two deliberate departures, both recorded in the README rather than implied as parity: the
rightmost JSON object wins when a reply contains several (upstream parses first-
{-to-last-}),and every raw-text fallback receives the reply with reasoning blocks stripped (upstream's
_rawis the whole answer). The second is applied uniformly because a reasoning trace can otherwise
feed digits to the ordering recovery or an option string to the contrastive recovery.
Reproducing
Smoke subsets, neither of which is a scored population —
lmrows trail thegenrows, so--limitalone never reaches them:Upstream evaluates with deterministic decoding (temperature 0) and one pass per instance.
Tests:
gym env test --resources-server chemreason_bench(226 tests).Harness validation
Model-free, and stronger than any model comparison:
upstream's
eval/eval.pyagree on all six primary metrics and on Primary-Overall(0.988983) to six decimal places. Repeated with replies delivered bare,
<think>-wrappedand fenced, and across both protocols.
reproduction runs (
genrows of Qwen2.5-7B, Llama-3.1-8B and Phi-3-mini-4k) were fedthrough upstream's parsing tail and
post_*functions and scored by upstream'seval/eval.py,and the same text through this scorer. Every per-task primary metric and Primary-Overall agree
to two decimals, 18 of 18 cells. 50 rows (0.23%) differ in the prediction record without moving
any score: 49 are
step_completionactions outside the allowed set, which upstream blanks to""where this port keeps the string (neither matches gold); 1 is a three-object contrastivereply, where upstream's first-
{-to-last-}span fails to parse and its raw scan takes thefirst option mentioned while the rightmost-object rule above reads the last -- gold was a
fourth option, so both are wrong.
Primary-Overall. Reversing an ordering scores 0.000 on that task. An illegal
duration_unitzeroes step completion through the format-error penalty, while an unknown
amount_unitisscrubbed by canonicalisation and is not fatal — an asymmetry that is upstream's, and pinned.
Gold cannot reach 100 on
step_completion, and this is an upstream data property the portreproduces rather than papers over: 460 of 1,483 rows carry empty gold slots and
slot_f1({}, {})is 0 by construction, 2 rows use slot keys outside the schema, and 6 carryduration_unit: "day", which upstream's own legality check rejects. There are two ceilings:0.9339 under
eval.pyalone — the figure the six-decimal agreement is measured against — and0.9272 through the full pipeline, because canonicalisation alters 297 of the 1,483 gold slot
sets. A model run takes the second path.
A fixed constant answer scores 27.54 Primary-Overall.
f1_positivepays 0.627 and 0.729 onthe two validation tasks because always-positive earns good positive-class F1 when 46–57 % of
gold labels are positive. That is roughly 71 % of the weakest published model's headline
(LLama-2 7B, 38.58), reachable without answering anything, so Primary-Overall must never be read
as a correctness rate. It is called out at the top of the README for that reason.
Reproduction of the published numbers
Full 10,648-row runs (7,306
gen+ 3,342lm), temperature 0, one pass, each model servedlocally with vLLM 0.19.1 (
--max-model-len 16384,--tensor-parallel-size 4; Phi-3-mini-4k:--max-model-len 4096, output budget 1024,--max-logprobs 1000). Driver:Upstream's published numbers carry a tokenization bug.
predict.pyrenders the chattemplate to text — which already contains the BOS token — and then calls
tokenizer(text)withthe default
add_special_tokens=True, so every model whose tokenizer hasadd_bos_token=truewas scored from a double-BOS prompt, on both protocols. This port sends a single BOS by default;
the paper's condition is one override away (no code change):
++policy_model.responses_api_models.vllm_model.extra_body.add_special_tokens=true.Qwen2.5 (no BOS token) and Phi-3-mini (
add_bos_token=false) are unaffected either way.Qwen2.5-7B-Instruct — Primary-Overall 53.82 vs published 53.94.
Llama-3.1-8B-Instruct — Primary-Overall 50.43 (single BOS, default) and 49.35 with
the paper's double BOS reproduced, vs published 49.45.
Phi-3-mini-4k-instruct — Primary-Overall 43.55 vs published 43.51. The paper's
"Phi-3-mini 7B" is this 3.8B checkpoint; the 128k variant is a different fine-tune.
Per-task composition of Primary-Overall — each task is the mean of its
gen/lmcolumns(single-protocol tasks are their
genvalue);paperquotes the composites from the paper'sappendix tables. Llama under the paper's double-BOS condition.
Side by side with upstream's harness. The same weights were also run through upstream's
own
predict.pyandeval.pyat the pinned commit, unmodified, in the same container (gen passover all 7,306 prompts;
lmpass over the 3,342 discriminative rows). Per-task composites, Gymunder the same prompt condition as upstream (double BOS for Llama):
Every task agrees within 0.4 between the two harnesses. Upstream's code on our Llama weights
gives 49.43 under its double BOS and Gym gives 50.43 with a single BOS: the published Llama gap
is the tokenization, not the model snapshot. Upstream caps generation at 96-200 new tokens per
task where Gym allows 4096.
Under each model's own condition every cell is within ~1 point of the published row (largest
gap 0.56, Llama step_validation); Phi-3's collapsed
lmvalidation scores reproduce too, so theyare a property of that model, not of the harness. Upstream publishes neither a spread nor a run
count, so no significance test is constructible; run-to-run drift at temperature 0 was measured
at up to 0.35 on a task.
Notes
lmlabels are decided from token probabilities as upstream does:lmrows requestlogprobs via
metadata.extra_body,nemo_gym/responses_converter.pynow carries thechoice-level logprobs back onto the output text (the one core change in this PR), and the
decision follows the paper's appendix F.3.2 eq. (1)/(2). Two deliberate departures from
predict.pyare recorded in the README: its suffix rule (any token ending in YES/NO over thefull vocabulary — 153 Llama tokens count as NO vs 21 as YES, a tail no top-k API can see; <1
point on Llama) and its two-visible-indices guard (zeroed every Phi-3 contrastive row).
prepare.pydownloads it at runtime from thepinned commit. A small amount of upstream
benchmark_data/is committed under CC BY 4.0 withattribution (6 verbatim rows per test fixture, 10 rendered prompts, 5 restructured example rows). Upstream's own
LICENSEcarries unfilledCopyright [yyyy] [name of copyright owner]boilerplate, so the licensor is unidentified, and the provenance chain above is notrestated in the repo — ORD is share-alike and Organic Syntheses is separately copyrighted, so
the CC BY 4.0 card does not demonstrably cover them. Instances are template-rendered
derivatives rather than verbatim redistribution. Recorded for review rather than asserted as a
rights determination.
testsplit is used; the >120k-row training pool is never read.Checklist
README.md, plus the root README row added byupdate-readme-tableon the first pre-commit pass.git commit -s).New-environment gates (CONTRIBUTING.md)
tests/test_app.py,test_metrics.py,test_prepare.py(226 tests)data/example.jsonlexists with exactly 5 rowsdata/example_metrics.jsonreports"Number of examples": 5data/example_rollouts.jsonlexists with exactly 5 rollouts, scored by the current verifierdata/domain(knowledge)licensefield (Creative Commons Attribution 4.0 International)verified: false