Skip to content

feat(stem_judge): add a STEM LLM-judge resources server - #6518

Merged
yaoyu-33 merged 3 commits into
mainfrom
jiachengx/stem-judge-resources-server
Nov 20, 2026
Merged

yaoyu-33 merged 3 commits into
mainfrom
jiachengx/stem-judge-resources-server

Conversation

@jiacheng-xu

@jiacheng-xu jiacheng-xu commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • Answer rows. One judge call with the stem_v11 prompt. The judge's last Judgement: 'yes'|'no', read from its text after its own last </think>, gives reward 1 or 0; the evaluation saves it as verdict_label: "Judgement: yes|no", the form Gym's rollout recovery checks against the reward. Answer rows must carry a non-empty expected_answer (or metadata.expected_answer); a row without one fails request validation instead of being judged against nothing.
  • Rubric rows. A row with a rubric list 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 at rubric_pass_fraction (threshold).
  • Per-row answer contract. answer_format: boxed rows need a non-empty last \boxed{}; free rows (explanations, derivations) are judged on the whole final answer. Under the default boxed_judge_input: final_answer the box is a format gate and the judge grades the whole final answer; box shows the judge only the box.
  • Gates that score 0 without a judge call (the truncation gate is optional in the upstream server and always on here), each recorded in 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 over max_box_chars (box_too_long, off by default), or a final answer over max_answer_chars (answer_too_long, 16,000 characters).
  • Reference rendering. A reference that starts with - 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 eV reads as a markdown list item and the judge drops the sign.
  • Judge failures. Judge calls go through 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 with status="failed" or an error is a judge failure and masks the row. REVERIFY_MODE is STATELESS; checkpoints replay verify (checkpoint_mode = "stateless", checkpoint_verify = "replay"), like equivalence_llm_judge.
  • Task-data schema. task_data.py exports TaskData, the row contract; StemJudgeRunRequest inherits it, so dataset tooling and verify() apply the same rules.
  • Optional per-rollout JSONL log (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_v11 prompt is resources_servers/stem_llm_judge/prompt_templates/stem_llm_judge.txt from Grigor Nalbandyan's stem_llm_judge resources server, branch gnalbandyan/stem_llm_judge at d002fd9 in this repository (NVIDIA, Apache-2.0), byte for byte; the test suite pins its hash. Adapted from the same commit's app.py: the verdict patterns (rewritten with possessive quantifiers, see Validation), PROBLEM_EXTRACT_REGEX, the question, assistant-text, truncation and step helpers, the metadata.expected_answer fallback, the judge concurrency limit and the generation-log record. Affected files: resources_servers/stem_judge/app.py and resources_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 with stem_v11 on 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_judge judge P / R / F1 stem_v11 P / R / F1
Physics 0.993 / 0.718 / 0.834 0.976 / 0.918 / 0.946
Non-physics 0.939 / 0.596 / 0.729 0.935 / 0.921 / 0.928

The 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_v11 recovers 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.py TestSchemaPresence and TestRepoDataMatchesSchemas: passed; gym env schema --resources-server stem_judge prints the schema.
  • pre-commit run --all-files: all hooks passed (the README table row comes from update-readme-table).
  • data/example_metrics.json from gym dataset collate "+config_paths=[resources_servers/stem_judge/configs/stem_judge.yaml]" +output_dirpath=data/stem_judge +mode=example_validation.
  • The tests cover every gate, the grading-observation outcomes (parsed → completed, unparsed or cut off → unknown, transport failure → failed), verdict and rubric parsing, rubric scoring, the reference rendering, request validation (rubrics, missing references, every example row), question extraction (string input, content lists, regexes), the shipped config and prompt hash, cut-off and reasoning-only judge replies, a failed judge call masked by judge_failsafe, the reverify mode, and the saved shape of rubric evaluations.
  • Verdict regex. The stem_v11 patterns backtrack catastrophically on degenerate judge text ("Answer:" + "\n" * 60 took 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 trailing Answer: Yes and 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_criteria tries 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.
  • Local pre-push review (three independent passes against .agents/skills/pr-review per 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 secret comment 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.jsonl holds 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 is nvidia/nemotron-3.5-lightning-30b-a3b and the judge nvidia/nemotron-3-ultra-550b-a55b, both on the NVIDIA API; the commands are in the server README's "Running" section (a judge_model server in judge.yaml and ++stem_judge.resources_servers.stem_judge.judge_model_server.name=judge_model). Every saved judge response names the judge model.

Row Format Policy final answer Judge Reward
Incline acceleration (ref. 4.9 m/s^2) boxed \boxed{4.9\,\mathrm{m/s^2}} Judgement: yes 1
Lithium 2s vs 2p (explanation) free penetration and shielding put 2p higher Judgement: yes 1
Pendulum period to second order (rubric) free second-order period from a perturbation expansion r1, r2 met; penalty r3 not met 1.0
pH of 0.010 M HCl (ref. 2.00) boxed \boxed{2} Judgement: yes 1
Hydrogen ground state (ref. - 13.6 eV) boxed \boxed{-13.6 \text{ eV}} Judgement: yes 1

No judge call failed (_failures.jsonl empty).

Three extra rows (not committed) check the zero-reward paths with the same policy and judge:

Row Final answer Outcome
Incline, reference changed to 9.8 m/s^2 \boxed{4.9} Judgement: no, reward 0
Prompt says not to use \boxed "The pH is 2, as 0.010 M HCl fully dissociates at 25 °C." no_boxed, reward 0, no judge call
Lithium explanation, reference inverted ("2p is lower") correct explanation Judgement: yes, reward 1

The 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

  • The verdict patterns keep upstream's semantics, including two quirks a reviewer found: the primary pattern has no word boundary and accepts only straight quotes around the verdict, and the fallback accepts a bare 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.
  • No judge-call timeout beyond the HTTP client's (as in equivalence_llm_judge).

Compatibility

New component only; no existing server, config or data changes. The config starts at verified: false. By default the judge is policy_model, matching math_with_judge and equivalence_llm_judge; the README shows how to route it to a separate judge model server.

🤖 Generated with Claude Code

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]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 19, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the risk:high Autobot PR risk: high label Nov 19, 2026
…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]>
@jiacheng-xu
jiacheng-xu marked this pull request as ready for review November 19, 2026 22:08
@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:evaluation Evaluation, rollout collection, reward profiling, comparison, and exporters needs-review PR is ready for code review and waiting on a reviewer labels Nov 19, 2026

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread resources_servers/stem_judge/app.py Outdated
return self


class StemJudgeRunRequest(BaseRunRequest):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):
    pass

