Skip to content

Add MolDeTox resources server - #3437

Merged
bxyu-nvidia merged 3 commits into
mainfrom
rshahbazyan/add-moldetox-benchmark
Sep 21, 2026
Merged

bxyu-nvidia merged 3 commits into
mainfrom
rshahbazyan/add-moldetox-benchmark

Conversation

@rimashahbazyan

@rimashahbazyan rimashahbazyan commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds MolDeTox as a NeMo Gym environment: toxicity-aware molecular editing
built on toxicity cliffs — pairs of structurally similar molecules with
opposite measured toxicity for the same endpoint. Given a toxic molecule and an
endpoint, the model must produce the minimally-edited non-toxic partner.

Scoring is fully deterministic — canonical-SMILES and SAFE-fragment
comparison via RDKit. There is no judge model, no external service, and no
toxicity predictor anywhere in the scoring path; the gold answers are
experimentally measured pairs.

All eight upstream QA configs are covered: three tasks × single/multi, with
Task 3 in both SMILES and SAFE output form.

Benchmark at a glance

Paper arXiv:2605.12181 — "MolDeTox: Evaluating Language Model's Stepwise Fragment Editing for Molecular Detoxification"
Upstream repo None exists. The paper's only availability statement is the HF dataset; the sole GitHub link anywhere in it is datamol-io/safe, a third-party library. Appendix D repeatedly says "the code", so an implementation exists internally — it was not released.
Hugging Face MolDeTox/MolDeTox, CC-BY-4.0, ungated
Pinned revision 059e1926fa62a07c3f01afadadf72cce154cfb7f — upstream revised the files on 2026-08-27 and split sizes changed, so the name alone is not a stable reference
Source material Therapeutics Data Commons, FDA, SIDER
Size 8 QA configs, 7,904 test rows; upstream also ships ~202k train rows, which nothing here reads

Configs

Config Test rows scoring_mode Model must produce
task1_single 1,026 fragments_task1 The one fragment driving toxicity
task1_multi 950 fragments_task1 Two or more toxic fragments
task2_single 943 fragments_task2 The one replacement fragment
task2_multi 1,033 fragments_task2 Two or more replacement fragments
task3_smiles_gen_single 943 smiles Whole detoxified molecule, as SMILES
task3_smiles_gen_multi 1,033 smiles Same, multi-fragment edit
task3_safe_gen_single 943 safe Whole detoxified molecule, as SAFE
task3_safe_gen_multi 1,033 safe Same, multi-fragment edit

single and multi are a property of the item — how many fragments must change
— not a multi-turn protocol. Every config is one-shot. The ninth upstream config,
toxicitycliff, is the source pair table rather than a task; it is used only to
join the toxic input molecule onto each row.

Published baselines — GPT-5.2, zero-shot, mean ± std over three runs

Tables D and E. Zero-shot is upstream's baseline reporting mode; its 4-shot
columns are a labelled variant that retrieves demonstrations from the train
split.

Config Acc. (%)
task1_single 41.09 ± 0.28
task2_single 7.92 ± 0.15
task3_safe_gen_single 4.00 ± 0.11
task3_smiles_gen_single 3.50 ± 0.30
task1_multi 3.85 ± 0.10
task2_multi 0.23 ± 0.08
task3_smiles_gen_multi 0.21
task3_safe_gen_multi 0.15

Only four models appear under SMILES generation; the full 13-model roster appears
only under SAFE generation.

Task and scoring

Reward is exact match in every mode. What "exact" means differs:

  • smiles — canonical SMILES equality via RDKit.
  • safe — the prediction is decoded to SMILES with the datamol SAFE decoder,
    then compared canonically. A failed reconstruction counts invalid, matching
    upstream's Appendix D, rather than being masked.
  • fragments_task1, fragments_task2 — string multiset over dot-separated
    SAFE fragments. Order does not matter, multiplicity does. Individual SAFE
    fragments carry unmatched attachment digits (Cc1cccc6c1, C46) and genuinely
    do not parse as molecules — verified, RDKit returns None for every one —
    so canonicalisation is impossible there and comparison is verbatim.

The two fragment modes share that reward and differ only in auxiliary metrics,
because Appendix D defines different ones per task. Splitting them means the
scoring mode alone determines what is produced.

Mode Auxiliary metrics
smiles, safe validity, tanimoto_rdk/maccs/morgan, levenshtein
fragments_task1 fragment_f1, n_fragments_predicted
fragments_task2 fragment_f1, n_fragments_predicted, levenshtein

