Repository navigation
fix(longmt): run scoring in an isolated Python 3.12 environment - #5780
Conversation
|
/ok to test c3b39b3 |
ananthsub
left a comment
There was a problem hiding this comment.
Running the scorer in its own Python 3.12 process is the right way to keep LongMT working after the move to 3.13, and the scoring code itself carries over unchanged. The changes requested are about failure handling. A single timeout, worker crash, or NaN now permanently disables an actor while the server keeps routing documents to it, so scorer failures turn into zero rewards for the rest of a run (see the comments on scoring_process.py and scoring/worker.py). Setup also now runs on the event loop and repeats on every request after a failure.
The PR description also needs:
- the validation commands that were run, including which tests skip in the server venv;
- smoke-rollout evidence, since this changes how rewards are produced;
- the user-facing changes: first-call provisioning, which needs network access and
uv; the shared-storage requirement for remote actors;LONGMT_SCORING_PYTHON; and the 30-minute request timeout; - a note on the
REVERIFY_MODEaddition, which is unrelated to the Python move and could be its own PR.
A possible follow-up direction, not something to block on: after this PR, the Ray actor only places a process on a GPU and passes JSON lines through. Serving scorer.py as a small HTTP service in its 3.12 environment would remove the actors, the interpreter mirroring and the shared-storage requirement. wmt_translation uses the same Ray actor pattern and could follow the same path.
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
HOLD
The runtime split preserves the inspected scoring math, but the new process boundary has failure paths that can disable an actor permanently or leave a request waiting indefinitely. Cold-cache provisioning also blocks the HTTP event loop. The inline findings include corrections and proposed regression checks.
RISK — Provide real scoring and reward-comparison evidence. The PR currently reports only “all tests passing” and “rollout behavior.” That doesn't establish that the changed interpreter, dependencies, and failure handling preserve the benchmark results. The trusted quality bar requires representative real model rollouts for behavior-changing environment work.
Could you replace those placeholders with the exact validation commands and actual pass/fail/skip results, plus a representative run with compute_segale=true through the real Ray/subprocess path? Include at least two nonempty translations, finite comet_qe values, absent segale_error, and successful subsequent scoring with resident models. For the fixed LongMT benchmarks, provide a matched before/after reward profile on the same saved translations: sample count, mean reward, per-language COMET means, and scoring-error counts. Identify the reference runtime and any inability to run the current base rather than treating missing comparison coverage as a pass. Retain the GPU-free compute_segale=false behavior; a full training run isn't required.
I completed the source review across all 17 changed files, including the omitted wrapper-lock comparison against the merge base and the directly affected callers, tests, and CI paths. The worker/scorer child's report wasn't delivered, so I completed that inspection directly. I couldn't execute checks, install dependencies, or run GPU rollouts in this read-only review. All acceptance checks below are proposed, not executed results; suggested code needs author verification.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| raise ValueError("LongMT scorer returned a non-object response") | ||
| return result | ||
| except BaseException: | ||
| self.close() |
There was a problem hiding this comment.
BLOCKER — Recover the worker before scoring the next document.
After any timeout, malformed response, or worker exit, _request() calls close(). Nothing starts another process. Every later score() on this object fails at the exited-process check. The Ray actor remains alive and delegates to the same object, so round-robin dispatch keeps selecting it and verification returns zero reward with segale_error. With one actor, one failed document therefore makes every subsequent document unscorable; larger pools lose that actor's share for the rest of the run. Previously, an exception in the in-process scorer didn't destroy its resident execution context.
Could ScoringProcess retain its launch arguments and restart/re-handshake on the next request after a transport failure? Reap the old worker and stop its reader before creating a fresh queue and reader, so an old EOF or late response cannot satisfy a new request. Don't automatically replay the failed document, restart after an explicit shutdown, or reload models after successful requests. Ordinary worker {error: ...} responses should remain document-local without requiring a restart. This needs a lifecycle change rather than a safe one-line patch.
Proposed acceptance: extend the broken-worker cases so a first request times out, exits, or emits invalid JSON, then a normal request on the same client succeeds using a newly initialized worker. Assert the old PID is gone, consecutive successful requests retain their PID, a scorer exception doesn't prevent the next success, and explicit close() doesn't resurrect a worker.
There was a problem hiding this comment.
Fixed in cc81880. The client retains its launch configuration and starts a replacement worker after a transport failure, with a fresh queue and reader after cleanup. It does not replay the failed document or restart after explicit shutdown. Ordinary scorer error responses remain document-local, and successful requests retain the worker. Regression tests cover these lifecycle cases; the GPU smoke also confirmed resident-worker reuse.
| from setup_scoring import ensure_scoring_python | ||
|
|
||
| cache_dir = _cache_dir() | ||
| scoring_python = ensure_scoring_python(cache_dir / "longmt-scoring") |
There was a problem hiding this comment.
BLOCKER — Provision the runtime before serving verification requests.
With compute_segale=true and an empty cache, verify() calls _ensure_actors() synchronously, which reaches this new call. Provisioning waits on flock, runs uv sync, and validates imports without yielding or applying timeouts. Other requests on that HTTP worker, including its async health endpoints, cannot progress meanwhile. Holding the setup lock while issuing the first verification is a minimal source-derived trigger. The synchronous Ray readiness wait already existed; this unbounded installation stage before it is new.
Could you provision once during server startup when scoring is enabled, retain the returned interpreter, and pass it into the actor builder? That follows the trusted startup-install contract and restores the invariant that a verification request never performs runtime installation. Keep compute_segale=false free of installation and actor allocation, retain explicit-interpreter validation and serialized/idempotent installation, and keep /reverify_mode itself free of actor allocation. Update the README's first-use provisioning description accordingly.
Proposed acceptance: delay the installer and assert it finishes before serving starts; later verifications must not invoke it again. With scoring disabled, construction and verification must never install or allocate actors. Retain the stateless metadata assertions, and verify a scored request still forwards its source, translation, and target language.
There was a problem hiding this comment.
Fixed in cc81880. Environment provisioning and actor readiness now happen during server construction when scoring is enabled; verification requests do not invoke installation. Scoring-disabled construction skips provisioning and actor allocation, and /reverify_mode does not allocate actors. Explicit-interpreter validation and serialized, idempotent setup are retained. The README now describes startup provisioning rather than first-request provisioning.
| if self.process.poll() is not None: | ||
| raise RuntimeError(f"LongMT scorer exited with code {self.process.returncode}") | ||
| assert self.process.stdin is not None | ||
| self.process.stdin.write(json.dumps(payload, ensure_ascii=False) + "\n") |
There was a problem hiding this comment.
BLOCKER — Include request transmission in the timeout.
The synchronous pipe write() and flush() happen before deadline is created. If a worker stops reading after its ready handshake and a document exceeds the pipe buffer, the actor blocks here indefinitely: the response timeout and cleanup path are never reached. A minimal proposed reproduction is a stand-in worker that emits {"ready": true} and then sleeps without reading, followed by score("x" * 8388608, "b", "fr_FR") with a short timeout. The public request model doesn't bound document length. The actor then cannot service later documents, while verification awaits its Ray result.
Could you start one deadline before transmission and use deadline-aware pipe I/O for both sending and receiving? The complete correction must handle a partial write, terminate/reap the worker on send timeout, and avoid a cleanup flush that can block on the same full pipe. Merely moving the deadline assignment or placing the write in an unsupervised thread won't enforce that invariant. The I/O implementation needs to match the supported platforms, so I don't have a verified drop-in patch.
Proposed acceptance: add the non-reading worker case to the process tests. The large request must raise TimeoutError within the deadline plus bounded cleanup, and its worker must be gone. A reading worker must still receive a document larger than the pipe buffer, including Unicode and embedded newlines, without truncation; consecutive successful requests must remain persistent.
There was a problem hiding this comment.
Fixed in cc81880. A single deadline now covers transmission and response waiting. Stdin uses nonblocking writes with selector-based readiness and partial-write handling; the pipe is
unbuffered so cleanup does not flush into a blocked pipe. A regression sends an 8 MiB request to a nonreading worker, verifies timeout and process cleanup, then checks recovery. It also
verifies a large Unicode/newline payload arrives intact and successful requests reuse the worker.
| except Exception as exc: | ||
| LOG.exception("Document scoring failed") | ||
| result = {"error": f"{type(exc).__name__}: {exc}"} | ||
| responses.write(json.dumps(result, ensure_ascii=False, allow_nan=False) + "\n") |
There was a problem hiding this comment.
RISK — Handle result serialization errors inside the document boundary.
A scorer result such as {"comet_qe": float("nan"), "error": None} reaches json.dumps(..., allow_nan=False) outside the try. Serialization raises ValueError and exits the worker instead of returning an error for that document. The same happens for a non-finite value nested in spans. Scoring converts COMET outputs to floats without a finiteness check, so the transport must handle this result shape. This is distinct from recovering a worker that genuinely crashes.
Could lines 41–48 serialize within the protected block, keeping the pipe write outside it?
try:
LOG.info("Starting document scoring")
result = scorer.score(**json.loads(line))
payload = json.dumps(result, ensure_ascii=False, allow_nan=False)
LOG.info("Completed document scoring")
except Exception as exc:
LOG.exception("Document scoring failed")
payload = json.dumps({"error": f"{type(exc).__name__}: {exc}"}, ensure_ascii=False)
responses.write(payload + "\n")This preserves finite results, None fields, Unicode, and the existing scorer-exception response. Don't replace non-finite scores with a valid-looking zero.
Proposed acceptance: run the real worker under Python 3.12 with a stub scorer returning a top-level NaN, a nested NaN/Infinity, an exception, and then a finite result. Each failure must produce one error object; the subsequent finite result must succeed on the same PID with its fields unchanged.
There was a problem hiding this comment.
Fixed in cc81880. json.dumps(..., allow_nan=False) is now inside the per-document protected block, with the response write outside it. Non-finite output becomes a document error rather than a
worker crash or valid-looking zero score. Real-worker Python 3.12 tests cover non-finite results, scorer exceptions, and subsequent successful scoring on the same PID.
| if not self.config.use_extra_gpu and len(live) == G * A: | ||
| live = [live[g * A + s] for s in range(A) for g in range(G)] | ||
| self._segale_actors = live | ||
| self._actors_init_attempted = True |
There was a problem hiding this comment.
RISK — Remember failed pool initialization instead of retrying for every document.
If every actor fails initialization or misses the 300-second deadline, _ensure_actors() kills the actors and raises before this assignment. The flag remains false, so each subsequent verification provisions/checks the runtime, allocates another pool, waits again, and fails again. A missing GPU resource is enough to turn queued documents into repeated initialization cycles. These attempts are serialized on one event loop; concurrent retries aren't necessary to cause the degradation. The previous implementation marked the attempt before starting, allowing later calls to reach actor_unavailable.
Could you restore remembered failure, or use an explicit bounded retry/backoff policy? The smallest correction retaining the previous behavior is to restore this assignment immediately after the initial guard and remove the success-only assignment here:
if self._actors_init_attempted:
return
self._actors_init_attempted = TrueKeep the new cleanup of rejected actors. Successful initialization must reuse its pool; partial success must retain only ready actors; a complete pool must retain its GPU-interleaved dispatch order.
Proposed acceptance: change the new startup test so an all-failed setup is followed by another verification without creating another pool, returning the remembered failure or segale_error="actor_unavailable". Retain failed-actor cleanup assertions and add successful/partial-pool reuse and dispatch cases.
There was a problem hiding this comment.
Fixed in cc81880. Initialization is marked attempted before provisioning and actor creation. Failed startup is remembered and requires an explicit server restart; requests do not repeatedly
create pools. Cleanup of rejected actors is retained. Added tests cover complete failure, successful and partial pool reuse, and the complete pool’s GPU-interleaved dispatch order.
| "langdetect", | ||
| "sacrebleu[ja,ko]>=2.4", | ||
| ] | ||
| dependencies = ["nemo-gym[dev,ray]"] |
There was a problem hiding this comment.
RISK — Restore regular execution of the scoring-runtime tests.
Removing the heavy dependencies from the wrapper is appropriate, but the moved dependency tests still import them in pytest's interpreter. Changed-server CI runs the wrapper suite, and its launcher doesn't run a scorer environment. Thus the ersatz weights_only guards and dependency-specific download tests now skip there. The dependency-free download-helper tests still run. Separately, the only real-worker test requires LONGMT_TEST_PYTHON, which the inspected CI paths don't set; the remaining process tests use replacement workers.
Could CI execute the dependency-specific tests in the locked Python 3.12 scorer environment and run the real worker protocol tests with a stub scorer? Keep the wrapper free of scoring dependencies. Required imports in the dedicated scorer run should fail rather than disappear behind optional-dependency skips. Wire the focused step into the existing test aggregation so its result is accounted for.
Proposed acceptance: both synthetic-checkpoint tests execute without skips: the argparse.Namespace checkpoint loads and weights_only is not False. The ersatz/LASER/COMET download cases execute and preserve their cache/local-resolution assertions. The real worker covers finite output, a serialization failure, a scorer exception, and a subsequent success. The ordinary Python 3.13 suite must still run without the heavy scoring packages.
There was a problem hiding this comment.
Fixed in cc81880. The dedicated Python 3.12 scoring job runs with required imports, so dependency tests cannot silently skip. Its result is included in the final CI aggregation, with
regression coverage for failure, cancellation, and unexpected skips. The wrapper remains free of the heavy scoring dependencies. Locally, the Python 3.13 validation had 83 passes and nine
expected dependency skips; the Python 3.12 scoring suite had 16 passes and no skips.
| "laser-encoders @ git+https://github.com/jeffwillette/LASER.git@14ba8c31efe48c351333ff0159fe2d25a6aaee37", | ||
| "ersatz @ git+https://github.com/jeffwillette/ersatz.git@d21f40499be09668d7f9ecb19468be1acf1b17be", | ||
| "torch==2.12.0", "torchvision==0.27.0", "setuptools>=70,<81", | ||
| "unbabel-comet==2.2.7", "transformers>=4.17,<5", |
There was a problem hiding this comment.
NOTE — Suggestion: retain an auditable security-floor exception for the scorer.
The new scorer locks Transformers 4.51.3, below the shared transformers>=5.17.0 floor. The old wrapper recorded its <5 exception; that record is removed here, while the floor audit intentionally skips non-Gym projects, including this scorer. The COMET compatibility test checks the supported range but doesn't expose the exception to that audit.
Could you record the scorer's scoped Transformers exception and include this known standalone runtime in the floor audit? This is an auditability suggestion, not evidence of an exploitable vulnerability. Preserve COMET's <5 and Hub's <1 compatibility assertions; don't copy unrelated Gym overrides wholesale into the isolated scorer. Choose the exception representation together with the audit change rather than adding an unused policy entry.
Proposed acceptance: the audit visits the scorer, recognizes its declared exception, and rejects a below-floor version when that exception is absent. Retain the existing COMET compatibility and wrapper/scorer isolation assertions. I found no shared protobuf floor in the inspected policy, so protobuf's changed version isn't itself evidence of a floor violation.
There was a problem hiding this comment.
Implemented in cc81880. The scorer is explicitly registered as a standalone project in the component policy, and the audit now includes it. Its compatibility exceptions are documented and
checked rather than being unused policy entries. Unrelated Gym overrides are not copied into the scorer. Existing COMET compatibility and wrapper/scorer isolation checks are retained, and
regression coverage rejects standalone policy drift.
| LOG.info("Installing locked Python 3.12 scoring environment at %s", root) | ||
| subprocess.run( | ||
| ["uv", "sync", "--locked", "--no-dev", "--python", "3.12", "--project", str(PROJECT)], | ||
| env={**os.environ, "UV_PROJECT_ENVIRONMENT": str(root / ".venv")}, |
There was a problem hiding this comment.
NOTE — Suggestion: make automatic provisioning portable with the shared cache.
This command controls the venv location but doesn't place or mirror its underlying Python 3.12 installation beneath the cache. The actor uses the returned path on another node, while the Gym-side interpreter explicitly mirrors its installation. If the provisioned venv relies on a host-local interpreter absent on that node, sharing the venv alone won't make it executable.
The README documents that the Python installation must also exist at the same path on every node, so this is a portability improvement, not an undocumented guarantee. Could automatic setup install a managed interpreter beneath the shared cache, or validate this prerequisite explicitly? uv's implementation isn't mounted here, so I can't confirm which interpreter it selects or offer a verified replacement command.
Preserve locked/idempotent installation, failed installs without a ready marker, and explicit LONGMT_SCORING_PYTHON environments that are validated without modification.
Proposed acceptance: provision while a host-local Python is available, then launch the returned interpreter in a second container sharing the cache, source, and model mounts but not that host's interpreter directory. It should import the scoring dependencies successfully, or setup should clearly reject the unmet portability prerequisite. Retain all three setup regression cases.
There was a problem hiding this comment.
Implemented the provisioning change in cc81880: the managed Python installation now lives under the shared cache alongside its venv. Locked/idempotent installation, no ready marker after
failed installation, and validation without modification of explicit interpreter overrides are retained and tested. The GPU smoke passed using LONGMT_SCORING_PYTHON; the suggested second-
container test without the host interpreter mount has not been run.
cc81880 to
40f29a4
Compare
|
/ok to test 40f29a4 |
644a147 to
481baac
Compare
|
/ok to test 481baac |
|
/ok to test 3d1f020 |
Keep Gym and Ray on Python 3.13 while running SEGALE, LASER, and COMET in a persistent Python 3.12 subprocess per actor. Add locked scoring dependencies, environment provisioning and validation, subprocess lifecycle handling, and regression tests. Preserve LongMT's API and scoring behavior. Declare stateless reverification support so Gym can score completed translations independently of their generation session, with HTTP regression coverage. Signed-off-by: Jeff Willette <[email protected]>
Replace obsolete scoring exceptions with the wrapper's NumPy constraint. Check COMET dependencies in the scorer lock and add regression coverage for Python and dependency isolation. Signed-off-by: Jeff Willette <[email protected]>
Recover failed workers, bound request transmission, and provision scoring before serving requests. Preserve document-local errors and actor reuse. Run Python 3.12 scoring tests in CI, audit dependency exceptions, and keep the managed interpreter in the shared cache. Signed-off-by: Jeff Willette <[email protected]>
Signed-off-by: Jeff Willette <[email protected]>
Signed-off-by: Jeff Willette <[email protected]>
Signed-off-by: Jeff Willette <[email protected]>
fa36fb5 to
2a5f93b
Compare
|
/ok to test 2a5f93b |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43932309110 |
Main's NVIDIA-NeMo#5899 removes the grader's request and response byte caps. It conflicts with this branch in the grader's app.py, README.md and tests/test_app.py; its task_data.py change merges cleanly. The merge takes main's cap-free request handling, also for /finish and /code_exec, and drops agentic_max_response_bytes, which set those caps in finish_tool mode: the config field, its line in the agentic recipe and the three tests that exercised it. The command, output, source and semantic-validator limits stay. Main's NVIDIA-NeMo#5691 (the Stirrup agent's app.py) and NVIDIA-NeMo#5720 and NVIDIA-NeMo#5780 (scripts/component-lock-policy.json) change files this branch also changes, in other lines; neither side's changes are altered. Signed-off-by: Erik Arakelyan <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
What does this PR do?
Keep Gym and Ray on Python 3.13 while running LongMT's SEGALE, LASER, and COMET scoring stack in a persistent Python 3.12 subprocess per Ray actor. This isolates the scoring dependencies from Gym's Python requirements while preserving the translation-quality scoring calculation.
Scoring initialization runs in
setup_webserver(), after Gym's dry-run return and before serving requests. Constructing the server or running with+dry_run=truedoes not provision the scorer or allocate its GPU actors.The subprocess protocol bounds request transmission and response waiting, handles partial pipe writes, and recovers workers after transport failures. Serialization failures remain local to the affected document. Failed evaluations are masked verifier errors and are excluded from quality aggregation; they are not treated as translation-quality zeroes or replayed automatically. Successful requests reuse resident models.
The change also adds a dedicated Python 3.12 scoring CI job, native build-tool provisioning, regression coverage, and explicit dependency-policy exceptions for the isolated scorer.
Validation
Commands run from Gym, with interpreter paths abbreviated:
Results for these runs:
git diff --checkpassed. The private guardwords check could not execute because its catalog was unavailable.Rollouts
Scored five saved Gym translations and two saved SDG translations through the real LongMT verifier, Ray actor, and Python 3.12 scoring subprocess. No translations were regenerated.
All seven results had nonempty translations, finite reward and COMET values, no
segale_error, and completed, unmasked evaluations. Repeating the first sample also succeeded. The scoring subprocess PID remained unchanged across the run and repeat, confirming resident-worker reuse.Compatibility and benchmark impact
None. This is a bugfix that allows for separate Python environments for longmt due to dependencies requiring 3.12 while Gym has bumped to 3.13
Checklist
pre-commit run --all-files) (so CI lint/format checks pass).git commit -s) (so the DCO check passes).