Keep 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread resources_servers/stem_judge/app.py Outdated
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])]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@Kipok

Kipok commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

/ok to test e6002b1

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 19, 2026 23:04
@github-actions

Copy link
Copy Markdown
Contributor

@yaoyu-33
yaoyu-33 requested a review from init-nikhil November 19, 2026 23:37

@yaoyu-33 yaoyu-33 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. The 118 component tests passed, and I verified that the documented vLLM judge path emits its verdict in a single text block.

@yaoyu-33 yaoyu-33 added ready-to-merge PR is approved, current, and waiting for final CI or merge and removed needs-review PR is ready for code review and waiting on a reviewer labels Nov 20, 2026
@yaoyu-33
yaoyu-33 enabled auto-merge November 20, 2026 00:16
@yaoyu-33
yaoyu-33 added this pull request to the merge queue Nov 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44644674134

Merged via the queue into main with commit d6d3dd6 Nov 20, 2026
73 checks passed
@yaoyu-33
yaoyu-33 deleted the jiachengx/stem-judge-resources-server branch November 20, 2026 00:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:evaluation Evaluation, rollout collection, reward profiling, comparison, and exporters feature New capabilities, enhancements, or enablement work ready-to-merge PR is approved, current, and waiting for final CI or merge risk:high Autobot PR risk: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants