Repository navigation
feat(stem_judge): add a STEM LLM-judge resources server - #6518
Conversation
Grades open-answer STEM questions with an LLM judge for RL rewards. Answer rows use the stem_v11 judge prompt and its yes/no verdict parser (from the stem_llm_judge server on gnalbandyan/stem_llm_judge, d002fd9), with the verdict regexes made possessive so degenerate judge text cannot backtrack; rubric rows are graded per criterion. A per-row answer_format (boxed or free) and length gates score 0 without a judge call, with the reason in grading_status. Judge calls go through call_judge, so a failed call masks the row instead of scoring it; a cut off judge reply is unparsed. Includes tests, five example rows, five example rollouts with a separate judge model, and the example metrics. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Jiacheng Xu <[email protected]>
…tector The SHA-256 that pins the stem_v11 prompt reads as a high-entropy string. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Jiacheng Xu <[email protected]>
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE
I found three RISKs: the resources server lacks the schema required by dataset tooling, explicitly failed judge responses can become unmasked scores, and rubric parsing rejects valid criterion IDs containing unmatched braces.
I inspected all 13 changed files and traced the affected validation, grading and recovery paths. I covered grading and delivery directly after two delegated reports were unavailable. This was a static review; I did not execute tests or verify the reported runs.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| return self | ||
|
|
||
|
|
||
| class StemJudgeRunRequest(BaseRunRequest): |
There was a problem hiding this comment.
RISK: Ship the task-data schema used by dataset tooling
The server defines its row contract only in StemJudgeRunRequest. There is no schema module in the server directory, so load_task_data_schema returns None. Consequently, collation skips this server's field validation, gym env schema --resources-server stem_judge exits unsuccessfully, and the existing schema-presence and committed-data tests reject the addition. The latter also records stem_judge: no loadable schema through its dataset-owner lookup. These are source-derived failures, not executed results.
Could you add a dependency-light module named task_data.py exporting TaskData in the server directory? Move the task fields, RubricCriterion and gradability validation there, then reuse that contract in the runtime request rather than maintaining a second declaration. The request can have this structure:
class StemJudgeRunRequest(TaskData, BaseRunRequest):
passKeep the schema importable without importing the server or Gym runtime. Declare the examples' id field so shared validation does not report it as unknown. Preserve the open extra-field policy, scalar metadata-reference fallback including 0, reference-free rubric rows, and the existing malformed-rubric rejection rules.
Acceptance checks, not executed: the two shared tests named above should pass; schema inspection should emit JSON Schema; all five committed examples should validate cleanly. Add a schema/runtime parity check showing that missing answer references and duplicate rubric IDs fail both contracts, while metadata reference 0, reference-free rubrics and carried row labels retain their current behavior. Verify the proposed inheritance against the resulting models before adopting it.
There was a problem hiding this comment.
Fixed in e6002b1. resources_servers/stem_judge/task_data.py exports TaskData (standard library and Pydantic only) with RubricCriterion, the gradability validator and reference_of; StemJudgeRunRequest(TaskData, BaseRunRequest) reuses it, so there is one declaration. It declares id and uuid, keeps extra="allow", the scalar metadata fallback (including 0), reference-free rubric rows and the malformed-rubric rejections. TestSchemaPresence and TestRepoDataMatchesSchemas pass locally, gym env schema --resources-server stem_judge prints the JSON Schema, and new tests check that all five example rows validate and that schema and runtime accept and reject the same rows (missing reference, duplicate ids, NaN points, metadata 0, reference-free rubric, carried labels).
| ) | ||
|
|
||
| evaluation = JudgeEvaluation(responses_create_params=params, response=judge_response) | ||
| if judge_response.status == "incomplete": |
There was a problem hiding this comment.
RISK: Mask explicitly failed judge responses instead of scoring them
A judge response with status="failed", an error and output=[] passes the shared helper's HTTP/schema checks. This branch checks only incomplete, so verification returns reward=0, grading_status="judge_unparsed" and mask_sample=false. If the failed response retains partial text containing Judgement: yes, it can instead receive a positive parsed grade. Both attribute a failed grading operation to the policy answer. The OpenAI model adapter passes validated response status through, and call_judge does not reject an operation-level failure.
Could you import the public JudgeError from nemo_gym.verification and insert this immediately before constructing evaluation?
if judge_response.status == "failed" or judge_response.error is not None:
raise JudgeError(
f"Judge response failed: {judge_response.error or judge_response.status}"
)The existing judge_failsafe route wrapper will then mask the row and retain the policy response. Keep incomplete replies, reasoning-only replies and completed replies without a verdict on their intentional judge_unparsed path. Successful answer and rubric replies must still produce completed grading observations.
Proposed checks, not executed: return status="failed", error={"code":"server_error","message":"judge failed"} and empty output from the mocked judge, then repeat with partial output containing Judgement: yes. Through judge_failsafe, both should return _ng_failure_class="judge_failed", mask_sample=true and the original policy response, with grading outcome failed. Retain the incomplete/reasoning-only assertions and parsed answer/rubric observation assertions in the existing tests. Verify the suggested code against the response model before adopting it.
There was a problem hiding this comment.
Fixed in e6002b1 as suggested: _call_judge raises JudgeError when the reply has status="failed" or an error, before building the evaluation, so judge_failsafe masks the row and keeps the policy response. Incomplete, reasoning-only and verdict-less completed replies stay on judge_unparsed. New tests cover a failed reply with empty output and one with partial Judgement: yes text (both judge_failed, mask_sample=true, original response kept) and the failed grading outcome.
| boolean or the string "true"/"false". Returns None when no object marks every id. | ||
| """ | ||
| text = text.rsplit("</think>", 1)[-1] | ||
| candidates = [span for span in _brace_spans(text) if JSON_OBJECT_START.match(text, span[0])] |
There was a problem hiding this comment.
RISK: Ignore braces inside JSON strings when locating rubric verdicts
Criterion IDs accept any non-empty string, but _brace_spans counts braces inside quoted JSON keys as structure. For a valid single-criterion rubric with id="r}", a completed judge reply of {"r}": true} produces only the premature span {"r}. parse_criteria(..., ["r}"]) therefore returns None, and _grade_rubric assigns judge_unparsed and reward 0 instead of full credit. The same failure occurs with an unmatched opening brace in an ID. This is a deterministic parser failure derived from the source, not an executed test.
Could you make candidate extraction distinguish JSON string contents, including escaped quotes and backslashes, from structural braces? Preserve arbitrary non-empty criterion IDs rather than rejecting these otherwise valid rows. Keep the bounded candidate work: replacing this with an unbounded decode attempt at every opening brace would lose the latency protection. I have not identified a small replacement scanner that also safely handles the surrounding prose, so I am not suggesting an unchecked patch.
Proposed regression checks: parse_criteria('{"r}": true}', ['r}']) and its r{ counterpart should return the corresponding true mark; verification of a one-point free-format rubric with either ID should return grading_status="judged", rubric_score=1 and reward=1. Also cover an escaped quote followed by a brace in the key. Preserve code-fenced JSON, string boolean values, selection of the last complete mapping, and rejection of missing or non-boolean marks from test_criteria and test_criteria_unparsed. Retain the trailing-LaTeX and deeply nested JSON cases with their existing outcomes and runtime bound in the performance regressions. These checks were not executed.
There was a problem hiding this comment.
Fixed in e6002b1. parse_criteria no longer counts braces: it finds where JSON objects with a key start ({, optional whitespace, ") and decodes each with json.JSONDecoder.raw_decode, which handles braces and escaped quotes inside keys and strings. It still tries at most the last 64 starts, newest first. New tests cover ids r}, r{ and a"} and a one-point free rubric with id r} (judged, score 1, reward 1); the code-fence, string-boolean, last-complete-object, missing/non-boolean, trailing-LaTeX and deeply-nested cases keep their outcomes and time bounds.
…parse braces in criterion ids - task_data.py exports TaskData, the row contract; StemJudgeRunRequest inherits it, so collation, `gym env schema` and the shared schema-presence and committed-data tests see the same rules as verify(). - A judge reply with status "failed" or an error raises JudgeError, so judge_failsafe masks the row instead of scoring it. - parse_criteria decodes JSON objects from where they start rather than counting braces, so a criterion id such as "r}" parses; it still tries at most the last 64 object starts. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Jiacheng Xu <[email protected]>
|
/ok to test e6002b1 |
yaoyu-33
left a comment
There was a problem hiding this comment.
LGTM. The 118 component tests passed, and I verified that the documented vLLM judge path emits its verdict in a single text block.
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44644674134 |
What
Adds
resources_servers/stem_judge, a resources server that grades open-answer STEM questions (physics, chemistry, biology and similar) with an LLM judge, for use as an RL reward.stem_v11prompt. The judge's lastJudgement: 'yes'|'no', read from its text after its own last</think>, gives reward 1 or 0; the evaluation saves it asverdict_label: "Judgement: yes|no", the form Gym's rollout recovery checks against the reward. Answer rows must carry a non-emptyexpected_answer(ormetadata.expected_answer); a row without one fails request validation instead of being judged against nothing.rubriclist is graded criterion by criterion. The judge marks each criterion id true or false, and the server computes earned points over total positive points (rubric_reward: fraction) or pass/fail atrubric_pass_fraction(threshold).answer_format: boxedrows need a non-empty last\boxed{};freerows (explanations, derivations) are judged on the whole final answer. Under the defaultboxed_judge_input: final_answerthe box is a format gate and the judge grades the whole final answer;boxshows the judge only the box.grading_status: the policy hit its length cap (truncated), no assistant text (empty_final_answer), a boxed row without a box (no_boxed), a box overmax_box_chars(box_too_long, off by default), or a final answer overmax_answer_chars(answer_too_long, 16,000 characters).-is shown to the judge as-…(a two-or-more-item list is left alone): the prompt puts the reference on its own line, where- 13.6 eVreads as a markdown list item and the judge drops the sign.call_judge. A failed call is retried when another attempt can succeed (408, 429, 5xx, timeout, lost connection) and otherwise fails at once; either way it is reported as a judge failure, so the row is masked rather than scored. A reply with no verdict, or one cut off at the judge's token limit, scores 0 (judge_unparsed); a reply withstatus="failed"or anerroris a judge failure and masks the row.REVERIFY_MODEisSTATELESS; checkpoints replay verify (checkpoint_mode = "stateless",checkpoint_verify = "replay"), likeequivalence_llm_judge.task_data.pyexportsTaskData, the row contract;StemJudgeRunRequestinherits it, so dataset tooling andverify()apply the same rules.generation_log_dir), written from a worker thread so it does not block the event loop.The policy and judge model servers are expected to run with a reasoning parser: the assistant message is the final answer.
Provenance. The
stem_v11prompt isresources_servers/stem_llm_judge/prompt_templates/stem_llm_judge.txtfrom Grigor Nalbandyan'sstem_llm_judgeresources server, branchgnalbandyan/stem_llm_judgeat d002fd9 in this repository (NVIDIA, Apache-2.0), byte for byte; the test suite pins its hash. Adapted from the same commit'sapp.py: the verdict patterns (rewritten with possessive quantifiers, see Validation),PROBLEM_EXTRACT_REGEX, the question, assistant-text, truncation and step helpers, themetadata.expected_answerfallback, the judge concurrency limit and the generation-log record. Affected files:resources_servers/stem_judge/app.pyandresources_servers/stem_judge/prompt_templates/stem_v11.txt. There is no open PR for that branch.Why
STEM RL data has been graded with
math_with_judge's judge, which compares only the boxed answer through an A/B-swapped[[A=B]]prompt. We compared it withstem_v11on 2,000 STEM rollouts sampled from earlier RL training runs. Every disagreement (409) and a stratified sample of agreements were adjudicated blind by a stronger model, with "correct" meaning the final answer matches the reference:math_with_judgejudge P / R / F1stem_v11P / R / F1The existing judge rarely accepts a wrong answer but misses 28% of correct physics answers and 40% of correct non-physics ones, mostly equivalent forms, rounding or units, and explanation-style answers.
stem_v11recovers most of them for about one point of precision. The box gate requires the requested format, and the length gates keep runaway outputs from reaching the judge.Issue: none. This adds a standalone resources server and changes no existing component.
Validation
All run on head e6002b1 unless noted:
gym env test --resources-server stem_judge +should_validate_data=true: 118 tests passed; data validated.tests/unit_tests/data/test_task_data.pyTestSchemaPresenceandTestRepoDataMatchesSchemas: passed;gym env schema --resources-server stem_judgeprints the schema.pre-commit run --all-files: all hooks passed (the README table row comes fromupdate-readme-table).data/example_metrics.jsonfromgym dataset collate "+config_paths=[resources_servers/stem_judge/configs/stem_judge.yaml]" +output_dirpath=data/stem_judge +mode=example_validation.judge_failsafe, the reverify mode, and the saved shape of rubric evaluations."Answer:" + "\n" * 60took 2.6 s, a 20,000-newline reply 11.5 s, growing without bound). The rewritten patterns return the same verdict as the originals on all 679,710 judge texts tried (226,570 stored judge replies from an offline rejudge, each also with a trailingAnswer: Yesand a leading**Final Answer:** $\boxed{\text{No}}$), and parse each of the degenerate inputs in the tests in under 6 ms (the tests assert under 0.5 s). Reading only the text after the judge's last</think>(as upstream does) changed none of the 7,847 stored replies that contain one.parse_criteriatries at most the last 64 brace spans that open like a JSON object (LaTeX braces such as{2}are skipped), so deeply nested judge JSON is unparsed in milliseconds instead of 17 s..agents/skills/pr-reviewper round, strict, broad; not the hosted/review): three broad rounds and a follow-up round on this head. They found 1 BLOCKER (catastrophic regex backtracking) and RISKs in reference validation, question extraction, reverify mode, rubric verdict serialization, blocking log I/O,</think>handling, the smoke evidence and logging of reasoning-only judge replies; all are fixed. Final verdict on this head: SHIP, with advisory NOTEs open (rare-whitespace and empty-brace edge cases in reference and criteria parsing, test tightening, README wording). That review covered 5fe3d15. Later commits: d92d0b3 adds a# pragma: allowlist secretcomment to the pinned prompt hash; e6002b1 fixes the hosted review's three RISKs (task-data schema, failed judge replies masked, braces in criterion ids) with tests, and was pushed without another local round.Rollout evidence
data/example_rollouts.jsonlholds one rollout per example row, collected on an earlier revision of this branch that differs only in how the judge's closing message is read, the startup template check, the rubric-criteria candidate filter and the list-item regex; none of these affect these rows. The policy isnvidia/nemotron-3.5-lightning-30b-a3band the judgenvidia/nemotron-3-ultra-550b-a55b, both on the NVIDIA API; the commands are in the server README's "Running" section (ajudge_modelserver injudge.yamland++stem_judge.resources_servers.stem_judge.judge_model_server.name=judge_model). Every saved judge response names the judge model.4.9 m/s^2)\boxed{4.9\,\mathrm{m/s^2}}Judgement: yesJudgement: yes2.00)\boxed{2}Judgement: yes- 13.6 eV)\boxed{-13.6 \text{ eV}}Judgement: yesNo judge call failed (
_failures.jsonlempty).Three extra rows (not committed) check the zero-reward paths with the same policy and judge:
9.8 m/s^2\boxed{4.9}Judgement: no, reward 0\boxedno_boxed, reward 0, no judge callJudgement: yes, reward 1The last row shows a limit of the prompt: the inverted reference contradicted the question's own premise, and the judge's reasoning called it a likely typo and graded the physics instead. Unit tests cover the other zero-reward paths (each gate, unparsed and cut-off replies, rubric penalties and thresholds).
An earlier revision of this server, with the same prompt, gates and verdict semantics but the pre-0.8.0 import paths, judge errors raised instead of masked and the original regexes, has graded the STEM part of a GRPO training run: over 100,000 judge calls with no failed judge call.
Known limits and follow-ups
Answer: yes|no. In the 226,570 stored judge replies, 165 (0.07%) wrapped the verdict in curly quotes or backticks and parsed as no verdict (reward 0). Widening the pattern would change measured behavior, so it is left for a follow-up.equivalence_llm_judge).Compatibility
New component only; no existing server, config or data changes. The config starts at
verified: false. By default the judge ispolicy_model, matchingmath_with_judgeandequivalence_llm_judge; the README shows how to route it to a separate judge model server.🤖 Generated with Claude Code