Skip to content

feat(deepcad): add CAD verifier and OpenCode multi-turn environment - #5950

Merged
yfw merged 17 commits into
mainfrom
rohit/cad-rl
Nov 17, 2026
Merged

yfw merged 17 commits into
mainfrom
rohit/cad-rl

Conversation

@rohitrango

@rohitrango rohitrango commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What changes

Adds a CAD reconstruction environment that grades CadQuery programs against reference STEP geometry. It provides a simple-agent setting and a stock opencode_agent setting with a lent workspace, target images, rendering feedback, and grading of the final model.py. The OpenCode default is 131,072 context tokens, a 32,768-token per-call output cap, and disabled compaction/delegation. The resources server owns workspace collection and cleanup; there is no custom CAD agent or legacy_agent relay.

CAD-specific lazy materialization and source/operation sampling live in Gym. Metadata indexing does not render or process prompts. Selected repeated rows share one bounded render, reuse an atomic cache, and retain their routing and sampling settings. The sampler provides independent uniform source draws per prompt without batch quotas, the existing uniform/operation mixture, and deterministic checkpoint/resume behavior without importing PyTorch. Training frameworks use the environment-neutral load_dataset_hooks API. The corresponding CAD NeMo-RL branch now has generic adapters and migrated recipes.

Review fixes distinguish invalid predictions from inconclusive verification, check provider errors during artifact inspection, and retry the same source in fresh sandboxes with a bounded retry count. A fresh isolated verifier process validates, fuses, and seals the prediction within the remaining execution budget. The scorer preserves that union. Workspace cleanup must succeed before grading. Prepared OpenCode rows explicitly carry target images in task data, matching the current Environment Server seed protocol.

Five small synthetic examples, their STEP references, dataset metrics, and actual single-turn rollout records satisfy the example-data gate. Component dependencies use pyproject.toml and uv.lock. No separate issue is needed: these changes address this PR's CAD review feedback.

Validation

  • Uniform-source sampling follow-up: 22 focused sampler tests passed, including source/operation mixture statistics, arbitrary positive batch sizes (1, 2, 4, and 64), and deterministic checkpoint/resume with 0 and 2 workers. All-file pre-commit checks passed. This metadata/index-sampling change does not change agent or verifier execution; fresh model rollout evidence is not required for it.

  • Earlier Linux checks: 280 CAD tests passed, no skips, including numerical B-rep/mixed-IoU checks, overlapping/disjoint-solid parity, sealing and execution-budget enforcement, prediction/infrastructure classification, session cleanup, and sampler resume with 0 and 2 workers.

  • Earlier Linux checks: 34 NeMo-RL integration tests passed, including generic hook dispatch, initial-image attachment before GRPO repetition, configuration compatibility, and StatefulDataLoader/Arrow integration. The sampler cases overlap the CAD suite.

  • Real lazy-render test: 16 repeated rows cause exactly one cold renderer invocation; a warm request causes none and preserves identical inputs and caller settings.

  • All 23 migrated CAD recipes retain their exact sampling settings and every other configuration value.

  • Focused NeMo-RL adapter type check passed. Gym all-file pre-commit, package layering, and whitespace checks passed. The private guardword catalog is unavailable, so its content scan was skipped.

  • Fresh real-model smoke on PR source 6540d2130: five tasks × two runs per setting. Single-turn mean B-rep IoU 0.933333; stock-OpenCode mean 1.0. All 20 final episodes were unmasked, with no grading failure kinds. Five actual single-turn records were refreshed in data/example_rollouts.jsonl; these compact CI fixtures omit optional token arrays, which remain in the full validation captures.

  • All 20 saved inputs retain prompts and three decodable target PNGs. OpenCode wrote/collected model.py in every episode, rendered twice per episode, and made 14 preview reads. Recorded inference requests confirm additional preview PNGs reached the model in every episode. These are controlled loop smoke tests, not benchmark results.

  • Native single-turn responses carry token IDs/log probabilities. Standard Gym collection reconstructs all 72 OpenCode model calls without masking or losing generated tokens; all 62 actual parent/child token-prefix comparisons and finite/aligned log-probability checks passed. The standalone diagnostic requires preserving prior reasoning (truncate_history_thinking: false); the initial configuration exposed six masked reconstructions before this fix.

  • On all five tasks, reference-as-answer scored 1.0; a valid, severely mismatched solid scored 0–1.91e-9. Cleanup found no remaining harness processes, service ports, workspace instances, or verifier sandboxes. Validation compute was released without changing production jobs.

  • Results and standalone capture overrides are documented in resources_servers/deepcad/OPENCODE.md. The smoke used Linux ARM64, Apptainer workspaces, Enroot grading, stock OpenCode 1.17.11, and the Mixed76 step-76 checkpoint at a 131,072-token context limit.

