Repository navigation
feat(deepcad): add CAD verifier and OpenCode multi-turn environment - #5950
Conversation
98ec879 to
886318d
Compare
|
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. |
yfw
left a comment
There was a problem hiding this comment.
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:
resources_servers/deepcad/requirements.txt:1: component locks and Core shard 1.resources_servers/deepcad_opencode/app.py:12: Core shard 2, "no tests ran" and component locks.resources_servers/deepcad/app.py:20-28: Core shard 2.resources_servers/deepcad/configs/deepcad.yaml:34: Core shard 3.resources_servers/deepcad/tests/test_prepare_data.py:200: changed-server tests.resources_servers/deepcad/configs/deepcad.yaml:25: the data gate that runs after the tests pass.
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
Signed-off-by: Rohit Jena <[email protected]>
Signed-off-by: Rohit Jena <[email protected]>
Co-authored-by: Yi-Fu Wu <[email protected]> Signed-off-by: Rohit Jena <[email protected]>
Signed-off-by: Rohit Jena <[email protected]>
Signed-off-by: Rohit Jena <[email protected]>
Co-authored-by: Yi-Fu Wu <[email protected]> Signed-off-by: Rohit Jena <[email protected]>
Co-authored-by: Yi-Fu Wu <[email protected]> Signed-off-by: Rohit Jena <[email protected]>
Signed-off-by: Rohit Jena <[email protected]>
Signed-off-by: Rohit Jena <[email protected]>
Signed-off-by: Rohit Jena <[email protected]>
Signed-off-by: Rohit Jena <[email protected]>
d8bd8f5 to
6540d21
Compare
Signed-off-by: Rohit Jena <[email protected]>
Signed-off-by: Rohit Jena <[email protected]>
| 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"]) |
There was a problem hiding this comment.
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 outrenderer_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_swrites atimeoutmarker (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.
| if not result.error_type and result.return_code in (-signal.SIGSEGV, 128 + signal.SIGSEGV): | ||
| raise ReferenceRejected("Reference sandbox segfault: " + detail) |
There was a problem hiding this comment.
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.
| 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.
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]>
This reverts commit 94ad709. Signed-off-by: Rohit Jena <[email protected]>
Signed-off-by: Rohit Jena <[email protected]>
Signed-off-by: Rohit Jena <[email protected]>
|
/ok to test d740a72 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44131563664 |
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_agentsetting with a lent workspace, target images, rendering feedback, and grading of the finalmodel.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 orlegacy_agentrelay.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_hooksAPI. 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.tomlanduv.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 indata/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.pyin 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 explicittarget_images. Validated lazy rows are accepted without rendering during conversion.Move
data.source_operation_samplingtodata.gym_dataset_hooks.config.source_operation_sampling, selectingresources_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, filesnemo_rl/data/source_operation_sampler.pyandtests/unit/data/test_source_operation_sampler.py, under Apache-2.0. Their Gym destinations areresources_servers/deepcad/dataset/source_operation_sampler.pyandresources_servers/deepcad/tests/test_source_operation_sampler.py; both file headers record the source and revision.