Two definitions follow the paper rather than the obvious reading. fragment_f1
is over fragment sets, as Appendix D.1 writes it, so a repeated fragment
neither helps nor hurts. The Task 2 levenshtein is not a whole-string edit
distance; Appendix D.2 says so outright and takes each predicted fragment's
minimum distance to any gold fragment, averaged. Appendix D.1 defines no distance
for Task 1, so none is emitted there.

Metrics a mode does not produce are None rather than 0.0, so an absent metric
is never averaged in as a zero. Only mean/reward and token counts are promoted
to key_metrics; the similarity metrics stay in agent_metrics for diagnosis,
for the reason under Harness validation.

The user message is upstream's, verbatim. The shipped question field is a
complete zero-shot prompt that already states the JSON output contract, so
prepare applies no template.

The system prompt is upstream's too, and is sent. The paper publishes one
per task family (Tables H, I, J, K); prompts.py carries them verbatim and the
preparer prepends the one matching the config. They restate the JSON contract
the question already carries, but add role framing and a HARD CONSTRAINTS
block ("Output ONLY the JSON object. Do not include explanations, markdown, or
extra text."). An earlier version sent none; --no-system-prompt reproduces
that, for measurement rather than for reporting.

Reproducing

# Setup — this server needs its own venv; rdkit and safe-mol are not in Gym's base
cd resources_servers/moldetox
uv venv --python 3.13.14
uv pip install -r requirements.txt
cd ../..
source resources_servers/moldetox/.venv/bin/activate

# Prepare a full split (test only; any of the eight configs)
python resources_servers/moldetox/scripts/prepare_moldetox.py \
    --config task3_smiles_gen_single \
    --output resources_servers/moldetox/data/val.jsonl

# Start servers (leave running)
gym env start \
    --resources-server moldetox \
    --model-type openai_model \
    --model "<model id>" \
    --model-url "<openai-compatible base url>" \
    --model-api-key "$API_KEY"

# Collect rollouts
gym eval run --no-serve \
    --agent moldetox_simple_agent \
    --input resources_servers/moldetox/data/val.jsonl \
    --output resources_servers/moldetox/data/val_rollouts.jsonl

All commands run from the repository root with that environment active. Note
gym eval run accepts --input only together with --no-serve, and
--split example is rejected end-to-end because example files are committed
smoke samples.

Tests: ng_test +entrypoint=resources_servers/moldetox (78 tests).

Harness validation

Model-free, and stronger than any model comparison:

  • Gold-as-prediction: feeding each gold answer back through verify() scores
    reward=1.0 on 7,904 / 7,904 rows across all eight configs, every row
    status scored, zero exceptions.
  • Negative controls: echoing the toxic input unchanged scores 0 / 943 on
    task3_smiles_gen_single; an undecodable SAFE string scores validity=0; an
    invalid SMILES is scored rather than silently dropped; fragment reordering and
    SAFE attachment-digit relabelling both still score 1.0, which is correct for a
    representation whose digits are arbitrary labels.

Echoing the toxic input is worth dwelling on: it scores 0.0 accuracy at mean
Morgan Tanimoto 0.711
, because cliff pairs are similar by construction. A
do-nothing baseline looks strong on every similarity metric, so accuracy is the
only headline-safe number here. get_key_metrics enforces that rather than
leaving it to the reader: only mean/reward and token counts are promoted.

On comparing against the published numbers

Unlike most benchmarks in this repo, a run here is directly comparable in
protocol. Zero-shot is upstream's baseline mode, the prompts are upstream's
verbatim, the model (GPT-5.2) is on its roster, and Section 3.2 gives the
sampler: temperature 0.7, three runs per model. That makes the residual gaps
meaningful rather than expected, and they are real.

openai/openai/gpt-5.2 via inference-api.nvidia.com/v1, zero-shot,
temperature 0.7, three runs, on the four single-step configs, with
upstream's published system prompts sent. 11,565 completions, 0 API errors.
Temperature was confirmed honoured rather than silently ignored before the runs:
eight completions of one prompt give 2 distinct outputs at temperature 0.0, 5 at
0.7, and 6 at 2.0.

Config Mode Ours (3 runs) Upstream (3 runs) Diff Welch t p
task1_single fragments 39.05 ± 0.50 41.09 ± 0.28 −2.04 −6.16 0.008
task2_single fragments 8.34 ± 0.27 7.92 ± 0.15 +0.42 +2.39 0.093
task3_smiles_gen_single smiles 4.38 ± 0.31 3.50 ± 0.30 +0.88 +3.57 0.023
task3_safe_gen_single safe 3.39 ± 0.46 4.00 ± 0.11 −0.61 −2.21 0.145

Two of four now differ, down from three. Two configs moved into agreement and
one moved out of it by overshooting.

Welch's t-test is the instrument because both sides estimate accuracy on the
same fixed task set, so task sampling is not a source of disagreement; what
varies is decoding, across runs. An earlier pass here used a Wilson binomial
interval and appeared to agree on all eight configs. That interval answers a
different question and is much wider, which is why it agreed. This table
supersedes it.

The two protocol corrections, measured

Two protocol errors were found and fixed, each by re-running rather than by
argument. Neither closed the gap on its own, and together they changed which
configs disagree rather than removing disagreement.

Temperature. The first runs set none, which the API resolved to 1.0;
Section 3.2 specifies 0.7. Matching it moved every config by under 0.4 points.

The system prompt. The paper publishes one per task family, as Tables H, I,
J and K, and the first runs sent none. Sending them raised three of four configs
by 0.4 to 1.3 points.

Config No system prompt With system prompt Upstream Verdict before Verdict after
task1_single 39.21 ± 0.50 39.05 ± 0.50 41.09 ± 0.28 differs differs
task2_single 7.00 ± 0.21 8.34 ± 0.27 7.92 ± 0.15 differs agrees
task3_smiles_gen_single 3.89 ± 0.32 4.38 ± 0.31 3.50 ± 0.30 agrees differs, above
task3_safe_gen_single 2.90 ± 0.06 3.39 ± 0.46 4.00 ± 0.11 differs agrees

The effect is real and in the predicted direction on three configs, and the
mechanism is visible in the outputs: with the HARD CONSTRAINTS block the model
returns bare JSON instead of fenced or narrated answers, so less depends on our
extractor. But it is not the whole explanation. task1_single is untouched by it
and remains two points low, and task3_smiles_gen_single moved from agreement to
significantly above upstream, which no single systematic deficit explains.

Sending the published system prompt is now the shipped default regardless of its
effect on the numbers, because it is what upstream specifies.

The four multi configs were run once each at unset temperature and are reported
for completeness only. They resolve 0 to 2 correct answers out of about 1,000, so
they discriminate essentially nothing:

Config Ours (1 run) Correct Upstream
task1_multi 4.53% 43 3.85%
task3_smiles_gen_multi 0.19% 2 0.21%
task2_multi 0.10% 1 0.23%
task3_safe_gen_multi 0.00% 0 0.15%

Auxiliary Task 3 metrics track closely, and were computed from the paper's prose
definitions with no upstream code to fit against, which is what makes the
agreement informative (ours / upstream, from the unset-temperature round):

Config Validity Morgan MACCS RDK Levenshtein
task3_smiles_gen_single 0.913 / 0.930 0.565 / 0.557 0.758 / 0.753 0.678 / 0.702 7.39 / 7.29
task3_safe_gen_single 0.926 / 0.936 0.570 / 0.583 0.7625 / 0.7625 0.682 / 0.720 7.04 / 6.70

Candidate causes for the residual gap

Temperature and the system prompt are now controlled, and two configs still
disagree. What is left:

  1. task1_single is unmoved by either correction and sits two points low
    across six runs. It is the largest and most reliable disagreement, and the
    system prompt changed it by 0.16 points, which is inside run-to-run noise.
    Whatever drives it is not prompting.
  2. task3_smiles_gen_single now overshoots. A harness that were simply
    lenient would overshoot everywhere; it does not. A plausible reading is that
    our extractor recovers answers upstream's would have discarded, which would
    raise us on the config where free-form SMILES is easiest to emit.
  3. "GPT-5.2" may not be the same deployment. Ours routes through NVIDIA's
    gateway, and top_p, the token budget and the endpoint style are unstated.
  4. Fragment-mode verbatim matching is plausibly too strict for Task 2 — see
    Known limitations. Note this predicts we score low on Task 2, and after the
    system-prompt fix we no longer do.

The most informative next measurement is a second model from upstream's roster;
GPT-4o and Llama-3.1-8B-Instruct are both reachable. A constant offset across
models points at the harness, a varying one at the deployment. Causes 1 and 2
point in opposite directions, which a single systematic harness deficit does not
explain, so the deployment is the more likely common factor.

Deliberate divergences from upstream

  • BLEU-1 is not computed. Upstream reports bare clipped unigram precision,
    which is degenerate on SMILES: the invalid string C1CC scores a perfect 1.0
    against a 35-character gold, since every character occurs in it. Adding a
    brevity penalty fixes that but moves the figure ~0.05 off upstream's, so the
    metric is dropped rather than reported in a form that is either misleading or
    incomparable.
  • levenshtein is None when the prediction is not a usable molecule, so
    those rows are excluded from the mean rather than charged the full gold length.
    Charging them measured 10.07 against upstream's 6.70 on task3_safe_gen_single,
    where ~7% of predictions do not decode and therefore have no string to compare
    at all. Excluding them gives 7.04.
  • PRS is not implemented. Appendix D.3 names the six properties (MW, logP,
    HBA, HBD, PSA, RotB) and states the reference molecule is the toxic input, but
    leaves the per-property desirability functions and weights unstated as
    "QED-inspired", with no implementation to check against. Those curves determine
    the value entirely. toxic_smiles is carried in verifier_metadata so PRS can
    be added later without re-preparing data.
  • datasets is not a direct dependency. The eight configs are plain
    .jsonl files at a pinned revision, and hf_hub_download plus json.loads
    reads them directly. Both paths were compared over all eight configs of the
    pinned revision and produce identical rows. The dataset card is not honoured by
    the builder in any case: load_dataset reports Some datasets params were ignored: ['type'] and picks the JSON builder for the CSV config, which then
    fails. This does not shrink the install. An earlier version of this
    description claimed it dropped PyArrow and Pandas; that was wrong. nemo-gym
    declares datasets in its own base dependencies, so those packages arrive
    regardless. What goes away is a duplicate direct declaration and a builder that
    mis-selects here.

Known limitations

  • Task 2 fragment scoring is plausibly too strict, and the fix is available.
    Task 1 asks the model to select fragments from the decomposition printed in
    its own prompt — verified: the gold appears verbatim on 1026/1026 and 950/950
    rows — so verbatim comparison is correct there. Task 2 asks it to invent a
    replacement, so its writing (ring-closure digits, atom order) is model-chosen
    and a chemically identical answer can score zero. Splicing the prediction into
    common_safe_fragments and decoding reconstructs the corresponding Task 3 gold
    on 943/943 and 1033/1033 rows, so a canonical comparison is available.
    Not done here because it changes the estimand away from upstream's, which
    defines Task 2 accuracy over the raw fragment multiset. task2_single remains
    significantly below upstream at matched protocol (t = −6.14), consistent with
    this being a contributing cause. Tracked, not silently ignored.
  • The four multi configs are near the floor (0–2 correct out of ~1,000).
    They are implemented and validated but carry almost no discriminative signal.

Data and licensing

  • Code: Apache-2.0. No upstream code was ported — there is none to port — so
    metrics.py and the scorer are original work implementing the paper's prose
    definitions.
  • Data: CC-BY-4.0, ungated, derived upstream from Therapeutics Data Commons,
    FDA, and SIDER. prepare_moldetox.py downloads at runtime at a pinned revision;
    only the 5-row data/example.jsonl smoke sample is committed, which CC-BY-4.0
    permits with attribution.
  • Dependencies: rdkit (BSD-3) and safe-mol (Apache-2.0). Neither is a
    discretionary choice — RDKit is the cheminformatics toolkit upstream's metrics
    are defined against, and safe-mol is the SAFE decoder the paper cites by URL
    as the one it uses. Both pinned (rdkit==2025.9.6, safe-mol==0.2.1) because
    installing safe-mol downgrades rdkit; the full validation and test suite were
    re-run under the downgrade and are clean.
  • Only the test split is used. The ~202k-row train split is never read, and
    --split is constrained to test so that stays true rather than resting on
    the caller.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally (78 tests).
  • Pre-commit checks pass locally — on the first pass update-readme-table
    rewrote README.md to add the environment row, as CONTRIBUTING describes;
    the second pass is clean.
  • All commits have DCO sign-off (git commit -s).

New-environment gates (CONTRIBUTING.md)

  • At least one test — tests/test_app.py, 78 tests
  • Copyright header on every new file
  • data/example.jsonl exists with exactly 5 rows
  • data/example_metrics.json reports "Number of examples": 5
  • data/example_rollouts.jsonl exists with exactly 5 rollouts
  • No merge-conflict artifacts in data/
  • Config sets domain (knowledge)
  • Train/validation datasets carry a license field
  • verified: false

Verified directly: gym env test --resources-server moldetox +should_validate_data=true exits 0.

MolDeTox is a toxicity-aware molecular editing benchmark built from
toxicity cliffs: pairs of structurally near-identical molecules with
opposite measured toxicity. All eight QA configs are implemented against
the pinned dataset revision 059e1926. Only the test split is reachable;
`--split` is constrained rather than documented, because a free-form
string quietly contradicted the README's test-only scope.

Both prompt turns come from upstream. The dataset ships each user message
in `question`, and the paper publishes a system prompt per task family as
Appendix Tables H, I, J and K, which prompts.py carries verbatim. Sending
no system message is a measurable divergence, not an upstream gap, so
`--no-system-prompt` exists to reproduce it rather than to support it.

Reward is exact match in every mode, but "exact" differs by task. Task 3
answers are whole molecules compared as canonical SMILES, or decoded from
SAFE first with a failed reconstruction counted invalid. Tasks 1 and 2
answer with SAFE fragment sets, which carry unmatched attachment digits
and genuinely do not parse as molecules, so they are compared as string
multisets.

The two fragment modes are separate because Appendix D defines different
auxiliary metrics per task: D.1 gives Task 1 exact match and a set-based
F1 only, while D.2 adds a fragment-level edit distance that is explicitly
not a whole-string distance. Splitting them keeps the scoring mode the
single thing that determines which metrics are produced.

Scoring is deterministic and needs no judge model. Validation is
model-free: every one of the 7,904 test golds scores 1.0 when fed back
through verify(), and negative controls cover echoing the toxic input,
undecodable SAFE, invalid SMILES, fragment reordering and attachment-digit
relabelling.

Only mean/reward and token counts are promoted to key_metrics. The
similarity metrics must not be read as performance here: echoing the toxic
input unchanged scores zero accuracy at mean Morgan Tanimoto 0.711,
because cliff pairs are similar by construction.

Three upstream metrics are deliberately not reported. BLEU-1 is bare
clipped unigram precision, which is degenerate on SMILES. Levenshtein is
None rather than the full gold length when a prediction is unusable. PRS
needs desirability curves and weights the paper never states.

Data preparation uses huggingface-hub directly rather than datasets. The
eight configs are plain JSONL files at a pinned revision, both paths were
compared over all eight and produce identical rows, and the dataset card
is not honoured by the builder in any case.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Sep 16, 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.

The CI secrets scan reads the pinned Hugging Face commit SHA as a
HexHighEntropyString and fails the job. It is a public revision identifier
and the whole point of pinning is that it is readable.

Fixed with an inline pragma, which is this repository's existing
convention, rather than by regenerating a shared baseline. There is no
.secrets.baseline here to regenerate, and touching one would put this
branch in the path of every other open PR.

Reproduced the finding locally with detect-secrets 1.5.0 before and after:
one finding at prepare_moldetox.py:45, then zero across the whole server.
The same SHA in the server README is not flagged.

Added as a new commit rather than an amend: the branch is already
published, and rewriting it would need a force-push, which the contributing
guide disallows on upstream branches and which orphans inline review
comments.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
@yaoyu-33 yaoyu-33 added area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers complexity:medium Single-domain change with interacting parts or a moderate review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Sep 16, 2026
@github-actions github-actions Bot added the sla:triage-overdue Review assignment is over the one-business-day SLA label Sep 17, 2026
The implementation notes planned a benchmarks/moldetox/ entry and the
server shipped without one, so `gym eval prepare --benchmark moldetox` did
not exist and preparation was a documented script invocation instead. This
adds the entry. Scoring and wiring stay in the resources server; this
supplies data and a chain to its config.

Registers task3_smiles_gen_single only. MolDeTox publishes a figure for
each of its eight QA configs, so naming one canonical is a choice rather
than a lookup: this is the config upstream headlines, and the one whose
measured accuracy agrees with the published figure. The other seven stay
reachable through the server's script, and both READMEs say so.

prepare.py reuses the server's loader and row builder rather than
reimplementing them, so the two paths cannot drift. Verified: the
benchmark output is byte-identical to the server script's output for the
same config, 943 rows, system and user turns in that order, zero unjoined
toxicity-cliff rows.

It drops agent_ref, which the server's script still emits as 21 others do.
Routing comes from the config declaration and collate strips the field with
a deprecation warning, so new code should not add it.

`gym eval prepare --benchmark moldetox` was run end to end against the
pinned revision, not just written.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
@bxyu-nvidia

Copy link
Copy Markdown
Contributor

/ok to test 27b7938

@github-actions github-actions Bot removed the sla:triage-overdue Review assignment is over the one-business-day SLA label Sep 21, 2026
@bxyu-nvidia
bxyu-nvidia merged commit d4d9bb2 into main Sep 21, 2026
51 checks passed
@bxyu-nvidia
bxyu-nvidia deleted the rshahbazyan/add-moldetox-benchmark branch September 21, 2026 23:00

This branch was previously deployed

1 inactive deployment
public — 27b79387 Deployed Sep 21, 2026 by copy-pr-bot[bot] via release / finalize / notify #3393
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 complexity:medium Single-domain change with interacting parts or a moderate review surface 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