Compatibility and scope

  • Each prompt now samples its source uniformly with replacement; individual batches can contain unequal source counts. Batch size need not divide by source count. Previous quota-sampler checkpoints require a fresh dataloader state.

  • Regenerate OpenCode manifests with prepare_opencode.py; workspace seeds now use explicit target_images. Validated lazy rows are accepted without rendering during conversion.

  • Move data.source_operation_sampling to data.gym_dataset_hooks.config.source_operation_sampling, selecting resources_servers.deepcad.dataset.training. Obsolete configs fail with migration instructions.

  • Operation shaping is disabled by default and uses verifier-side source AST analysis. The response field is source_operations. Dead code and unrelated methods with matching names can count; enabled-bonus scores differ from the previous runtime-trace version.

  • Corpus ingestion, research datasets, training/Slurm launch tooling, optional API cheatsheets, orientation overlays, and other experimental reward variants remain outside this PR. The full Gym checkout retains its superset features.

  • The sandbox image supports pinned amd64 and arm64 OpenCode/plugin artifacts. ARM64 deployments must apply the documented digest overrides. Trusted artifact sealing requires separate model/controller users, as supplied by the Docker image.

Remaining validation

Default Docker image build and actual deployment isolation remain unvalidated by the Apptainer/Enroot smoke. The examples do not saturate the 128k context window or validate distributed training tensor/media handoff. The standalone server lacks required_prefix_token_ids, so the diagnostic disables prefix supply and directly verifies generation-time continuity; native training retains exact-prefix supply. No production jobs or dependencies were changed.

Source attribution

The source/operation sampler and its tests are adapted from the CAD branch of NVIDIA-NeMo/RL, revision f2c87657d570be0e5293b57bd9b5e45e60087848, files nemo_rl/data/source_operation_sampler.py and tests/unit/data/test_source_operation_sampler.py, under Apache-2.0. Their Gym destinations are resources_servers/deepcad/dataset/source_operation_sampler.py and resources_servers/deepcad/tests/test_source_operation_sampler.py; both file headers record the source and revision.

@rohitrango rohitrango added feature New capabilities, enhancements, or enablement work area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers labels Nov 10, 2026
@copy-pr-bot

copy-pr-bot Bot commented Nov 10, 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.

@copy-pr-bot

copy-pr-bot Bot commented Nov 10, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@rohitrango rohitrango changed the title feat(deepcad): add CAD reconstruction environments and multi-turn OpenCode harness feat(deepcad): add CAD verifier and OpenCode multi-turn environment Nov 10, 2026
@rohitrango
rohitrango marked this pull request as ready for review November 13, 2026 19:54
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 13, 2026 19:55

@yfw yfw 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.

HOLD. One data bug gives silent wrong rewards, and the required CI job Nemo_CICD_Test is red for five reasons that this PR causes. A sixth, the data gate, fails as soon as those are fixed.

The silent wrong rewards come from the reference file names at prepare_gym.py:726. The design comment at deepcad_opencode.yaml:84 recommends moving the OpenCode setting to stock opencode_agent. Our Harness-Ready Environments runbook walks through that move. The move does not block merge, and the choice is yours.

DeepCAD is a useful environment to have in Gym, and the verifier design is careful. Generated code runs in a separate sandbox with no network, and reference STEP files never leave the host. The scorers are pure functions with real STEP-based tests. Missing references and sandbox failures are masked rather than scored, as the README documents.

Process: the PR merges cleanly with main, and CI ran on this head, so no /ok to test is needed. Merge requires Lint check, Nemo_CICD_Test and DCO. Lint check and DCO pass. Nemo_CICD_Test fails in component locks, unit tests and changed-server tests, and each cause has an inline comment:

copyright-check is red but not required (mixed_iou.py:1). The non-blocking Environment Server compliance job flags the agent for defining run() and for having no sessions, which the design comment covers. Pre-commit passes at this head.

PR description: it says "This remains a draft pending ...", but the PR is not a GitHub draft. Please mark it as a draft until the rollout evidence that README.md:50-52 asks for is in. The note that the 7 deselected tests are VTK rendering cases is not accurate. 4 of them import a module that the PR does not contain, 1 needs libosmesa6, and 2 pass on Linux. The description also names an internal fork and a cluster. Please remove those names.

Local test runs on CPU at this head: resources_servers/deepcad gives 144 passed and 5 failed, the same as CI. The agent gives 12 passed, and resources_servers/deepcad_opencode gives "no tests ran". With the CI fixes from the inline comments applied together, resources_servers/deepcad has no failures and 1 skip, the diagonal render test that needs libosmesa6. The agent gives 11 passed, and the pinned ruff is clean. This review ran no live model and no Docker.

Generated by Claude Code

Comment thread resources_servers/deepcad/app.py Resolved
Comment thread resources_servers/deepcad/operations.py Resolved
Comment thread resources_servers/deepcad/app.py Resolved
@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 16, 2026 18:39
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the needs-review PR is ready for code review and waiting on a reviewer label Nov 16, 2026
@rohitrango
rohitrango marked this pull request as draft November 16, 2026 19:17
@rohitrango
rohitrango marked this pull request as ready for review November 16, 2026 21:47
@rohitrango
rohitrango marked this pull request as draft November 16, 2026 22:07
@rohitrango
rohitrango marked this pull request as ready for review November 16, 2026 23:02
Comment on lines +181 to +219
except subprocess.TimeoutExpired as exc:
if record.get("source_kind") != "cad_corpus" or not config.reference_catalog:
raise
detail = {
"reason": f"Reference render exceeded {config.timeout_s}s: {record['asset_id']}",
"asset_id": record["asset_id"],
"source_sha256": record["source_sha256"],
"timeout_s": config.timeout_s,
"status": "render_timeout_unverified",
}
temporary = timed_out.with_suffix(".building")
temporary.write_text(json.dumps(detail))
temporary.replace(timed_out)
logger.warning("Quarantined reference render: %s", detail)
raise ReferenceRenderTimeout(detail["reason"]) from exc
failure = result.with_suffix(".rejected.json")
if process.returncode in (-signal.SIGSEGV, 128 + signal.SIGSEGV):
# A native CAD/render crash belongs to this input; retain evidence
# and use the same deterministic replacement as invalid references.
failure.write_text(
json.dumps(
{
"reason": f"Reference render segfault for {record['id']} (return_code={process.returncode})",
"return_code": process.returncode,
"stderr": process.stderr[-2000:],
"status": "segfault_quarantined",
}
)
)
if failure.exists():
from resources_servers.deepcad.dataset.corpus_inputs import ReferenceRejected

detail = json.loads(failure.read_text())
detail.update(asset_id=record["asset_id"], source_sha256=record["source_sha256"])
temporary = rejected.with_suffix(".building")
temporary.write_text(json.dumps(detail))
temporary.replace(rejected)
logger.warning("Quarantined lazy reference: %s", detail)
raise ReferenceRejected(detail["reason"])

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.

resources_servers/deepcad/dataset/lazy_inputs.py:181-219

One renderer crash or one slow render marks a reference bad for good, so an outage changes the training task.

The README says "Provider and renderer outages propagate instead of silently changing the selected task" (README.md:174-175). Two paths here write a permanent marker after one failure:

  • A segfault of the renderer process writes .rejected.json (L197-L219). A crash in the host's VTK or Mesa is an outage, not a bad reference. The cache key leaves out renderer_python (L87-L99), so the marker stays after the renderer is fixed. With a renderer that crashes once and then works, 3 of 3 runs returned the replacement asset, and the original was never rendered again. With a renderer that always crashes, one 8-row batch left 38 assets marked bad before it failed.
  • The 180 s timeout_s writes a timeout marker (L181-L195). That time also covers sandbox start, image pull and the wait on the reference's file lock, so a slow provider marks a good reference bad. (Read from the code; not run.)

Also, a non-corpus record that segfaults raises KeyError: 'asset_id' at L214, and the crash details are lost.

Suggested fix, in prose because it changes the control flow: mark a reference bad only when the same failure happens twice, each time in a fresh renderer process. Raise the first failure as an outage. Then a deterministic crash or hang is still replaced, and a one-time crash or slow start is not. Use record.get("asset_id") in the detail.

Comment on lines +130 to +131
if not result.error_type and result.return_code in (-signal.SIGSEGV, 128 + signal.SIGSEGV):
raise ReferenceRejected("Reference sandbox segfault: " + detail)

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.

resources_servers/deepcad/dataset/corpus_inputs.py:130-131

A reference program killed for memory raises an outage, so training stops at the same batch after every resume.

The reference sandbox has a 2 GiB memory limit (L103). When the kernel kills the program, the shell exits 137 with no traceback. That case matches neither the segfault check at L130-L131 nor the patterns at L132-L137, so it raises RuntimeError, not ReferenceRejected. With a stub exec that returns 137, the result is RuntimeError | is ReferenceRejected: False. The sampler picks the same batch again on resume, because the seed, epoch and batch number decide it (source_operation_sampler.py:136). So the run fails at the same step each time.

Suggested fix: treat a kill by the memory limit like the segfault case.

Suggested change
if not result.error_type and result.return_code in (-signal.SIGSEGV, 128 + signal.SIGSEGV):
raise ReferenceRejected("Reference sandbox segfault: " + detail)
if not result.error_type and result.return_code in (
-signal.SIGSEGV,
128 + signal.SIGSEGV,
-signal.SIGKILL,
128 + signal.SIGKILL,
):
raise ReferenceRejected("Reference sandbox crash or memory kill: " + detail)

Other per-reference failures that stay RuntimeError (an OCC error other than Geom_UndefinedValue, an export failure in runner.py) stop the run the same way. If they should stop it, please say so in the README, with the step to quarantine the asset by hand.

Comment thread resources_servers/deepcad/operations.py Resolved
Enroot rejects /dev/null because --rc requires a regular file. Use a
passthrough script in the sandbox staging directory and include script
creation and process launch in failed-create cleanup.

Cover argument and exit-code forwarding, bypass opt-out, and cleanup.
Validated all 63 provider tests, repository pre-commit checks, and a real
Linux ARM64 Enroot startup with a rejecting image entrypoint.

Signed-off-by: Rohit Jena <[email protected]>
@yfw
yfw enabled auto-merge November 17, 2026 16:17
@yfw

yfw commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

/ok to test d740a72

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 17, 2026 16:39
@yfw
yfw added this pull request to the merge queue Nov 17, 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/44131563664

Merged via the queue into main with commit a031b07 Nov 17, 2026
95 of 96 checks passed
@yfw
yfw deleted the rohit/cad-rl branch November 17, 2026 17:13
@yfw
yfw restored the rohit/cad-rl branch November 17, 2026 17:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants