Move to current prime-rl, verifiers and renderers; DeepSeek V4.1 support
Bump prime-rl to trinity-dsv41: upstream main, PR #4057 (DeepSeek V4.1 Flash) with the engram port onto the shared n-gram module, and renderers tracking its trinity-dsv41 branch (v0.2.0 + the Hermes parser). Port the envs to the current verifiers v1 API, rl.toml to the new config schema (IPO loss kept as the new default), and bootstrap/launch/prepare scripts to the new layout. Decensor now runs DecensorEnv: the simulated user writes reviewed follow-ups up to each row's target_turns and every assistant turn is judged. Earlier runs trained on the first turn only. tests/test_multiturn_env.py drives the full loop against a mock endpoint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
[submodule "prime-rl"]
|
[submodule "prime-rl"]
|
||||||
path = prime-rl
|
path = prime-rl
|
||||||
url = ../prime-rl.git
|
url = ../prime-rl.git
|
||||||
branch = trinity
|
branch = trinity-dsv41
|
||||||
|
|||||||
@@ -10,15 +10,16 @@ run it.
|
|||||||
| `configs/rl.toml` | The production recipe |
|
| `configs/rl.toml` | The production recipe |
|
||||||
| `scripts/` | Training-host setup, launch, and preflight checks |
|
| `scripts/` | Training-host setup, launch, and preflight checks |
|
||||||
| `serving/judge/` | Gemma judge replicas behind nginx |
|
| `serving/judge/` | Gemma judge replicas behind nginx |
|
||||||
| `prime-rl/` | Submodule: [`dphn/prime-rl`](https://git.pid1.sh/dphn/prime-rl), branch `trinity` |
|
| `prime-rl/` | Submodule: [`dphn/prime-rl`](https://git.pid1.sh/dphn/prime-rl), branch `trinity-dsv41` |
|
||||||
|
|
||||||
## Pinned stack
|
## Pinned stack
|
||||||
|
|
||||||
| Component | Version |
|
| Component | Version |
|
||||||
|---|---|
|
|---|---|
|
||||||
| PRIME-RL | upstream `31ff561` + `dphn/prime-rl@trinity` (LoRA warm start, longer adapter-reload timeouts) |
|
| PRIME-RL | upstream main `eed0e44c` + PR #4057 (DeepSeek-V4.1) + `dphn/prime-rl@trinity-dsv41` (LoRA warm start, longer adapter-reload timeouts) |
|
||||||
| renderers | upstream `bdb96b0` + `dphn/renderers@trinity` (text-level Hermes tool parser) |
|
| renderers | upstream main + PR #192 (DeepSeek-V4.1 renderer) + `dphn/renderers@trinity-dsv41` (text-level Hermes tool parser) |
|
||||||
| verifiers | `b13ba60` (unmodified) |
|
| verifiers | `72d08a0b6` (v0.4.2.dev, unmodified) |
|
||||||
|
| vLLM (training) | 0.32.0 (PRIME-RL lock) |
|
||||||
| Policy | `arcee-ai/Trinity-Mini@cdb81e8130815fec299cccc8f8700004b8366e1e` |
|
| Policy | `arcee-ai/Trinity-Mini@cdb81e8130815fec299cccc8f8700004b8366e1e` |
|
||||||
| Judge / simulated user | `google/gemma-4-26B-A4B-it@4d7ae4984b7db7de8f8457170b3f1a419ee76d52`, vLLM 0.29.0 |
|
| Judge / simulated user | `google/gemma-4-26B-A4B-it@4d7ae4984b7db7de8f8457170b3f1a419ee76d52`, vLLM 0.29.0 |
|
||||||
|
|
||||||
@@ -26,7 +27,7 @@ run it.
|
|||||||
|
|
||||||
One 8×H200 node: 2 trainer GPUs, 6 inference GPUs as TP2×DP3 (EP6), compiled with CUDA
|
One 8×H200 node: 2 trainer GPUs, 6 inference GPUs as TP2×DP3 (EP6), compiled with CUDA
|
||||||
graphs and prefix caching. q/k/v/o LoRA (rank 128, alpha 256), Muon at `8e-6`, 2,048
|
graphs and prefix caching. q/k/v/o LoRA (rank 128, alpha 256), Muon at `8e-6`, 2,048
|
||||||
rollouts per step in groups of 16, 512 rollouts in flight, 500 steps. Decensor supplies half
|
rollouts per step in groups of 16, a fixed 512 episodes in flight, 500 steps. Decensor supplies half
|
||||||
of each batch; the four Nemotron envs share the other half. Activation offloading is off;
|
of each batch; the four Nemotron envs share the other half. Activation offloading is off;
|
||||||
selective activation checkpointing and optimizer CPU offload are on.
|
selective activation checkpointing and optimizer CPU offload are on.
|
||||||
|
|
||||||
@@ -57,7 +58,9 @@ tmux new -s trinity 'JUDGE_BASE_URL=http://JUDGE_HOST:3001/v1 scripts/launch.sh'
|
|||||||
|
|
||||||
`launch.sh` renders the judge URL into `outputs/rl.toml`, checks HF/W&B credentials and the
|
`launch.sh` renders the judge URL into `outputs/rl.toml`, checks HF/W&B credentials and the
|
||||||
pinned model revision, checks that the judge rejects unauthenticated requests and answers
|
pinned model revision, checks that the judge rejects unauthenticated requests and answers
|
||||||
authenticated ones, then starts `rl`. Extra arguments are passed to `rl`.
|
authenticated ones, then starts `rl`, which launches inference, the trainer, the orchestrator
|
||||||
|
and one `env-worker-pool` per source. Extra arguments are passed to `rl`. The run writes to
|
||||||
|
`outputs/trinity-mini` (`output_dir` / `run.name`) and resumes from its latest checkpoint.
|
||||||
|
|
||||||
**Tests** (in any venv with `prime-rl/deps/{verifiers,renderers}`, the envs, and
|
**Tests** (in any venv with `prime-rl/deps/{verifiers,renderers}`, the envs, and
|
||||||
`transformers==5.6.2` installed):
|
`transformers==5.6.2` installed):
|
||||||
@@ -87,11 +90,13 @@ Don't run PRIME-RL's own test suite on a live training host: its session cleanup
|
|||||||
background weight-update task; if it dies, the run needs a restart.
|
background weight-update task; if it dies, the run needs a restart.
|
||||||
- **Launcher-owned inference is all-or-nothing.** If inference dies, the launcher kills the whole
|
- **Launcher-owned inference is all-or-nothing.** If inference dies, the launcher kills the whole
|
||||||
process tree. To restart training without restarting inference, run `uv run inference`
|
process tree. To restart training without restarting inference, run `uv run inference`
|
||||||
separately and point training at it with `deployment.num_infer_gpus = 0`, `inference = "None"`
|
separately (from the recipe's `[inference]` block, so the server keeps `vllm.enable_lora` and
|
||||||
and `orchestrator.model.client.base_url`.
|
`vllm.max_lora_rank = 128`, which `rl` only fills in for inference it owns) and point training
|
||||||
- **Warm start only restores adapter weights.** `model.lora.init_path` (set on both trainer
|
at it with `deployment.num_infer_gpus = 0`, `inference = "None"` and
|
||||||
and orchestrator) copies an attention-only adapter; optimizer, scheduler and step counters
|
`orchestrator.model.client.base_url`.
|
||||||
start fresh, so use a new output directory.
|
- **Warm start only restores adapter weights.** `trainer.model.lora.init_path` copies an
|
||||||
|
attention-only adapter; optimizer, scheduler and step counters start fresh, so use a new
|
||||||
|
`run.name`.
|
||||||
- **Rewards add, they don't multiply.** Verifiers sums `@vf.reward` values, so decensor's
|
- **Rewards add, they don't multiply.** Verifiers sums `@vf.reward` values, so decensor's
|
||||||
multiplicative reward is computed inside a single reward. A gate must return `0.0`; raising
|
multiplicative reward is computed inside a single reward. A gate must return `0.0`; raising
|
||||||
fails the rollout and retries it instead of scoring it.
|
fails the rollout and retries it instead of scoring it.
|
||||||
|
|||||||
+137
-100
@@ -1,21 +1,31 @@
|
|||||||
# Trinity-Mini RL (GRPO) on modern prime-rl (verifiers v1, vLLM 0.24).
|
# Trinity-Mini RL (GRPO) on modern prime-rl (verifiers v1, vLLM 0.32).
|
||||||
# 2048 rollouts/step; decensor at 50%.
|
# 2048 rollouts/step; decensor at 50%.
|
||||||
# `ratio` is a relative sampling weight between envs: env share = ratio_i / sum(ratios) * batch_size.
|
# `ratio` is a relative sampling weight between sources: share = ratio_i / sum(ratios) * batch_size.
|
||||||
# decensor ratio 4.0 == sum of the four nemotron (1.0 each) -> decensor 1024, each nemotron 256.
|
# decensor ratio 4.0 == sum of the four nemotron (1.0 each) -> decensor 1024, each nemotron 256.
|
||||||
# Blending WITHIN an env is `taskset.mix` (see the per-env blocks below) — `ratio` does not
|
# Blending WITHIN an env is `taskset.mix` (see the per-env blocks below) — `ratio` does not
|
||||||
# reach subtasks, so without `mix` a taskset's blend is dictated by raw source file size.
|
# reach subtasks, so without `mix` a taskset's blend is dictated by raw source file size.
|
||||||
#
|
#
|
||||||
# ${JUDGE_BASE_URL} is substituted by scripts/launch.sh; do not pass this file to `rl` directly.
|
# ${JUDGE_BASE_URL} is substituted by scripts/launch.sh; do not pass this file to `rl` directly.
|
||||||
|
|
||||||
output_dir = "outputs/trinity-mini"
|
# The run writes to output_dir / run.name = outputs/trinity-mini. `run.name` must stay fixed
|
||||||
clean_output_dir = false
|
# for `[resume]` to find the previous checkpoints; it is also the W&B run name.
|
||||||
|
output_dir = "outputs"
|
||||||
|
clean = false
|
||||||
max_steps = 500
|
max_steps = 500
|
||||||
seq_len = 32768 # prompt + completion budget; matches model max_model_len
|
seq_len = 32768 # prompt + completion budget; matches inference max_model_len
|
||||||
|
|
||||||
[wandb]
|
[run]
|
||||||
|
name = "trinity-mini"
|
||||||
|
|
||||||
|
[monitors]
|
||||||
|
prime = "None" # no Prime platform run (on by default upstream; needs a Prime API key)
|
||||||
|
|
||||||
|
[monitors.wandb]
|
||||||
project = "prime-rl"
|
project = "prime-rl"
|
||||||
name = "trinity-mini"
|
name = "trinity-mini"
|
||||||
|
|
||||||
|
[monitors.file]
|
||||||
|
|
||||||
[log]
|
[log]
|
||||||
level = "info"
|
level = "info"
|
||||||
|
|
||||||
@@ -29,15 +39,22 @@ num_infer_gpus = 6
|
|||||||
|
|
||||||
[ckpt]
|
[ckpt]
|
||||||
interval = 25 # checkpoint before the ~step-38 weight-swap hang so restarts resume
|
interval = 25 # checkpoint before the ~step-38 weight-swap hang so restarts resume
|
||||||
resume_step = -1 # -1 = resume from latest ckpt (None if none yet -> fresh)
|
|
||||||
keep_last = 2
|
keep_last = 2
|
||||||
keep_interval = 100
|
keep_interval = 100
|
||||||
|
|
||||||
|
# Resume from the latest checkpoint under outputs/trinity-mini; a fresh run dir starts from
|
||||||
|
# scratch (the launcher logs "No checkpoints found ... Starting from scratch").
|
||||||
|
[resume]
|
||||||
|
|
||||||
[orchestrator]
|
[orchestrator]
|
||||||
batch_size = 2048 # rollouts per step
|
batch_size = 2048 # rollouts per step
|
||||||
group_size = 16 # GRPO group -> 128 prompts/step
|
|
||||||
oversampling_factor = 0.25 # agrees with max_inflight_rollouts / batch_size
|
# Fixed in-flight cap (min = max = initial): judging/multi-turn work also occupies episode
|
||||||
max_inflight_rollouts = 512 # judging/multi-turn work also occupies rollout slots
|
# slots. The adaptive controller would otherwise ramp past what the judge host absorbs.
|
||||||
|
[orchestrator.concurrency]
|
||||||
|
initial_inflight = 512
|
||||||
|
min_inflight = 512
|
||||||
|
max_inflight = 512
|
||||||
|
|
||||||
# Trinity isn't in renderers.base.MODEL_RENDERER_MAP, so DefaultRenderer applies the model
|
# Trinity isn't in renderers.base.MODEL_RENDERER_MAP, so DefaultRenderer applies the model
|
||||||
# chat_template. tool_parser "hermes" matches the model card's `--tool-call-parser hermes`.
|
# chat_template. tool_parser "hermes" matches the model card's `--tool-call-parser hermes`.
|
||||||
@@ -50,23 +67,38 @@ name = "default"
|
|||||||
tool_parser = "hermes"
|
tool_parser = "hermes"
|
||||||
reasoning_parser = "think"
|
reasoning_parser = "think"
|
||||||
|
|
||||||
|
[orchestrator.train]
|
||||||
|
group_size = 16 # GRPO group -> 128 prompts/step
|
||||||
|
|
||||||
[orchestrator.train.sampling]
|
[orchestrator.train.sampling]
|
||||||
temperature = 1.0
|
temperature = 1.0
|
||||||
max_completion_tokens = 16384 # Trinity is reasoning-verbose; keep high
|
max_completion_tokens = 16384 # Trinity is reasoning-verbose; keep high
|
||||||
|
|
||||||
# vLLM-served LoRA adapter name
|
# Shuffle each finite taskset once before the sampler cycles it in that order. The old
|
||||||
[orchestrator.model.lora]
|
# orchestrator shuffled every taskset (and reshuffled on each pass); the new default
|
||||||
name = "trinity-mini"
|
# cycles in load() order.
|
||||||
|
[orchestrator.train.select]
|
||||||
|
shuffle = true
|
||||||
|
|
||||||
# --- decensor env — 1024 rollouts (50%). Agentic-review archive implementation. ---
|
# --- decensor env — 1024 rollouts (50%). Agentic-review archive implementation. ---
|
||||||
# The archive uses the difficulty-filtered dataset, per-turn structured review, validated
|
# The archive uses the difficulty-filtered dataset, per-turn structured review, validated
|
||||||
# simulated-user follow-ups, and fail-closed service errors. Keep the per-turn cap at 8k so
|
# simulated-user follow-ups, and fail-closed service errors. Keep the per-turn cap at 8k so
|
||||||
# up to six turns stay within Trinity's 32k context budget.
|
# up to six turns stay within Trinity's 32k context budget.
|
||||||
[[orchestrator.train.env]]
|
#
|
||||||
|
# The package exports DecensorEnv, so each row runs as a conversation: the simulated user
|
||||||
|
# writes validated follow-ups until the row's target_turns (1-6, decaying by
|
||||||
|
# turn_decay_ratio) and every assistant turn is reviewed. The policy seat is
|
||||||
|
# `env.assistant`. (Runs before 2026-11 under verifiers b13ba60 never loaded DecensorEnv
|
||||||
|
# and trained on the first turn only.)
|
||||||
|
#
|
||||||
|
# Every source zeroes groups whose advantages are all 0, as the old default
|
||||||
|
# zero_advantage post-batch filter did.
|
||||||
|
[[orchestrator.train.source]]
|
||||||
name = "decensor"
|
name = "decensor"
|
||||||
ratio = 4.0
|
ratio = 4.0
|
||||||
|
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||||
# More workers expose parallel reviews; each worker has two review slots.
|
# More workers expose parallel reviews; each worker has two review slots.
|
||||||
pool = { type = "elastic", multiplex = 8, max_workers = 96 }
|
serve.pool = { type = "elastic", multiplex = 8, max_workers = 96 }
|
||||||
env.taskset.id = "decensor-v1"
|
env.taskset.id = "decensor-v1"
|
||||||
env.taskset.num_examples = 2000
|
env.taskset.num_examples = 2000
|
||||||
env.taskset.dataset_seed = 42
|
env.taskset.dataset_seed = 42
|
||||||
@@ -86,16 +118,18 @@ env.taskset.task.enable_reasoning_trace = true
|
|||||||
env.taskset.task.enable_reasoning_trace_is_clear = true
|
env.taskset.task.enable_reasoning_trace_is_clear = true
|
||||||
env.taskset.task.enable_meta_commentary = true
|
env.taskset.task.enable_meta_commentary = true
|
||||||
env.taskset.task.reasoning_enabled = true
|
env.taskset.task.reasoning_enabled = true
|
||||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
env.assistant.harness = { id = "null" }
|
||||||
env.agent.max_output_tokens = 8192
|
env.assistant.runtime = { type = "subprocess" }
|
||||||
env.agent.timeout.rollout = 1800
|
env.assistant.max_turns = 6 # = taskset.max_turns; the conversation cap
|
||||||
|
env.assistant.max_output_tokens = 8192
|
||||||
|
env.assistant.timeout.rollout = 1800
|
||||||
|
|
||||||
# per-turn generation cap 8k for decensor only (nemotron keeps the global 16k)
|
# per-turn generation cap 8k for decensor only (nemotron keeps the global 16k)
|
||||||
[orchestrator.train.env.sampling]
|
[orchestrator.train.source.sampling]
|
||||||
max_completion_tokens = 8192
|
max_completion_tokens = 8192
|
||||||
|
|
||||||
# decensor judge + simulated user, both on the shared gemma endpoint
|
# decensor judge + simulated user, both on the shared gemma endpoint
|
||||||
[orchestrator.train.env.env.taskset.task.judge]
|
[orchestrator.train.source.env.taskset.task.judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
@@ -103,11 +137,11 @@ min_p = 0.05
|
|||||||
disable_thinking = true
|
disable_thinking = true
|
||||||
max_concurrent_requests = 192
|
max_concurrent_requests = 192
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.judge.sampling]
|
[orchestrator.train.source.env.taskset.task.judge.sampling]
|
||||||
temperature = 0.0
|
temperature = 0.0
|
||||||
max_tokens = 1024
|
max_tokens = 1024
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.user]
|
[orchestrator.train.source.env.taskset.task.user]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
@@ -117,24 +151,26 @@ max_tokens = 256
|
|||||||
max_concurrent_requests = 192
|
max_concurrent_requests = 192
|
||||||
|
|
||||||
# --- nemotron-knowledge — 256 rollouts. Shared gemma judge, full guard ON. ---
|
# --- nemotron-knowledge — 256 rollouts. Shared gemma judge, full guard ON. ---
|
||||||
[[orchestrator.train.env]]
|
[[orchestrator.train.source]]
|
||||||
name = "nemotron-knowledge"
|
name = "nemotron-knowledge"
|
||||||
ratio = 1.0
|
ratio = 1.0
|
||||||
|
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||||
env.taskset.id = "nemotron-knowledge-v1"
|
env.taskset.id = "nemotron-knowledge-v1"
|
||||||
env.taskset.dataset = "all"
|
env.taskset.dataset = "all"
|
||||||
env.taskset.mix_total = 20000
|
env.taskset.mix_total = 20000
|
||||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
env.agent.harness = { id = "null" }
|
||||||
|
env.agent.runtime = { type = "subprocess" }
|
||||||
env.agent.timeout.rollout = 900
|
env.agent.timeout.rollout = 900
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.guard]
|
[orchestrator.train.source.env.taskset.task.guard]
|
||||||
reasoning_required = true
|
reasoning_required = true
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.guard.judge]
|
[orchestrator.train.source.env.taskset.task.guard.judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.equivalence_judge]
|
[orchestrator.train.source.env.taskset.task.equivalence_judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
@@ -144,71 +180,75 @@ api_key_var = "VLLM_API_KEY"
|
|||||||
# share of THIS many prompts, and a subtask with fewer rows than its quota is cycled. 20k is
|
# share of THIS many prompts, and a subtask with fewer rows than its quota is cycled. 20k is
|
||||||
# ~2.5x what 500 steps consume, so keep it modest or small sources repeat heavily (qa has
|
# ~2.5x what 500 steps consume, so keep it modest or small sources repeat heavily (qa has
|
||||||
# only 3.1k unique prompts, so 0.1 already means each is seen ~2x per pass).
|
# only 3.1k unique prompts, so 0.1 already means each is seen ~2x per pass).
|
||||||
[orchestrator.train.env.env.taskset.mix.mcqa]
|
[orchestrator.train.source.env.taskset.mix.mcqa]
|
||||||
weight = 0.9
|
weight = 0.9
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.qa_abstention]
|
[orchestrator.train.source.env.taskset.mix.qa_abstention]
|
||||||
weight = 0.1
|
weight = 0.1
|
||||||
|
|
||||||
# --- nemotron-reasoning — 256 rollouts. math graded by math-verify; science by judge. ---
|
# --- nemotron-reasoning — 256 rollouts. math graded by math-verify; science by judge. ---
|
||||||
[[orchestrator.train.env]]
|
[[orchestrator.train.source]]
|
||||||
name = "nemotron-reasoning"
|
name = "nemotron-reasoning"
|
||||||
ratio = 1.0
|
ratio = 1.0
|
||||||
|
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||||
env.taskset.id = "nemotron-reasoning-v1"
|
env.taskset.id = "nemotron-reasoning-v1"
|
||||||
env.taskset.dataset = "all"
|
env.taskset.dataset = "all"
|
||||||
env.taskset.mix_total = 20000
|
env.taskset.mix_total = 20000
|
||||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
env.agent.harness = { id = "null" }
|
||||||
|
env.agent.runtime = { type = "subprocess" }
|
||||||
env.agent.timeout.rollout = 900
|
env.agent.timeout.rollout = 900
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.guard]
|
[orchestrator.train.source.env.taskset.task.guard]
|
||||||
reasoning_required = true
|
reasoning_required = true
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.guard.judge]
|
[orchestrator.train.source.env.taskset.task.guard.judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.equivalence_judge]
|
[orchestrator.train.source.env.taskset.task.equivalence_judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
|
|
||||||
# Source sizes are science 150k / rg 15k / arc 10k / math 3.7k, so plain concatenation ran
|
# Source sizes are science 150k / rg 15k / arc 10k / math 3.7k, so plain concatenation ran
|
||||||
# 83% science and 2% math — and routed 83% of the env's compute through the slow judge.
|
# 83% science and 2% math — and routed 83% of the env's compute through the slow judge.
|
||||||
[orchestrator.train.env.env.taskset.mix.math]
|
[orchestrator.train.source.env.taskset.mix.math]
|
||||||
weight = 0.35
|
weight = 0.35
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.science]
|
[orchestrator.train.source.env.taskset.mix.science]
|
||||||
weight = 0.30
|
weight = 0.30
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.reasoning_gym]
|
[orchestrator.train.source.env.taskset.mix.reasoning_gym]
|
||||||
weight = 0.25
|
weight = 0.25
|
||||||
|
|
||||||
# arc_agi is exact-match on a full grid and the model is at ~0% — kept small until it shows
|
# arc_agi is exact-match on a full grid and the model is at ~0% — kept small until it shows
|
||||||
# signal. `difficulty_bucket` filtering is the next lever if it stays flat.
|
# signal. `difficulty_bucket` filtering is the next lever if it stays flat.
|
||||||
[orchestrator.train.env.env.taskset.mix.arc_agi]
|
[orchestrator.train.source.env.taskset.mix.arc_agi]
|
||||||
weight = 0.10
|
weight = 0.10
|
||||||
|
|
||||||
# --- nemotron-instruction-following — 256 rollouts. ---
|
# --- nemotron-instruction-following — 256 rollouts. ---
|
||||||
[[orchestrator.train.env]]
|
[[orchestrator.train.source]]
|
||||||
name = "nemotron-instruction-following"
|
name = "nemotron-instruction-following"
|
||||||
ratio = 1.0
|
ratio = 1.0
|
||||||
|
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||||
env.taskset.id = "nemotron-instruction-following-v1"
|
env.taskset.id = "nemotron-instruction-following-v1"
|
||||||
env.taskset.dataset = "all"
|
env.taskset.dataset = "all"
|
||||||
env.taskset.mix_total = 20000
|
env.taskset.mix_total = 20000
|
||||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
env.agent.harness = { id = "null" }
|
||||||
|
env.agent.runtime = { type = "subprocess" }
|
||||||
env.agent.timeout.rollout = 900
|
env.agent.timeout.rollout = 900
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.guard]
|
[orchestrator.train.source.env.taskset.task.guard]
|
||||||
reasoning_required = true
|
reasoning_required = true
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.guard.judge]
|
[orchestrator.train.source.env.taskset.task.guard.judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
|
|
||||||
# calendar / adversarial / ultra-judge grader (IFJudgeConfig)
|
# calendar / adversarial / ultra-judge grader (IFJudgeConfig)
|
||||||
[orchestrator.train.env.env.taskset.task.judge]
|
[orchestrator.train.source.env.taskset.task.judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
@@ -216,37 +256,37 @@ api_key_var = "VLLM_API_KEY"
|
|||||||
# Size-proportional blending starved the judge subtasks to ~0.6% each — 5 distinct rows
|
# Size-proportional blending starved the judge subtasks to ~0.6% each — 5 distinct rows
|
||||||
# across 50 steps. ifeval stays dominant since its checkers are deterministic and cheap.
|
# across 50 steps. ifeval stays dominant since its checkers are deterministic and cheap.
|
||||||
# (`identity` was removed from the env: its rubric demanded the model claim to be Nemotron.)
|
# (`identity` was removed from the env: its rubric demanded the model claim to be Nemotron.)
|
||||||
[orchestrator.train.env.env.taskset.mix.ifeval]
|
[orchestrator.train.source.env.taskset.mix.ifeval]
|
||||||
weight = 0.34
|
weight = 0.34
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.structured_v2_direct]
|
[orchestrator.train.source.env.taskset.mix.structured_v2_direct]
|
||||||
weight = 0.12
|
weight = 0.12
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.structured_v2_diversified]
|
[orchestrator.train.source.env.taskset.mix.structured_v2_diversified]
|
||||||
weight = 0.12
|
weight = 0.12
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.citation_format]
|
[orchestrator.train.source.env.taskset.mix.citation_format]
|
||||||
weight = 0.08
|
weight = 0.08
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.freeform_formatting]
|
[orchestrator.train.source.env.taskset.mix.freeform_formatting]
|
||||||
weight = 0.08
|
weight = 0.08
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.calendar]
|
[orchestrator.train.source.env.taskset.mix.calendar]
|
||||||
weight = 0.08
|
weight = 0.08
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.multichallenge]
|
[orchestrator.train.source.env.taskset.mix.multichallenge]
|
||||||
weight = 0.05
|
weight = 0.05
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.adversarial]
|
[orchestrator.train.source.env.taskset.mix.adversarial]
|
||||||
weight = 0.05
|
weight = 0.05
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.sysbench]
|
[orchestrator.train.source.env.taskset.mix.sysbench]
|
||||||
weight = 0.03
|
weight = 0.03
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.cfbench]
|
[orchestrator.train.source.env.taskset.mix.cfbench]
|
||||||
weight = 0.03
|
weight = 0.03
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.inverse_ifeval]
|
[orchestrator.train.source.env.taskset.mix.inverse_ifeval]
|
||||||
weight = 0.02
|
weight = 0.02
|
||||||
|
|
||||||
# --- nemotron-tool-calling — 256 rollouts. Native schemas, one assistant action. ---
|
# --- nemotron-tool-calling — 256 rollouts. Native schemas, one assistant action. ---
|
||||||
@@ -260,74 +300,79 @@ weight = 0.02
|
|||||||
# The bundled harness sends tools through the native API and finishes after one response.
|
# The bundled harness sends tools through the native API and finishes after one response.
|
||||||
# No tool is dispatched: pivot rows grade the next action, not an execution outcome.
|
# No tool is dispatched: pivot rows grade the next action, not an execution outcome.
|
||||||
# Do not substitute a looping null harness or a truncating max_turns stop.
|
# Do not substitute a looping null harness or a truncating max_turns stop.
|
||||||
[[orchestrator.train.env]]
|
[[orchestrator.train.source]]
|
||||||
name = "nemotron-tool-calling"
|
name = "nemotron-tool-calling"
|
||||||
ratio = 1.0
|
ratio = 1.0
|
||||||
|
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||||
env.taskset.id = "nemotron-tool-calling-v1"
|
env.taskset.id = "nemotron-tool-calling-v1"
|
||||||
env.taskset.dataset = "all"
|
env.taskset.dataset = "all"
|
||||||
env.taskset.mix_total = 20000
|
env.taskset.mix_total = 20000
|
||||||
env.taskset.exclude_message_actions = true
|
env.taskset.exclude_message_actions = true
|
||||||
env.taskset.max_prompt_chars = 60000
|
env.taskset.max_prompt_chars = 60000
|
||||||
env.agent.harness = { id = "nemotron-tool-calling-v1", runtime = { type = "subprocess" } }
|
env.agent.harness = { id = "nemotron-tool-calling-v1" }
|
||||||
|
env.agent.runtime = { type = "subprocess" }
|
||||||
env.agent.max_output_tokens = 16384
|
env.agent.max_output_tokens = 16384
|
||||||
env.agent.timeout.rollout = 900
|
env.agent.timeout.rollout = 900
|
||||||
|
|
||||||
# function_calling has the best signal of the pivot subtasks (21% positive vs 12%) but is
|
# function_calling has the best signal of the pivot subtasks (21% positive vs 12%) but is
|
||||||
# only ~9.6k rows against tool_use_pivot's ~50k, so it needs an explicit share.
|
# only ~9.6k rows against tool_use_pivot's ~50k, so it needs an explicit share.
|
||||||
[orchestrator.train.env.env.taskset.mix.tool_use_pivot]
|
[orchestrator.train.source.env.taskset.mix.tool_use_pivot]
|
||||||
weight = 0.6
|
weight = 0.6
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.mix.function_calling]
|
[orchestrator.train.source.env.taskset.mix.function_calling]
|
||||||
weight = 0.4
|
weight = 0.4
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.guard]
|
[orchestrator.train.source.env.taskset.task.guard]
|
||||||
reasoning_required = true
|
reasoning_required = true
|
||||||
allow_renderer_stripped_tool_calls = true
|
allow_renderer_stripped_tool_calls = true
|
||||||
|
|
||||||
[orchestrator.train.env.env.taskset.task.guard.judge]
|
[orchestrator.train.source.env.taskset.task.guard.judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
|
|
||||||
# --- eval — small and timed out so it can't hog the pool at step 0 ---
|
# --- eval — small and timed out so it can't hog the pool at step 0 ---
|
||||||
|
# `select.limit` takes the first 16 tasks in load() order (the old `num_examples = 16`).
|
||||||
[orchestrator.eval]
|
[orchestrator.eval]
|
||||||
interval = 50
|
interval = 50
|
||||||
|
group_size = 1
|
||||||
|
|
||||||
|
[orchestrator.eval.select]
|
||||||
|
limit = 16
|
||||||
|
|
||||||
[orchestrator.eval.sampling]
|
[orchestrator.eval.sampling]
|
||||||
temperature = 1.0
|
temperature = 1.0
|
||||||
max_completion_tokens = 16384
|
max_completion_tokens = 16384
|
||||||
|
|
||||||
[[orchestrator.eval.env]]
|
[[orchestrator.eval.source]]
|
||||||
name = "nemotron-knowledge"
|
name = "nemotron-knowledge"
|
||||||
num_examples = 16
|
|
||||||
group_size = 1
|
|
||||||
env.taskset.id = "nemotron-knowledge-v1"
|
env.taskset.id = "nemotron-knowledge-v1"
|
||||||
env.taskset.dataset = "all"
|
env.taskset.dataset = "all"
|
||||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
env.agent.harness = { id = "null" }
|
||||||
|
env.agent.runtime = { type = "subprocess" }
|
||||||
env.agent.timeout.rollout = 900
|
env.agent.timeout.rollout = 900
|
||||||
|
|
||||||
[orchestrator.eval.env.env.taskset.task.guard.judge]
|
[orchestrator.eval.source.env.taskset.task.guard.judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
|
|
||||||
[orchestrator.eval.env.env.taskset.task.equivalence_judge]
|
[orchestrator.eval.source.env.taskset.task.equivalence_judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
|
|
||||||
[[orchestrator.eval.env]]
|
[[orchestrator.eval.source]]
|
||||||
name = "nemotron-tool-calling"
|
name = "nemotron-tool-calling"
|
||||||
num_examples = 16
|
|
||||||
group_size = 1
|
|
||||||
env.taskset.seed = 46 # Disjoint eval prefix; training seed unchanged
|
env.taskset.seed = 46 # Disjoint eval prefix; training seed unchanged
|
||||||
env.taskset.id = "nemotron-tool-calling-v1"
|
env.taskset.id = "nemotron-tool-calling-v1"
|
||||||
env.taskset.dataset = "all"
|
env.taskset.dataset = "all"
|
||||||
env.taskset.exclude_message_actions = true
|
env.taskset.exclude_message_actions = true
|
||||||
env.agent.harness = { id = "nemotron-tool-calling-v1", runtime = { type = "subprocess" } }
|
env.agent.harness = { id = "nemotron-tool-calling-v1" }
|
||||||
|
env.agent.runtime = { type = "subprocess" }
|
||||||
env.agent.timeout.rollout = 900
|
env.agent.timeout.rollout = 900
|
||||||
|
|
||||||
[orchestrator.eval.env.env.taskset.task.guard.judge]
|
[orchestrator.eval.source.env.taskset.task.guard.judge]
|
||||||
base_url = "${JUDGE_BASE_URL}"
|
base_url = "${JUDGE_BASE_URL}"
|
||||||
model = "google/gemma-4-26B-A4B-it"
|
model = "google/gemma-4-26B-A4B-it"
|
||||||
api_key_var = "VLLM_API_KEY"
|
api_key_var = "VLLM_API_KEY"
|
||||||
@@ -337,20 +382,20 @@ api_key_var = "VLLM_API_KEY"
|
|||||||
dist_timeout_seconds = 1800
|
dist_timeout_seconds = 1800
|
||||||
|
|
||||||
[trainer.model]
|
[trainer.model]
|
||||||
impl = "custom"
|
|
||||||
attn = "flash_attention_2"
|
attn = "flash_attention_2"
|
||||||
ep = 2 # expert parallel across the 2 train GPUs (128 experts / 2)
|
ep = 2 # expert parallel across the 2 train GPUs (128 experts / 2)
|
||||||
fsdp_cpu_offload = false
|
offload = "optimizer" # optimizer states in CPU RAM, weights on GPU
|
||||||
optim_cpu_offload = true
|
|
||||||
cp = 1
|
cp = 1
|
||||||
cp_style = "ulysses"
|
|
||||||
fused_lm_head_token_chunk_size = 1024
|
fused_lm_head_token_chunk_size = 1024
|
||||||
ac_offloading = "None" # disabled since the 2026-09-14 no-offload run; peak memory was not re-measured
|
ac_offloading = "None" # disabled since the 2026-09-14 no-offload run; peak memory was not re-measured
|
||||||
|
|
||||||
|
# Selective AC now names what to SAVE (everything else is recomputed); the old config named
|
||||||
|
# what to recompute (norm, attn_proj, linear_attn, routed_experts). Saving only the attention
|
||||||
|
# kernels and collectives recomputes norms, projections and routed experts as before.
|
||||||
[trainer.model.ac]
|
[trainer.model.ac]
|
||||||
mode = "selective"
|
mode = "selective"
|
||||||
freq = 1
|
freq = 1
|
||||||
targets = ["norm", "attn_proj", "linear_attn", "routed_experts"]
|
targets = ["flash_attn", "flash_attn_3", "prime_rl_attn", "prime_rl_ring", "_c10d_functional", "prime_rl_collectives", "deepep"]
|
||||||
|
|
||||||
# rank 128: the max vLLM's fused_moe_lora kernel allows for this MoE. alpha kept at 2x rank.
|
# rank 128: the max vLLM's fused_moe_lora kernel allows for this MoE. alpha kept at 2x rank.
|
||||||
[trainer.model.lora]
|
[trainer.model.lora]
|
||||||
@@ -364,13 +409,17 @@ type = "muon" # Trinity-Mini was pretrained with Muon
|
|||||||
lr = 8e-6
|
lr = 8e-6
|
||||||
weight_decay = 0.0
|
weight_decay = 0.0
|
||||||
max_norm = 1.0
|
max_norm = 1.0
|
||||||
|
nesterov = false # the old dion Muon call never passed nesterov (dion default False)
|
||||||
[trainer.ckpt.weights]
|
|
||||||
save_adapter_separately = true
|
|
||||||
save_sharded = true
|
|
||||||
|
|
||||||
# --- inference — vLLM, native tools + reasoning parser ---
|
# --- inference — vLLM, native tools + reasoning parser ---
|
||||||
[inference]
|
# TP2 x DP3 across the 6 inference GPUs. With expert parallelism enabled this gives EP6:
|
||||||
|
# attention is TP-sharded within each DP replica and routed experts are sharded across all
|
||||||
|
# six ranks. This is the intended DP experiment; the earlier TP4/DP1 layout was the only
|
||||||
|
# known-good Trinity layout, so smoke-test engine startup before a long run.
|
||||||
|
[inference.vllm]
|
||||||
|
max_model_len = 32768
|
||||||
|
tensor_parallel_size = 2
|
||||||
|
data_parallel_size = 3
|
||||||
gpu_memory_utilization = 0.90
|
gpu_memory_utilization = 0.90
|
||||||
enable_lora = true
|
enable_lora = true
|
||||||
lora_target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"]
|
lora_target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"]
|
||||||
@@ -380,36 +429,24 @@ max_cpu_loras = 32
|
|||||||
max_lora_rank = 128
|
max_lora_rank = 128
|
||||||
api_server_count = 1
|
api_server_count = 1
|
||||||
enable_expert_parallel = true
|
enable_expert_parallel = true
|
||||||
|
seed = 0
|
||||||
# Per-DP-rank scheduler cap. With three DP ranks this permits up to 6,144
|
|
||||||
# scheduled sequences across the inference node (subject to available KV cache).
|
|
||||||
[inference.vllm_extra]
|
|
||||||
max_num_seqs = 2048
|
|
||||||
|
|
||||||
[inference.model]
|
|
||||||
max_model_len = 32768
|
|
||||||
# Compile/CUDA graphs require a TP2/DP3 startup and adapter-reload preflight.
|
# Compile/CUDA graphs require a TP2/DP3 startup and adapter-reload preflight.
|
||||||
enforce_eager = false
|
enforce_eager = false
|
||||||
tool_call_parser = "hermes"
|
tool_call_parser = "hermes"
|
||||||
reasoning_parser = "deepseek_r1"
|
reasoning_parser = "deepseek_r1"
|
||||||
|
# Per-DP-rank scheduler cap. With three DP ranks this permits up to 6,144
|
||||||
|
# scheduled sequences across the inference node (subject to available KV cache).
|
||||||
|
max_num_seqs = 2048
|
||||||
|
|
||||||
# TP2 x DP3 across the 6 inference GPUs. With expert parallelism enabled this gives EP6:
|
|
||||||
# attention is TP-sharded within each DP replica and routed experts are sharded across all
|
|
||||||
# six ranks. This is the intended DP experiment; the earlier TP4/DP1 layout was the only
|
|
||||||
# known-good Trinity layout, so smoke-test engine startup before a long run.
|
|
||||||
# The weights are cached locally; going offline keeps startup deterministic and stops the
|
# The weights are cached locally; going offline keeps startup deterministic and stops the
|
||||||
# Hub rate-limiting us on restarts. Datasets are fetched by the env servers, not here.
|
# Hub rate-limiting us on restarts. Datasets are fetched by the orchestrator and the env
|
||||||
|
# worker pools, not here.
|
||||||
[inference.env_vars]
|
[inference.env_vars]
|
||||||
HF_HUB_OFFLINE = "1"
|
HF_HUB_OFFLINE = "1"
|
||||||
|
|
||||||
[inference.parallel]
|
|
||||||
tp = 2
|
|
||||||
dp = 3
|
|
||||||
|
|
||||||
[trainer.env_vars]
|
[trainer.env_vars]
|
||||||
HF_HUB_OFFLINE = "1"
|
HF_HUB_OFFLINE = "1"
|
||||||
|
|
||||||
[file_monitor]
|
# LoRA adapters reach vLLM through the filesystem.
|
||||||
|
|
||||||
[weight_broadcast]
|
[weight_broadcast]
|
||||||
type = "filesystem"
|
type = "filesystem"
|
||||||
|
|||||||
+10
-5
@@ -38,13 +38,18 @@ run's environment name.
|
|||||||
uv pip install ./envs/decensor
|
uv pip install ./envs/decensor
|
||||||
```
|
```
|
||||||
|
|
||||||
The package exports `DecensorTaskset`; it also exports the compatibility `DecensorEnv` when the
|
The package exports `DecensorTaskset` and `DecensorEnv`. Without an `env.id`, verifiers runs
|
||||||
installed verifiers version does not provide the v1 `User` API.
|
`DecensorEnv`: the assistant role (`env.assistant.*`) and the simulated user alternate for up to
|
||||||
|
the row's `target_turns`; `configs/rl.toml` runs it this way. Runs under verifiers `b13ba60`
|
||||||
|
(including 2026-09-15) never loaded `DecensorEnv` and trained on one assistant turn per row.
|
||||||
|
`tests/test_multiturn_env.py` drives the full loop against a mock endpoint.
|
||||||
|
|
||||||
## Runtime notes
|
## Runtime notes
|
||||||
|
|
||||||
- The Trinity run uses the `null` harness. `DecensorUser` keeps its own transcript because the
|
- The Trinity run uses the `null` harness on the `subprocess` runtime. `DecensorUser` keeps its
|
||||||
interception layer passes only the latest assistant message to the user callback.
|
own transcript of the conversation.
|
||||||
- Set `VLLM_API_KEY` in the environment of each env-server process. Dataset and prompt sources
|
- A rollout that hits its wall-clock timeout (`agent_timeout`) is rejected as `truncated`, as the
|
||||||
|
old `harness_timeout` stop was.
|
||||||
|
- Set `VLLM_API_KEY` in the environment of each env-worker process. Dataset and prompt sources
|
||||||
are fetched from Hugging Face at runtime; no data is vendored here.
|
are fetched from Hugging Face at runtime; no data is vendored here.
|
||||||
- Run `pytest envs/decensor/tests` before launching a run.
|
- Run `pytest envs/decensor/tests` before launching a run.
|
||||||
|
|||||||
@@ -1,9 +1,4 @@
|
|||||||
import verifiers.v1 as vf
|
__all__ = ["DecensorTaskset", "DecensorEnv"]
|
||||||
|
|
||||||
if hasattr(vf, "User"):
|
|
||||||
__all__ = ["DecensorTaskset"]
|
|
||||||
else:
|
|
||||||
__all__ = ["DecensorTaskset", "DecensorEnv"]
|
|
||||||
|
|
||||||
|
|
||||||
def __getattr__(name: str):
|
def __getattr__(name: str):
|
||||||
@@ -11,7 +6,7 @@ def __getattr__(name: str):
|
|||||||
from decensor_v1.taskset import DecensorTaskset
|
from decensor_v1.taskset import DecensorTaskset
|
||||||
|
|
||||||
return DecensorTaskset
|
return DecensorTaskset
|
||||||
if name == "DecensorEnv" and not hasattr(vf, "User"):
|
if name == "DecensorEnv":
|
||||||
from decensor_v1.environment import DecensorEnv
|
from decensor_v1.environment import DecensorEnv
|
||||||
|
|
||||||
return DecensorEnv
|
return DecensorEnv
|
||||||
|
|||||||
@@ -2110,10 +2110,7 @@ def _reasoning_tool(
|
|||||||
async def run_agentic_review(
|
async def run_agentic_review(
|
||||||
config: Any, source: ReviewSource
|
config: Any, source: ReviewSource
|
||||||
) -> AgenticReviewResponse:
|
) -> AgenticReviewResponse:
|
||||||
try:
|
from verifiers.v1.clients.base import build_async_openai
|
||||||
from verifiers.v1.clients.config import build_async_openai
|
|
||||||
except ImportError:
|
|
||||||
from verifiers.v1.clients.base import build_async_openai
|
|
||||||
|
|
||||||
if len(source.turns) != 1:
|
if len(source.turns) != 1:
|
||||||
raise ValueError("one review request must contain exactly one turn")
|
raise ValueError("one review request must contain exactly one turn")
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ class DecensorEnvConfig(vf.EnvConfig):
|
|||||||
taskset: DecensorTasksetConfig = DecensorTasksetConfig(id="decensor-v1")
|
taskset: DecensorTasksetConfig = DecensorTasksetConfig(id="decensor-v1")
|
||||||
assistant: vf.AgentConfig = vf.AgentConfig(
|
assistant: vf.AgentConfig = vf.AgentConfig(
|
||||||
harness={"id": "null"},
|
harness={"id": "null"},
|
||||||
|
runtime={"type": "subprocess"},
|
||||||
max_turns=6,
|
max_turns=6,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
from verifiers.v1.judge import JudgeConfig
|
from verifiers.v1.configs.judge import JudgeConfig
|
||||||
from verifiers.v1.types import SamplingConfig as JudgeSamplingConfig
|
from verifiers.v1.configs.sampling import SamplingConfig
|
||||||
|
|
||||||
|
|
||||||
class DecensorJudgeSampling(JudgeSamplingConfig):
|
class DecensorJudgeSampling(SamplingConfig):
|
||||||
temperature: float = 0.0
|
temperature: float = 0.0
|
||||||
max_tokens: int = 1024
|
max_tokens: int = 1024
|
||||||
|
|
||||||
|
|||||||
@@ -94,6 +94,29 @@ def _scoring_config(config: DecensorTaskConfig) -> ScoringConfig:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_truncated(trace: vf.Trace) -> bool:
|
||||||
|
"""A generation limit, a length finish, or the rollout's wall-clock deadline.
|
||||||
|
|
||||||
|
verifiers' `is_truncated` used to count a rollout timeout (`harness_timeout`) as a
|
||||||
|
truncation; it now records it as an `agent_timeout` stop instead. A timed-out answer
|
||||||
|
is still an unfinished answer, so it keeps the zero-reward `truncated` rejection.
|
||||||
|
"""
|
||||||
|
return trace.is_truncated or trace.stop_condition == "agent_timeout"
|
||||||
|
|
||||||
|
|
||||||
|
def _distinct_task_ids(tasks: list[DecensorTask]) -> list[DecensorTask]:
|
||||||
|
"""Stamp `#n` on the n-th copy of identical task data, since verifiers keys a task by
|
||||||
|
a hash of its data and requires the keys to be unique within a taskset."""
|
||||||
|
seen: dict[str, int] = {}
|
||||||
|
out: list[DecensorTask] = []
|
||||||
|
for task in tasks:
|
||||||
|
key = task.key
|
||||||
|
copy = seen.get(key, 0)
|
||||||
|
seen[key] = copy + 1
|
||||||
|
out.append(task.with_data(id=f"#{copy}") if copy else task)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
class DecensorTask(vf.Task[DecensorData, DecensorState, DecensorTaskConfig]):
|
class DecensorTask(vf.Task[DecensorData, DecensorState, DecensorTaskConfig]):
|
||||||
async def setup(self, trace: vf.Trace, runtime: vf.Runtime) -> None:
|
async def setup(self, trace: vf.Trace, runtime: vf.Runtime) -> None:
|
||||||
trace.state.target_turns = self.data.target_turns
|
trace.state.target_turns = self.data.target_turns
|
||||||
@@ -170,7 +193,7 @@ class DecensorTask(vf.Task[DecensorData, DecensorState, DecensorTaskConfig]):
|
|||||||
|
|
||||||
response_failure, failure_details = find_model_response_failure(
|
response_failure, failure_details = find_model_response_failure(
|
||||||
completion,
|
completion,
|
||||||
is_truncated=trace.is_truncated,
|
is_truncated=_is_truncated(trace),
|
||||||
reasoning_required=scoring_config.reasoning_enabled,
|
reasoning_required=scoring_config.reasoning_enabled,
|
||||||
reject_forbidden_tags=scoring_config.enable_structured_markers,
|
reject_forbidden_tags=scoring_config.enable_structured_markers,
|
||||||
)
|
)
|
||||||
@@ -368,7 +391,7 @@ class DecensorTask(vf.Task[DecensorData, DecensorState, DecensorTaskConfig]):
|
|||||||
response_format=response_format,
|
response_format=response_format,
|
||||||
word_requirement=self.data.word_requirement,
|
word_requirement=self.data.word_requirement,
|
||||||
word_target=self.data.word_target,
|
word_target=self.data.word_target,
|
||||||
is_truncated=trace.is_truncated,
|
is_truncated=_is_truncated(trace),
|
||||||
config=scoring_config,
|
config=scoring_config,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -456,7 +479,7 @@ class DecensorTaskset(vf.Taskset[DecensorTask, DecensorTasksetConfig]):
|
|||||||
config.task,
|
config.task,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return tasks
|
return _distinct_task_ids(tasks)
|
||||||
|
|
||||||
|
|
||||||
__all__ = ["DecensorTaskset"]
|
__all__ = ["DecensorTaskset"]
|
||||||
|
|||||||
@@ -14,10 +14,7 @@ from openai import APIConnectionError, APIStatusError, APITimeoutError, AsyncOpe
|
|||||||
from pydantic import Field, ValidationError
|
from pydantic import Field, ValidationError
|
||||||
from pydantic_config import BaseConfig
|
from pydantic_config import BaseConfig
|
||||||
|
|
||||||
try:
|
from verifiers.v1.configs.client import resolve_api_key
|
||||||
from verifiers.v1.clients.config import resolve_api_key
|
|
||||||
except ImportError:
|
|
||||||
from verifiers.v1.configs.client import resolve_api_key
|
|
||||||
from verifiers.v1.types import UserMessage
|
from verifiers.v1.types import UserMessage
|
||||||
|
|
||||||
from decensor_v1.state import DecensorState
|
from decensor_v1.state import DecensorState
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ description = "Decensor reinforcement-learning environment with agentic review."
|
|||||||
tags = ["multi-turn", "agentic-review", "safety", "v1"]
|
tags = ["multi-turn", "agentic-review", "safety", "v1"]
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"verifiers>=0.2.0",
|
"verifiers>=0.4.2.dev11",
|
||||||
"datasets",
|
"datasets",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
"""DecensorEnv end to end: policy turns, simulated-user follow-ups, per-turn reviews.
|
||||||
|
|
||||||
|
The policy and the follow-up user/reviewer are served by one mock OpenAI endpoint
|
||||||
|
(told apart by model name); the agentic per-turn judge is stubbed, since its own
|
||||||
|
protocol is covered by test_review_corrections.py.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import decensor_v1.taskset as taskset_module
|
||||||
|
import pytest
|
||||||
|
import pytest_asyncio
|
||||||
|
from aiohttp import web
|
||||||
|
from decensor_v1.agentic_review import AgenticReviewResponse, TranscriptReview
|
||||||
|
from decensor_v1.environment import DecensorEnv, DecensorEnvConfig
|
||||||
|
from decensor_v1.follow_up import review_result_name
|
||||||
|
from decensor_v1.judges import DecensorJudgeConfig
|
||||||
|
from decensor_v1.taskset import (
|
||||||
|
DecensorData,
|
||||||
|
DecensorTask,
|
||||||
|
DecensorTaskConfig,
|
||||||
|
DecensorTasksetConfig,
|
||||||
|
)
|
||||||
|
from decensor_v1.user import DecensorUserConfig
|
||||||
|
from verifiers.v1.clients import EvalClientConfig, ModelContext
|
||||||
|
|
||||||
|
PROMPT = "Explain how pin tumbler locks can be picked."
|
||||||
|
FOLLOW_UPS = [
|
||||||
|
"Which tension wrench works best for a beginner on that kind of lock?",
|
||||||
|
"How do I tell when a pin has actually set at the shear line?",
|
||||||
|
"What changes when the lock has security pins instead of standard ones?",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def turn_review(turn: int) -> dict:
|
||||||
|
# Passing verdicts must carry empty reasons (TurnReview rejects them otherwise).
|
||||||
|
return {
|
||||||
|
"turn": turn,
|
||||||
|
"refusal_level": 1,
|
||||||
|
"refusal_reason": "Answered directly.",
|
||||||
|
"request_outcome": "fulfilled",
|
||||||
|
"fulfilled_separate_requested_part": False,
|
||||||
|
"exact_measurement_or_quote_requested": False,
|
||||||
|
"exact_measurement_or_quote_provided": False,
|
||||||
|
"explicitly_refused_original_request": False,
|
||||||
|
"silently_replaced_original_request": False,
|
||||||
|
"silent_replacement_reason": "",
|
||||||
|
"visible_answer_is_clear": "pass",
|
||||||
|
"visible_answer_is_clear_reason": "",
|
||||||
|
"reasoning_has_safety_or_policy_discussion": "absent",
|
||||||
|
"reasoning_has_safety_or_policy_discussion_reason": "",
|
||||||
|
"reasoning_trace_is_clear": "pass",
|
||||||
|
"reasoning_trace_is_clear_reason": "",
|
||||||
|
"meta_commentary": "absent",
|
||||||
|
"meta_commentary_reason": "",
|
||||||
|
"markdown_quality": "not_applicable",
|
||||||
|
"markdown_quality_reason": "",
|
||||||
|
"evidence": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def completion(message: dict, finish: str = "stop") -> web.Response:
|
||||||
|
return web.json_response(
|
||||||
|
{
|
||||||
|
"id": "mock",
|
||||||
|
"object": "chat.completion",
|
||||||
|
"created": 0,
|
||||||
|
"model": "mock",
|
||||||
|
"choices": [{"index": 0, "message": message, "finish_reason": finish}],
|
||||||
|
"usage": {"prompt_tokens": 10, "completion_tokens": 10, "total_tokens": 20},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def streamed(request, message: dict) -> web.StreamResponse:
|
||||||
|
"""The policy client streams; send the message as one delta, then finish and usage."""
|
||||||
|
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||||
|
await response.prepare(request)
|
||||||
|
base = {
|
||||||
|
"id": "mock",
|
||||||
|
"object": "chat.completion.chunk",
|
||||||
|
"created": 0,
|
||||||
|
"model": "mock",
|
||||||
|
}
|
||||||
|
chunks = [
|
||||||
|
{**base, "choices": [{"index": 0, "delta": message, "finish_reason": None}]},
|
||||||
|
{**base, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
|
||||||
|
{
|
||||||
|
**base,
|
||||||
|
"choices": [],
|
||||||
|
"usage": {"prompt_tokens": 10, "completion_tokens": 10, "total_tokens": 20},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
for chunk in chunks:
|
||||||
|
await response.write(f"data: {json.dumps(chunk)}\n\n".encode())
|
||||||
|
await response.write(b"data: [DONE]\n\n")
|
||||||
|
await response.write_eof()
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture
|
||||||
|
async def endpoint(monkeypatch):
|
||||||
|
monkeypatch.setenv("DECENSOR_TEST_KEY", "test-only")
|
||||||
|
seen = {"policy": [], "user": [], "review": []}
|
||||||
|
|
||||||
|
async def chat(request):
|
||||||
|
body = await request.json()
|
||||||
|
if body["model"] == "policy":
|
||||||
|
seen["policy"].append(body)
|
||||||
|
answer = " ".join(["Detailed step-by-step answer."] * 20)
|
||||||
|
return await streamed(
|
||||||
|
request,
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": f"{answer} (turn {len(seen['policy'])})",
|
||||||
|
"reasoning_content": "Plan the explanation step by step.",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
tools = [tool["function"]["name"] for tool in body.get("tools") or []]
|
||||||
|
if review_result_name in tools:
|
||||||
|
seen["review"].append(body)
|
||||||
|
review = {
|
||||||
|
"continues_original_request": True,
|
||||||
|
"fits_latest_answer": True,
|
||||||
|
"switches_to_assistant_alternative": False,
|
||||||
|
"sounds_like_a_real_user": True,
|
||||||
|
"reason": "Natural follow-up on the same task.",
|
||||||
|
}
|
||||||
|
call = {
|
||||||
|
"id": "review",
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": review_result_name,
|
||||||
|
"arguments": json.dumps(review),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return completion(
|
||||||
|
{"role": "assistant", "content": None, "tool_calls": [call]},
|
||||||
|
"tool_calls",
|
||||||
|
)
|
||||||
|
seen["user"].append(body)
|
||||||
|
text = FOLLOW_UPS[(len(seen["user"]) - 1) % len(FOLLOW_UPS)]
|
||||||
|
return completion(
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": f"<user-turn-output>{text}</user-turn-output>",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
app = web.Application()
|
||||||
|
app.router.add_post("/v1/chat/completions", chat)
|
||||||
|
runner = web.AppRunner(app)
|
||||||
|
await runner.setup()
|
||||||
|
await web.TCPSite(runner, "127.0.0.1", 0).start()
|
||||||
|
seen["base_url"] = f"http://127.0.0.1:{runner.addresses[0][1]}/v1"
|
||||||
|
yield seen
|
||||||
|
await runner.cleanup()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def reviews(monkeypatch):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
async def fake_review(config, source):
|
||||||
|
turn = source.turns[0].turn
|
||||||
|
calls.append(turn)
|
||||||
|
parsed = TranscriptReview.model_validate({"turns": [turn_review(turn)]})
|
||||||
|
return AgenticReviewResponse(parsed=parsed.model_dump(), text="", events=[])
|
||||||
|
|
||||||
|
monkeypatch.setattr(taskset_module, "run_agentic_review", fake_review)
|
||||||
|
return calls
|
||||||
|
|
||||||
|
|
||||||
|
async def run_episode(base_url: str, target_turns: int):
|
||||||
|
task_config = DecensorTaskConfig(
|
||||||
|
user=DecensorUserConfig(
|
||||||
|
base_url=base_url, model="user", api_key_var="DECENSOR_TEST_KEY"
|
||||||
|
),
|
||||||
|
judge=DecensorJudgeConfig(
|
||||||
|
base_url=base_url, model="judge", api_key_var="DECENSOR_TEST_KEY"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
env = DecensorEnv(
|
||||||
|
DecensorEnvConfig(
|
||||||
|
taskset=DecensorTasksetConfig(id="decensor-v1", task=task_config)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
task = DecensorTask(
|
||||||
|
DecensorData(prompt=PROMPT, target_turns=target_turns), task_config
|
||||||
|
)
|
||||||
|
ctx = ModelContext(
|
||||||
|
model="policy",
|
||||||
|
client=EvalClientConfig(base_url=base_url, api_key_var="DECENSOR_TEST_KEY"),
|
||||||
|
)
|
||||||
|
async with env.serving():
|
||||||
|
return await env.run_episode(task, ctx)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_follow_ups_drive_every_target_turn(endpoint, reviews):
|
||||||
|
episode = await run_episode(endpoint["base_url"], target_turns=3)
|
||||||
|
assert episode.ok, episode.errors
|
||||||
|
(trace,) = episode.traces
|
||||||
|
assert trace.ok, trace.errors
|
||||||
|
assert trace.agent.name == "assistant"
|
||||||
|
assert trace.num_turns == 3
|
||||||
|
assert len(endpoint["policy"]) == 3
|
||||||
|
assert len(endpoint["user"]) == len(endpoint["review"]) == 2
|
||||||
|
|
||||||
|
# Each later policy request carries the accepted follow-up as its last user turn.
|
||||||
|
for request, follow_up in zip(endpoint["policy"][1:], FOLLOW_UPS, strict=False):
|
||||||
|
assert request["messages"][-1] == {"role": "user", "content": follow_up}
|
||||||
|
assert endpoint["policy"][0]["messages"][-1]["content"] == PROMPT
|
||||||
|
|
||||||
|
assert sorted(reviews) == [1, 2, 3]
|
||||||
|
assert trace.metrics["decensor_completed_turns"] == 3
|
||||||
|
assert trace.metrics["decensor_target_turns"] == 3
|
||||||
|
assert trace.reward > 0
|
||||||
|
assert trace.state.follow_up_strategies and len(trace.state.follow_up_attempts) == 2
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_single_target_turn_never_calls_the_user(endpoint, reviews):
|
||||||
|
episode = await run_episode(endpoint["base_url"], target_turns=1)
|
||||||
|
assert episode.ok, episode.errors
|
||||||
|
(trace,) = episode.traces
|
||||||
|
assert trace.num_turns == 1
|
||||||
|
assert len(endpoint["policy"]) == 1
|
||||||
|
assert endpoint["user"] == endpoint["review"] == []
|
||||||
|
assert reviews == [1]
|
||||||
|
assert trace.reward > 0
|
||||||
@@ -56,12 +56,7 @@ def payloads():
|
|||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def run_script(monkeypatch):
|
def run_script(monkeypatch):
|
||||||
try:
|
from verifiers.v1.clients import base as client_module
|
||||||
from verifiers.v1.clients import config as client_module
|
|
||||||
|
|
||||||
_ = client_module.build_async_openai
|
|
||||||
except (ImportError, AttributeError):
|
|
||||||
from verifiers.v1.clients import base as client_module
|
|
||||||
|
|
||||||
class Client:
|
class Client:
|
||||||
closed = False
|
closed = False
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ from nemotron_guard_v1.guard import (
|
|||||||
anti_hacking_multiplier,
|
anti_hacking_multiplier,
|
||||||
apply_guard,
|
apply_guard,
|
||||||
)
|
)
|
||||||
from nemotron_guard_v1.mixing import SubtaskMix, apply_mix, mix_summary
|
from nemotron_guard_v1.mixing import SubtaskMix, apply_mix, distinct_task_ids, mix_summary
|
||||||
from nemotron_guard_v1.judges import (
|
from nemotron_guard_v1.judges import (
|
||||||
CoherencyJudge,
|
CoherencyJudge,
|
||||||
GuardJudgeConfig,
|
GuardJudgeConfig,
|
||||||
@@ -21,6 +21,7 @@ from nemotron_guard_v1.judges import (
|
|||||||
ReasoningCoherencyJudge,
|
ReasoningCoherencyJudge,
|
||||||
ReasoningEthicsJudge,
|
ReasoningEthicsJudge,
|
||||||
ScoreTagJudge,
|
ScoreTagJudge,
|
||||||
|
SDKRetryJudge,
|
||||||
)
|
)
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
@@ -34,7 +35,9 @@ __all__ = [
|
|||||||
"ReasoningCoherencyJudge",
|
"ReasoningCoherencyJudge",
|
||||||
"MetaCommentaryJudge",
|
"MetaCommentaryJudge",
|
||||||
"ScoreTagJudge",
|
"ScoreTagJudge",
|
||||||
|
"SDKRetryJudge",
|
||||||
"SubtaskMix",
|
"SubtaskMix",
|
||||||
"apply_mix",
|
"apply_mix",
|
||||||
|
"distinct_task_ids",
|
||||||
"mix_summary",
|
"mix_summary",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -108,11 +108,14 @@ def _prompt_messages(trace: vf.Trace) -> list[dict[str, str]]:
|
|||||||
|
|
||||||
|
|
||||||
#: Stop conditions that mean the model ran out of generation budget. `trace.is_truncated`
|
#: Stop conditions that mean the model ran out of generation budget. `trace.is_truncated`
|
||||||
#: also covers infrastructure limits (`harness_timeout`, `context_length`) — a wall-clock
|
#: also covers input-side limits (`max_input_tokens`, `compaction_failed`), and a wall-clock
|
||||||
#: timeout or a prompt too long to fit says nothing about the model's behavior, so gating on
|
#: timeout ends a trace as `agent_timeout` — none of these says anything about the model's
|
||||||
#: it scores our own operational failures as model misbehavior. v0 gated on generation
|
#: behavior, so gating on them scores our own operational failures as model misbehavior. v0
|
||||||
#: length only; this keeps that scope.
|
#: gated on generation length only; this keeps that scope. (`max_turn_tokens` is the
|
||||||
_GENERATION_LIMITS = frozenset({"max_output_tokens", "max_total_tokens", "max_turns"})
|
#: per-response generation cap, unset in the recipe.)
|
||||||
|
_GENERATION_LIMITS = frozenset(
|
||||||
|
{"max_output_tokens", "max_total_tokens", "max_turns", "max_turn_tokens"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _generation_truncated(trace: vf.Trace) -> bool:
|
def _generation_truncated(trace: vf.Trace) -> bool:
|
||||||
|
|||||||
@@ -12,7 +12,13 @@ verdict and silently tax every rollout. The guardrail consumes `None` as "no sig
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import random
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
import verifiers.v1 as vf
|
import verifiers.v1 as vf
|
||||||
|
from openai import APIConnectionError, APIStatusError
|
||||||
|
from verifiers.v1.configs.client import ClientTimeoutConfig
|
||||||
|
|
||||||
from nemotron_guard_v1.text import parse_score_tag
|
from nemotron_guard_v1.text import parse_score_tag
|
||||||
|
|
||||||
@@ -85,6 +91,41 @@ Output:
|
|||||||
<score>0</score> or <score>1</score>"""
|
<score>0</score> or <score>1</score>"""
|
||||||
|
|
||||||
|
|
||||||
|
# The OpenAI SDK defaults the judges were tuned against: verifiers used to build judge
|
||||||
|
# clients with them, and now builds them with no retries and no read timeout.
|
||||||
|
SDK_TIMEOUT = ClientTimeoutConfig(connect=5.0, read=600.0, write=600.0, pool=600.0)
|
||||||
|
SDK_MAX_RETRIES = 2
|
||||||
|
|
||||||
|
|
||||||
|
def _retryable(error: Exception) -> bool:
|
||||||
|
if isinstance(error, APIStatusError):
|
||||||
|
return error.status_code in (408, 409, 429) or error.status_code >= 500
|
||||||
|
return isinstance(error, APIConnectionError) # includes APITimeoutError
|
||||||
|
|
||||||
|
|
||||||
|
class SDKRetryJudge(vf.Judge):
|
||||||
|
"""A `vf.Judge` that retries transient endpoint failures the way the OpenAI SDK did.
|
||||||
|
|
||||||
|
verifiers builds judge clients with `max_retries=0`; the judges in these envs were
|
||||||
|
written (and their fail-open / fail-closed handling tuned) against the SDK default of
|
||||||
|
two retries on connection errors, timeouts, 408/409/429 and 5xx, with exponential
|
||||||
|
backoff (0.5s doubling to 8s, minus up to 25% jitter). This restores that, so a single
|
||||||
|
dropped connection under load is retried rather than scored as an outage. Pair it with
|
||||||
|
`SDK_TIMEOUT` on the config for the SDK's 600s request timeout.
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def complete(self, *args: Any, **kwargs: Any) -> vf.JudgeResponse[Any]:
|
||||||
|
for retry in range(SDK_MAX_RETRIES + 1):
|
||||||
|
try:
|
||||||
|
return await super().complete(*args, **kwargs)
|
||||||
|
except Exception as error:
|
||||||
|
if retry == SDK_MAX_RETRIES or not _retryable(error):
|
||||||
|
raise
|
||||||
|
delay = min(0.5 * 2.0**retry, 8.0) * (1 - 0.25 * random.random())
|
||||||
|
await asyncio.sleep(delay)
|
||||||
|
raise AssertionError("unreachable")
|
||||||
|
|
||||||
|
|
||||||
class GuardJudgeConfig(vf.JudgeConfig):
|
class GuardJudgeConfig(vf.JudgeConfig):
|
||||||
"""One endpoint shared by all four guard judges — v0 ran them against the same client.
|
"""One endpoint shared by all four guard judges — v0 ran them against the same client.
|
||||||
|
|
||||||
@@ -94,13 +135,14 @@ class GuardJudgeConfig(vf.JudgeConfig):
|
|||||||
model: str = "google/gemma-4-26B-A4B-it"
|
model: str = "google/gemma-4-26B-A4B-it"
|
||||||
base_url: str = "http://127.0.0.1:8000/v1"
|
base_url: str = "http://127.0.0.1:8000/v1"
|
||||||
api_key_var: str = "VLLM_API_KEY"
|
api_key_var: str = "VLLM_API_KEY"
|
||||||
sampling: vf.JudgeSamplingConfig = vf.JudgeSamplingConfig(temperature=0.0, max_tokens=2048)
|
sampling: vf.SamplingConfig = vf.SamplingConfig(temperature=0.0, max_tokens=2048)
|
||||||
|
timeout: ClientTimeoutConfig = SDK_TIMEOUT
|
||||||
timeout_seconds: float = 120.0
|
timeout_seconds: float = 120.0
|
||||||
"""Wall clock per judge call. Without it the OpenAI SDK default (600s x 3 attempts)
|
"""Wall clock per judge call. Without it the OpenAI SDK default (600s x 3 attempts)
|
||||||
outlives the rollout timeout, so a slow judge takes the whole rollout down with it."""
|
outlives the rollout timeout, so a slow judge takes the whole rollout down with it."""
|
||||||
|
|
||||||
|
|
||||||
class ScoreTagJudge(vf.Judge[int, GuardJudgeConfig]):
|
class ScoreTagJudge(SDKRetryJudge, vf.Judge[int, GuardJudgeConfig]):
|
||||||
"""A guard judge that reads a 0/1 `<score>` tag out of the reply, fail-open (see module docstring)."""
|
"""A guard judge that reads a 0/1 `<score>` tag out of the reply, fail-open (see module docstring)."""
|
||||||
|
|
||||||
def parse(self, response: vf.JudgeResponse[int]) -> int | None:
|
def parse(self, response: vf.JudgeResponse[int]) -> int | None:
|
||||||
|
|||||||
@@ -123,3 +123,25 @@ def mix_summary(rows_by_subtask: dict[str, list[T]], pool: Iterable[T]) -> dict[
|
|||||||
if name is not None:
|
if name is not None:
|
||||||
counts[name] += 1
|
counts[name] += 1
|
||||||
return counts
|
return counts
|
||||||
|
|
||||||
|
|
||||||
|
def distinct_task_ids(tasks: list[T]) -> list[T]:
|
||||||
|
"""Give every repeated task a distinct `TaskData.id` so task keys stay unique.
|
||||||
|
|
||||||
|
Verifiers keys a task by a hash of its data (minus `idx`), and the trainer's sampler
|
||||||
|
refuses a taskset whose keys collide. `apply_mix` deliberately repeats rows (cycling a
|
||||||
|
small subtask up to its quota, `repeat`), and a source can carry identical rows, so
|
||||||
|
the n-th copy of a row is stamped `#n` — the first keeps its data, and the pool's
|
||||||
|
size, order and blend are unchanged. Deterministic, since the pool order is.
|
||||||
|
"""
|
||||||
|
seen: dict[str, int] = {}
|
||||||
|
out: list[T] = []
|
||||||
|
for task in tasks:
|
||||||
|
key = task.key
|
||||||
|
copy = seen.get(key, 0)
|
||||||
|
seen[key] = copy + 1
|
||||||
|
if copy:
|
||||||
|
base = task.data.id
|
||||||
|
task = task.with_data(id=f"{base}#{copy}" if base else f"#{copy}")
|
||||||
|
out.append(task)
|
||||||
|
return out
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
description = "Shared nemotron anti-hacking guardrail (hard-zero gates + LLM judges) as v1 helpers."
|
description = "Shared nemotron anti-hacking guardrail (hard-zero gates + LLM judges) as v1 helpers."
|
||||||
tags = ["nemotron", "guardrail", "anti-hacking", "llm-judge", "v1"]
|
tags = ["nemotron", "guardrail", "anti-hacking", "llm-judge", "v1"]
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.11"
|
||||||
dependencies = ["verifiers>=0.2.0"]
|
dependencies = ["verifiers>=0.4.2.dev11"]
|
||||||
|
|
||||||
[build-system]
|
[build-system]
|
||||||
requires = ["hatchling"]
|
requires = ["hatchling"]
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import string
|
|
||||||
from typing import Any, Callable
|
from typing import Any, Callable
|
||||||
|
|
||||||
from langdetect import DetectorFactory, detect
|
from langdetect import DetectorFactory, detect
|
||||||
|
|||||||
@@ -26,7 +26,9 @@ from __future__ import annotations
|
|||||||
import re
|
import re
|
||||||
|
|
||||||
import verifiers.v1 as vf
|
import verifiers.v1 as vf
|
||||||
|
from nemotron_guard_v1.judges import SDK_TIMEOUT, SDKRetryJudge
|
||||||
from nemotron_guard_v1.text import strip_think_tags
|
from nemotron_guard_v1.text import strip_think_tags
|
||||||
|
from verifiers.v1.configs.client import ClientTimeoutConfig
|
||||||
|
|
||||||
# --- Judge prompt templates (verbatim from v0) -------------------------------
|
# --- Judge prompt templates (verbatim from v0) -------------------------------
|
||||||
|
|
||||||
@@ -137,10 +139,11 @@ class IFJudgeConfig(vf.JudgeConfig):
|
|||||||
model: str = "google/gemma-4-26B-A4B-it"
|
model: str = "google/gemma-4-26B-A4B-it"
|
||||||
base_url: str = "http://localhost:3001/v1"
|
base_url: str = "http://localhost:3001/v1"
|
||||||
api_key_var: str = "VLLM_API_KEY"
|
api_key_var: str = "VLLM_API_KEY"
|
||||||
sampling: vf.JudgeSamplingConfig = vf.JudgeSamplingConfig(temperature=0.0, max_tokens=2048)
|
sampling: vf.SamplingConfig = vf.SamplingConfig(temperature=0.0, max_tokens=2048)
|
||||||
|
timeout: ClientTimeoutConfig = SDK_TIMEOUT
|
||||||
|
|
||||||
|
|
||||||
class YesNoJudge(vf.Judge[str, IFJudgeConfig]):
|
class YesNoJudge(SDKRetryJudge, vf.Judge[str, IFJudgeConfig]):
|
||||||
"""Grades a single YES/NO criterion; the caller supplies the fully-formatted prompt."""
|
"""Grades a single YES/NO criterion; the caller supplies the fully-formatted prompt."""
|
||||||
|
|
||||||
def build_messages(self, *, judge_input: str) -> str:
|
def build_messages(self, *, judge_input: str) -> str:
|
||||||
@@ -150,7 +153,7 @@ class YesNoJudge(vf.Judge[str, IFJudgeConfig]):
|
|||||||
return parse_yes_no(response.text)
|
return parse_yes_no(response.text)
|
||||||
|
|
||||||
|
|
||||||
class CalendarJudge(vf.Judge[int, IFJudgeConfig]):
|
class CalendarJudge(SDKRetryJudge, vf.Judge[int, IFJudgeConfig]):
|
||||||
"""Grades a calendar schedule with a single 0-3 integer score."""
|
"""Grades a calendar schedule with a single 0-3 integer score."""
|
||||||
|
|
||||||
def build_messages(self, *, judge_input: str) -> str:
|
def build_messages(self, *, judge_input: str) -> str:
|
||||||
|
|||||||
@@ -38,11 +38,18 @@ from typing import Any
|
|||||||
from pydantic import model_validator
|
from pydantic import model_validator
|
||||||
|
|
||||||
import verifiers.v1 as vf
|
import verifiers.v1 as vf
|
||||||
from nemotron_guard_v1 import AntiHackingConfig, GuardedTask, SubtaskMix, apply_mix, mix_summary
|
from nemotron_guard_v1 import (
|
||||||
|
AntiHackingConfig,
|
||||||
|
GuardedTask,
|
||||||
|
SubtaskMix,
|
||||||
|
apply_mix,
|
||||||
|
distinct_task_ids,
|
||||||
|
mix_summary,
|
||||||
|
)
|
||||||
from nemotron_guard_v1.text import strip_think_tags
|
from nemotron_guard_v1.text import strip_think_tags
|
||||||
from verifiers.v1.types import content_text
|
from verifiers.v1.types import content_text
|
||||||
|
|
||||||
from nemotron_instruction_following_v1.checkers import CHECKERS, constraint_gradeable
|
from nemotron_instruction_following_v1.checkers import constraint_gradeable
|
||||||
from nemotron_instruction_following_v1.judging import (
|
from nemotron_instruction_following_v1.judging import (
|
||||||
ADVERSARIAL_DEFAULT_TEMPLATE,
|
ADVERSARIAL_DEFAULT_TEMPLATE,
|
||||||
CALENDAR_PROMPT,
|
CALENDAR_PROMPT,
|
||||||
@@ -370,7 +377,6 @@ class NemotronIFConfig(vf.TasksetConfig):
|
|||||||
max_examples: int = -1
|
max_examples: int = -1
|
||||||
"""Per-subtask row cap (`-1` loads every row). prime-rl train/eval are separate blocks."""
|
"""Per-subtask row cap (`-1` loads every row). prime-rl train/eval are separate blocks."""
|
||||||
seed: int = 42
|
seed: int = 42
|
||||||
system_prompt: str | None = None
|
|
||||||
mix: dict[str, SubtaskMix] = {}
|
mix: dict[str, SubtaskMix] = {}
|
||||||
"""Per-subtask blend, keyed by subtask name. Empty means concatenate, so the 11 subtasks
|
"""Per-subtask blend, keyed by subtask name. Empty means concatenate, so the 11 subtasks
|
||||||
are weighted by raw source size rather than by usefulness. Unlike `max_examples` (one cap
|
are weighted by raw source size rather than by usefulness. Unlike `max_examples` (one cap
|
||||||
@@ -438,13 +444,14 @@ class NemotronIFTaskset(vf.Taskset[NemotronIFTask, NemotronIFConfig]):
|
|||||||
tasks = apply_mix(by_subtask, self.config.mix, self.config.seed, self.config.mix_total)
|
tasks = apply_mix(by_subtask, self.config.mix, self.config.seed, self.config.mix_total)
|
||||||
realized = mix_summary(by_subtask, tasks)
|
realized = mix_summary(by_subtask, tasks)
|
||||||
print(f"nemotron-instruction-following blend: {realized} (total {len(tasks)})", flush=True)
|
print(f"nemotron-instruction-following blend: {realized} (total {len(tasks)})", flush=True)
|
||||||
return tasks
|
# The blend repeats rows; verifiers needs each task key (a data hash) unique.
|
||||||
|
return distinct_task_ids(tasks)
|
||||||
|
|
||||||
# -- helpers ---------------------------------------------------------------
|
# -- helpers ---------------------------------------------------------------
|
||||||
|
|
||||||
def _make(self, idx: int, prompt: list[dict[str, str]], **fields: Any) -> NemotronIFTask:
|
def _make(self, idx: int, prompt: list[dict[str, str]], **fields: Any) -> NemotronIFTask:
|
||||||
return NemotronIFTask(
|
return NemotronIFTask(
|
||||||
NemotronIFData(idx=idx, prompt=prompt, system_prompt=self.config.system_prompt, **fields),
|
NemotronIFData(idx=idx, prompt=prompt, system_prompt=self.system_prompt, **fields),
|
||||||
self.config.task,
|
self.config.task,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ description = "Nemotron instruction-following taskset (ifeval + structured + for
|
|||||||
tags = ["nemotron", "instruction-following", "ifeval", "structured-outputs", "llm-judge", "v1"]
|
tags = ["nemotron", "instruction-following", "ifeval", "structured-outputs", "llm-judge", "v1"]
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"verifiers>=0.2.0",
|
"verifiers>=0.4.2.dev11",
|
||||||
"nemotron-guard-v1",
|
"nemotron-guard-v1",
|
||||||
"datasets",
|
"datasets",
|
||||||
"huggingface-hub",
|
"huggingface-hub",
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ returns `None` on no verdict; the task reward maps `None` to 0.0.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import verifiers.v1 as vf
|
import verifiers.v1 as vf
|
||||||
|
from nemotron_guard_v1.judges import SDK_TIMEOUT, SDKRetryJudge
|
||||||
|
from verifiers.v1.configs.client import ClientTimeoutConfig
|
||||||
|
|
||||||
from nemotron_knowledge_v1.answers import parse_equivalence_score
|
from nemotron_knowledge_v1.answers import parse_equivalence_score
|
||||||
|
|
||||||
@@ -37,10 +39,11 @@ class EquivalenceJudgeConfig(vf.JudgeConfig):
|
|||||||
model: str = "google/gemma-4-26B-A4B-it"
|
model: str = "google/gemma-4-26B-A4B-it"
|
||||||
base_url: str = "http://localhost:3001/v1"
|
base_url: str = "http://localhost:3001/v1"
|
||||||
api_key_var: str = "VLLM_API_KEY"
|
api_key_var: str = "VLLM_API_KEY"
|
||||||
sampling: vf.JudgeSamplingConfig = vf.JudgeSamplingConfig(temperature=0.0, max_tokens=2048)
|
sampling: vf.SamplingConfig = vf.SamplingConfig(temperature=0.0, max_tokens=2048)
|
||||||
|
timeout: ClientTimeoutConfig = SDK_TIMEOUT
|
||||||
|
|
||||||
|
|
||||||
class EquivalenceJudge(vf.Judge[float, EquivalenceJudgeConfig]):
|
class EquivalenceJudge(SDKRetryJudge, vf.Judge[float, EquivalenceJudgeConfig]):
|
||||||
prompt = EQUIVALENCE_PROMPT
|
prompt = EQUIVALENCE_PROMPT
|
||||||
|
|
||||||
def parse(self, response: vf.JudgeResponse[float]) -> float | None:
|
def parse(self, response: vf.JudgeResponse[float]) -> float | None:
|
||||||
|
|||||||
@@ -24,7 +24,14 @@ from typing import Any
|
|||||||
import verifiers.v1 as vf
|
import verifiers.v1 as vf
|
||||||
from pydantic import model_validator
|
from pydantic import model_validator
|
||||||
|
|
||||||
from nemotron_guard_v1 import AntiHackingConfig, GuardedTask, SubtaskMix, apply_mix, mix_summary
|
from nemotron_guard_v1 import (
|
||||||
|
AntiHackingConfig,
|
||||||
|
GuardedTask,
|
||||||
|
SubtaskMix,
|
||||||
|
apply_mix,
|
||||||
|
distinct_task_ids,
|
||||||
|
mix_summary,
|
||||||
|
)
|
||||||
from nemotron_guard_v1.text import strip_think_tags
|
from nemotron_guard_v1.text import strip_think_tags
|
||||||
from verifiers.v1.types import content_text
|
from verifiers.v1.types import content_text
|
||||||
|
|
||||||
@@ -227,7 +234,6 @@ class NemotronKnowledgeConfig(vf.TasksetConfig):
|
|||||||
qa_repo: str = "nvidia/Nemotron-RL-QA-Abstention-v1"
|
qa_repo: str = "nvidia/Nemotron-RL-QA-Abstention-v1"
|
||||||
qa_file: str = "data/train.jsonl"
|
qa_file: str = "data/train.jsonl"
|
||||||
seed: int = 42
|
seed: int = 42
|
||||||
system_prompt: str | None = None
|
|
||||||
mix: dict[str, SubtaskMix] = {}
|
mix: dict[str, SubtaskMix] = {}
|
||||||
"""Per-subtask blend, keyed by subtask name. Empty means concatenate — which buries
|
"""Per-subtask blend, keyed by subtask name. Empty means concatenate — which buries
|
||||||
qa_abstention (3.1k rows) under mcqa (617k), leaving it ~0.5% of the mix."""
|
qa_abstention (3.1k rows) under mcqa (617k), leaving it ~0.5% of the mix."""
|
||||||
@@ -254,7 +260,8 @@ class NemotronKnowledgeTaskset(
|
|||||||
tasks = apply_mix(by_subtask, self.config.mix, self.config.seed, self.config.mix_total)
|
tasks = apply_mix(by_subtask, self.config.mix, self.config.seed, self.config.mix_total)
|
||||||
realized = mix_summary(by_subtask, tasks)
|
realized = mix_summary(by_subtask, tasks)
|
||||||
print(f"nemotron-knowledge blend: {realized} (total {len(tasks)})", flush=True)
|
print(f"nemotron-knowledge blend: {realized} (total {len(tasks)})", flush=True)
|
||||||
return tasks
|
# The blend repeats rows; verifiers needs each task key (a data hash) unique.
|
||||||
|
return distinct_task_ids(tasks)
|
||||||
|
|
||||||
def _load_mcqa(self) -> list[NemotronKnowledgeTask]:
|
def _load_mcqa(self) -> list[NemotronKnowledgeTask]:
|
||||||
from datasets import load_dataset
|
from datasets import load_dataset
|
||||||
@@ -279,7 +286,7 @@ class NemotronKnowledgeTaskset(
|
|||||||
NemotronKnowledgeData(
|
NemotronKnowledgeData(
|
||||||
idx=i,
|
idx=i,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
system_prompt=self.config.system_prompt,
|
system_prompt=self.system_prompt,
|
||||||
answer=expected,
|
answer=expected,
|
||||||
subtask="mcqa",
|
subtask="mcqa",
|
||||||
uuid=str(row.get("uuid", "")),
|
uuid=str(row.get("uuid", "")),
|
||||||
@@ -314,7 +321,7 @@ class NemotronKnowledgeTaskset(
|
|||||||
NemotronKnowledgeData(
|
NemotronKnowledgeData(
|
||||||
idx=i,
|
idx=i,
|
||||||
prompt=messages,
|
prompt=messages,
|
||||||
system_prompt=self.config.system_prompt,
|
system_prompt=self.system_prompt,
|
||||||
answer=expected,
|
answer=expected,
|
||||||
subtask="qa_abstention",
|
subtask="qa_abstention",
|
||||||
uuid=str(row.get("uuid") or row.get("id") or ""),
|
uuid=str(row.get("uuid") or row.get("id") or ""),
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ description = "Nemotron knowledge taskset (mcqa + qa_abstention) with the anti-h
|
|||||||
tags = ["nemotron", "knowledge", "mcqa", "qa", "llm-judge", "v1"]
|
tags = ["nemotron", "knowledge", "mcqa", "qa", "llm-judge", "v1"]
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"verifiers>=0.2.0",
|
"verifiers>=0.4.2.dev11",
|
||||||
"nemotron-guard-v1",
|
"nemotron-guard-v1",
|
||||||
"datasets",
|
"datasets",
|
||||||
"huggingface-hub",
|
"huggingface-hub",
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ returns `None` on no verdict; the task reward maps `None` to 0.0.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import verifiers.v1 as vf
|
import verifiers.v1 as vf
|
||||||
|
from nemotron_guard_v1.judges import SDK_TIMEOUT, SDKRetryJudge
|
||||||
|
from verifiers.v1.configs.client import ClientTimeoutConfig
|
||||||
|
|
||||||
from nemotron_reasoning_v1.answers import parse_equivalence_score
|
from nemotron_reasoning_v1.answers import parse_equivalence_score
|
||||||
|
|
||||||
@@ -37,10 +39,11 @@ class EquivalenceJudgeConfig(vf.JudgeConfig):
|
|||||||
model: str = "google/gemma-4-26B-A4B-it"
|
model: str = "google/gemma-4-26B-A4B-it"
|
||||||
base_url: str = "http://localhost:3001/v1"
|
base_url: str = "http://localhost:3001/v1"
|
||||||
api_key_var: str = "VLLM_API_KEY"
|
api_key_var: str = "VLLM_API_KEY"
|
||||||
sampling: vf.JudgeSamplingConfig = vf.JudgeSamplingConfig(temperature=0.0, max_tokens=2048)
|
sampling: vf.SamplingConfig = vf.SamplingConfig(temperature=0.0, max_tokens=2048)
|
||||||
|
timeout: ClientTimeoutConfig = SDK_TIMEOUT
|
||||||
|
|
||||||
|
|
||||||
class EquivalenceJudge(vf.Judge[float, EquivalenceJudgeConfig]):
|
class EquivalenceJudge(SDKRetryJudge, vf.Judge[float, EquivalenceJudgeConfig]):
|
||||||
prompt = EQUIVALENCE_PROMPT
|
prompt = EQUIVALENCE_PROMPT
|
||||||
|
|
||||||
def parse(self, response: vf.JudgeResponse[float]) -> float | None:
|
def parse(self, response: vf.JudgeResponse[float]) -> float | None:
|
||||||
|
|||||||
@@ -31,7 +31,14 @@ import re
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import verifiers.v1 as vf
|
import verifiers.v1 as vf
|
||||||
from nemotron_guard_v1 import AntiHackingConfig, GuardedTask, SubtaskMix, apply_mix, mix_summary
|
from nemotron_guard_v1 import (
|
||||||
|
AntiHackingConfig,
|
||||||
|
GuardedTask,
|
||||||
|
SubtaskMix,
|
||||||
|
apply_mix,
|
||||||
|
distinct_task_ids,
|
||||||
|
mix_summary,
|
||||||
|
)
|
||||||
from nemotron_guard_v1.text import strip_think_tags
|
from nemotron_guard_v1.text import strip_think_tags
|
||||||
from verifiers.v1.types import content_text
|
from verifiers.v1.types import content_text
|
||||||
|
|
||||||
@@ -280,7 +287,6 @@ class NemotronReasoningConfig(vf.TasksetConfig):
|
|||||||
arc_repo: str = "nvidia/Nemotron-RL-ARC-AGI-v1"
|
arc_repo: str = "nvidia/Nemotron-RL-ARC-AGI-v1"
|
||||||
arc_file: str = "data/transductive/train.jsonl"
|
arc_file: str = "data/transductive/train.jsonl"
|
||||||
seed: int = 42
|
seed: int = 42
|
||||||
system_prompt: str | None = None
|
|
||||||
mix: dict[str, SubtaskMix] = {}
|
mix: dict[str, SubtaskMix] = {}
|
||||||
"""Per-subtask blend, keyed by subtask name. Empty means concatenate every row of every
|
"""Per-subtask blend, keyed by subtask name. Empty means concatenate every row of every
|
||||||
subtask, which lets raw source size dictate the mix (science outnumbers math 40:1)."""
|
subtask, which lets raw source size dictate the mix (science outnumbers math 40:1)."""
|
||||||
@@ -333,9 +339,8 @@ class NemotronReasoningTaskset(
|
|||||||
by_subtask[subtask] = list(rows)
|
by_subtask[subtask] = list(rows)
|
||||||
|
|
||||||
tasks = apply_mix(by_subtask, self.config.mix, self.config.seed, self.config.mix_total)
|
tasks = apply_mix(by_subtask, self.config.mix, self.config.seed, self.config.mix_total)
|
||||||
# idx is verifiers' example identity (dedup, grouping, dashboards). Each loader
|
# idx is the task's position in the pool (verifiers reassigns it on iteration too);
|
||||||
# enumerates from 0, so it has to be reassigned across the blend or the subtasks
|
# each loader enumerates from 0, so it is renumbered across the blend.
|
||||||
# collide on it.
|
|
||||||
# Summarize BEFORE rebuilding: mix_summary matches rows by identity, and model_copy
|
# Summarize BEFORE rebuilding: mix_summary matches rows by identity, and model_copy
|
||||||
# produces new objects.
|
# produces new objects.
|
||||||
realized = mix_summary(by_subtask, tasks)
|
realized = mix_summary(by_subtask, tasks)
|
||||||
@@ -344,7 +349,8 @@ class NemotronReasoningTaskset(
|
|||||||
for idx, task in enumerate(tasks)
|
for idx, task in enumerate(tasks)
|
||||||
]
|
]
|
||||||
print(f"nemotron-reasoning blend: {realized} (total {len(tasks)})", flush=True)
|
print(f"nemotron-reasoning blend: {realized} (total {len(tasks)})", flush=True)
|
||||||
return tasks
|
# The blend repeats rows; verifiers needs each task key (a data hash) unique.
|
||||||
|
return distinct_task_ids(tasks)
|
||||||
|
|
||||||
def _jsonl_rows(self, repo: str, filename: str) -> list[dict[str, Any]]:
|
def _jsonl_rows(self, repo: str, filename: str) -> list[dict[str, Any]]:
|
||||||
from huggingface_hub import hf_hub_download
|
from huggingface_hub import hf_hub_download
|
||||||
@@ -367,7 +373,7 @@ class NemotronReasoningTaskset(
|
|||||||
NemotronReasoningData(
|
NemotronReasoningData(
|
||||||
idx=idx,
|
idx=idx,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
system_prompt=self.config.system_prompt,
|
system_prompt=self.system_prompt,
|
||||||
answer=answer,
|
answer=answer,
|
||||||
subtask=subtask,
|
subtask=subtask,
|
||||||
uuid=str(info.get("uuid", "")),
|
uuid=str(info.get("uuid", "")),
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ description = "Nemotron reasoning taskset (reasoning_gym + math + science + arc_
|
|||||||
tags = ["nemotron", "reasoning", "math", "reasoning-gym", "arc-agi", "llm-judge", "v1"]
|
tags = ["nemotron", "reasoning", "math", "reasoning-gym", "arc-agi", "llm-judge", "v1"]
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"verifiers>=0.2.0",
|
"verifiers>=0.4.2.dev11",
|
||||||
"nemotron-guard-v1",
|
"nemotron-guard-v1",
|
||||||
"datasets",
|
"datasets",
|
||||||
"huggingface-hub",
|
"huggingface-hub",
|
||||||
|
|||||||
@@ -14,11 +14,14 @@ id = "nemotron-tool-calling-v1"
|
|||||||
dataset = "all"
|
dataset = "all"
|
||||||
exclude_message_actions = true
|
exclude_message_actions = true
|
||||||
|
|
||||||
[env.agent.harness]
|
[env.agent]
|
||||||
id = "nemotron-tool-calling-v1"
|
harness = { id = "nemotron-tool-calling-v1" }
|
||||||
runtime = { type = "subprocess" }
|
runtime = { type = "subprocess" }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The runtime is set on the agent, not the harness; verifiers' default runtime is a Prime
|
||||||
|
sandbox, which this in-process harness does not need.
|
||||||
|
|
||||||
An unset harness resolves to this package's bundled harness. Do not override it
|
An unset harness resolves to this package's bundled harness. Do not override it
|
||||||
with `null` or use a `max_turns` budget to implement single-action completion.
|
with `null` or use a `max_turns` budget to implement single-action completion.
|
||||||
Normal completion is `agent_completed`; token-budget exhaustion still receives
|
Normal completion is `agent_completed`; token-budget exhaustion still receives
|
||||||
@@ -48,23 +51,20 @@ claims that a tool executed. `tool_call_shape` remains a diagnostic, not reward.
|
|||||||
|
|
||||||
## Trinity parser
|
## Trinity parser
|
||||||
|
|
||||||
Apply `patches/submodules/renderers-hermes-tool-parser.patch` to the runtime's
|
The text-level `hermes` parser comes from the renderers fork in `prime-rl/deps/renderers`
|
||||||
`deps/renderers`, and select `tool_parser = "hermes"`, `reasoning_parser = "think"`
|
(`dphn/renderers@trinity-dsv41`). Select `tool_parser = "hermes"`, `reasoning_parser = "think"`
|
||||||
in the orchestrator renderer. The patch installs `renderers/hermes.py`, registers
|
in the orchestrator renderer.
|
||||||
it, and wires the default renderer's reasoning-prefill detection.
|
|
||||||
|
|
||||||
The parser ignores explicit/prefilled reasoning and Markdown code examples,
|
The parser ignores explicit/prefilled reasoning and Markdown code examples,
|
||||||
requires strict JSON envelopes with object arguments, and preserves text before,
|
requires strict JSON envelopes with object arguments, and preserves text before,
|
||||||
between, and after calls. Parse-error spans refer to the original completion
|
between, and after calls. Parse-error spans refer to the original completion
|
||||||
tokens. Envelopes inside JSON string arguments do not prematurely end a call.
|
tokens. Envelopes inside JSON string arguments do not prematurely end a call.
|
||||||
|
|
||||||
The patch is a full patch against unmodified upstream renderers, **not** an
|
Restart existing environment workers after upgrading so they import the updated package
|
||||||
incremental patch on top of the old Hermes patch. When upgrading an existing
|
and renderer.
|
||||||
deployment, reverse its previous Hermes patch before applying this version;
|
|
||||||
preserve unrelated dependency edits. Restart existing environment workers so
|
|
||||||
they import the updated package and renderer.
|
|
||||||
|
|
||||||
Validated runtime: PRIME-RL `31ff561`, verifiers `b13ba60`, renderers `bdb96b0` + Hermes parser (`dphn/renderers@trinity`).
|
Validated runtime: verifiers `72d08a0b6` (0.4.2.dev) with the renderers in `prime-rl/deps/renderers`.
|
||||||
|
(Previously: PRIME-RL `31ff561`, verifiers `b13ba60`, renderers `bdb96b0` + Hermes parser.)
|
||||||
The native environment is version `0.2.0`; it intentionally changes the old
|
The native environment is version `0.2.0`; it intentionally changes the old
|
||||||
text-fallback reward and unknown-tool-continuation behavior.
|
text-fallback reward and unknown-tool-continuation behavior.
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,10 @@ function_calling, workplace, indirect_prompt_injection) is served by one guarded
|
|||||||
anti-hacking guardrail from `nemotron_guard_v1`.
|
anti-hacking guardrail from `nemotron_guard_v1`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from nemotron_tool_calling_v1.harness import NativeToolCallingHarness
|
from nemotron_tool_calling_v1.harness import (
|
||||||
|
NativeToolCallingHarness,
|
||||||
|
NativeToolCallingHarnessConfig,
|
||||||
|
)
|
||||||
from nemotron_tool_calling_v1.taskset import (
|
from nemotron_tool_calling_v1.taskset import (
|
||||||
NemotronToolCallingConfig,
|
NemotronToolCallingConfig,
|
||||||
NemotronToolCallingData,
|
NemotronToolCallingData,
|
||||||
@@ -17,6 +20,7 @@ from nemotron_tool_calling_v1.taskset import (
|
|||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"NativeToolCallingHarness",
|
"NativeToolCallingHarness",
|
||||||
|
"NativeToolCallingHarnessConfig",
|
||||||
"NemotronToolCallingConfig",
|
"NemotronToolCallingConfig",
|
||||||
"NemotronToolCallingData",
|
"NemotronToolCallingData",
|
||||||
"NemotronToolCallingTask",
|
"NemotronToolCallingTask",
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
"""One native next-action request, captured by verifiers without tool dispatch."""
|
"""One native next-action request, captured by verifiers without tool dispatch."""
|
||||||
|
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
import verifiers.v1 as vf
|
import verifiers.v1 as vf
|
||||||
from openai import AsyncOpenAI
|
from openai import AsyncOpenAI
|
||||||
from verifiers.v1.clients import ModelContext
|
from verifiers.v1.clients import ModelContext
|
||||||
@@ -7,10 +9,17 @@ from verifiers.v1.dialects.chat import message_to_wire
|
|||||||
from verifiers.v1.runtimes import ProgramResult, Runtime
|
from verifiers.v1.runtimes import ProgramResult, Runtime
|
||||||
|
|
||||||
|
|
||||||
class NativeToolCallingHarness(vf.Harness[vf.HarnessConfig]):
|
class NativeToolCallingHarnessConfig(vf.HarnessConfig):
|
||||||
|
dialect: Literal["chat_completions"] = "chat_completions"
|
||||||
|
"""The one request goes out as a chat completion with native `tools`."""
|
||||||
|
|
||||||
|
|
||||||
|
class NativeToolCallingHarness(vf.Harness[NativeToolCallingHarnessConfig]):
|
||||||
APPENDS_SYSTEM_PROMPT = True
|
APPENDS_SYSTEM_PROMPT = True
|
||||||
SUPPORTS_MESSAGE_PROMPT = True
|
|
||||||
EXECUTES_CODE = False
|
EXECUTES_CODE = False
|
||||||
|
# The loop runs in-process and only talks to the interception endpoint, so it runs
|
||||||
|
# on the subprocess runtime like the bundled `null` harness.
|
||||||
|
NEEDS_CONTAINER = False
|
||||||
|
|
||||||
async def launch(
|
async def launch(
|
||||||
self,
|
self,
|
||||||
@@ -20,20 +29,19 @@ class NativeToolCallingHarness(vf.Harness[vf.HarnessConfig]):
|
|||||||
endpoint: str,
|
endpoint: str,
|
||||||
secret: str,
|
secret: str,
|
||||||
mcp_urls: dict[str, str],
|
mcp_urls: dict[str, str],
|
||||||
|
data: vf.TaskData,
|
||||||
) -> ProgramResult:
|
) -> ProgramResult:
|
||||||
if mcp_urls or self.config.disabled_tools:
|
if mcp_urls or self.config.disabled_tools:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"Next-action tasks require the complete recorded tool schema, without MCP dispatch"
|
"Next-action tasks require the complete recorded tool schema, without MCP dispatch"
|
||||||
)
|
)
|
||||||
system, prompt = self.resolve_prompt(trace.task.data)
|
system, prompt = self.resolve_prompt(data)
|
||||||
messages = [{"role": "system", "content": system}] if system else []
|
messages = [{"role": "system", "content": system}] if system else []
|
||||||
if isinstance(prompt, str):
|
if isinstance(prompt, str):
|
||||||
messages.append({"role": "user", "content": prompt})
|
messages.append({"role": "user", "content": prompt})
|
||||||
else:
|
else:
|
||||||
messages.extend(message_to_wire(message) for message in prompt or [])
|
messages.extend(message_to_wire(message) for message in prompt or [])
|
||||||
tools = [
|
tools = [{"type": "function", "function": tool} for tool in data.tool_defs]
|
||||||
{"type": "function", "function": tool} for tool in trace.task.data.tool_defs
|
|
||||||
]
|
|
||||||
if not tools:
|
if not tools:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"Native tool-calling tasks must advertise at least one tool"
|
"Native tool-calling tasks must advertise at least one tool"
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ from nemotron_guard_v1 import (
|
|||||||
GuardedTask,
|
GuardedTask,
|
||||||
SubtaskMix,
|
SubtaskMix,
|
||||||
apply_mix,
|
apply_mix,
|
||||||
|
distinct_task_ids,
|
||||||
mix_summary,
|
mix_summary,
|
||||||
)
|
)
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
@@ -332,7 +333,6 @@ class NemotronToolCallingConfig(vf.TasksetConfig):
|
|||||||
num_examples: int = -1
|
num_examples: int = -1
|
||||||
"""Per-subtask cap; -1 loads all rows."""
|
"""Per-subtask cap; -1 loads all rows."""
|
||||||
seed: int = 42
|
seed: int = 42
|
||||||
system_prompt: str | None = None
|
|
||||||
exclude_message_actions: Literal[True] = True
|
exclude_message_actions: Literal[True] = True
|
||||||
"""This native-call-only taskset excludes message targets; disabling is an error."""
|
"""This native-call-only taskset excludes message targets; disabling is an error."""
|
||||||
max_prompt_chars: int = 0
|
max_prompt_chars: int = 0
|
||||||
@@ -371,7 +371,7 @@ class NemotronToolCallingTaskset(
|
|||||||
built: list[NemotronToolCallingTask] = []
|
built: list[NemotronToolCallingTask] = []
|
||||||
for row in raw:
|
for row in raw:
|
||||||
data = build_row(
|
data = build_row(
|
||||||
row, subtask, self.config.system_prompt, self.config.exclude_message_actions
|
row, subtask, self.system_prompt, self.config.exclude_message_actions
|
||||||
)
|
)
|
||||||
if data is None:
|
if data is None:
|
||||||
continue
|
continue
|
||||||
@@ -384,7 +384,7 @@ class NemotronToolCallingTaskset(
|
|||||||
print(f"nemotron-tool-calling: dropped {dropped} over-length prompts", flush=True)
|
print(f"nemotron-tool-calling: dropped {dropped} over-length prompts", flush=True)
|
||||||
|
|
||||||
tasks = apply_mix(by_subtask, self.config.mix, self.config.seed, self.config.mix_total)
|
tasks = apply_mix(by_subtask, self.config.mix, self.config.seed, self.config.mix_total)
|
||||||
# idx is verifiers' example identity, so it must be assigned after the blend —
|
# idx is the task's position in the pool (verifiers reassigns it on iteration too);
|
||||||
# per-subtask enumeration would collide across subtasks.
|
# per-subtask enumeration would collide across subtasks.
|
||||||
# Summarize BEFORE rebuilding: mix_summary matches rows by identity, and model_copy
|
# Summarize BEFORE rebuilding: mix_summary matches rows by identity, and model_copy
|
||||||
# produces new objects.
|
# produces new objects.
|
||||||
@@ -394,4 +394,5 @@ class NemotronToolCallingTaskset(
|
|||||||
for idx, task in enumerate(tasks)
|
for idx, task in enumerate(tasks)
|
||||||
]
|
]
|
||||||
print(f"nemotron-tool-calling blend: {realized} (total {len(tasks)})", flush=True)
|
print(f"nemotron-tool-calling blend: {realized} (total {len(tasks)})", flush=True)
|
||||||
return tasks
|
# The blend repeats rows; verifiers needs each task key (a data hash) unique.
|
||||||
|
return distinct_task_ids(tasks)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ description = "Nemotron tool-calling taskset (pivot next-action, workplace, prom
|
|||||||
tags = ["nemotron", "tool-calling", "function-calling", "agentic", "v1"]
|
tags = ["nemotron", "tool-calling", "function-calling", "agentic", "v1"]
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"verifiers>=0.2.0",
|
"verifiers>=0.4.2.dev11",
|
||||||
"nemotron-guard-v1",
|
"nemotron-guard-v1",
|
||||||
"datasets",
|
"datasets",
|
||||||
"huggingface-hub",
|
"huggingface-hub",
|
||||||
|
|||||||
@@ -14,10 +14,10 @@ from nemotron_tool_calling_v1.prompt import prepare_prompt
|
|||||||
from nemotron_tool_calling_v1.taskset import build_row
|
from nemotron_tool_calling_v1.taskset import build_row
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
from verifiers.v1 import Agent, AgentConfig
|
from verifiers.v1 import Agent, AgentConfig
|
||||||
from verifiers.v1.clients import EvalClient
|
from verifiers.v1.configs.client import EvalClientConfig, TrainClientConfig
|
||||||
from verifiers.v1.graph import MessageNode
|
from verifiers.v1.graph import MessageNode
|
||||||
from verifiers.v1.loaders import default_harness_id
|
from verifiers.v1.utils.loaders import default_harness_id
|
||||||
from verifiers.v1.trace import Trace, TraceTask
|
from verifiers.v1.trace import AgentInfo, Trace, TraceTask
|
||||||
from verifiers.v1.types import AssistantMessage, ToolCall
|
from verifiers.v1.types import AssistantMessage, ToolCall
|
||||||
|
|
||||||
GOLD = {"type": "function_call", "name": "book_flight", "arguments": {"dest": "Paris"}}
|
GOLD = {"type": "function_call", "name": "book_flight", "arguments": {"dest": "Paris"}}
|
||||||
@@ -52,6 +52,7 @@ def task():
|
|||||||
def trace_for(message):
|
def trace_for(message):
|
||||||
t = task()
|
t = task()
|
||||||
return t, Trace(
|
return t, Trace(
|
||||||
|
agent=AgentInfo(config=AgentConfig()),
|
||||||
task=TraceTask(type=type(t).__name__, data=t.data),
|
task=TraceTask(type=type(t).__name__, data=t.data),
|
||||||
nodes=[MessageNode(parent=None, message=message, sampled=True)],
|
nodes=[MessageNode(parent=None, message=message, sampled=True)],
|
||||||
)
|
)
|
||||||
@@ -174,7 +175,8 @@ def test_native_schema_and_history_are_separate_from_prompt_instructions():
|
|||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"kind,reward", [("native", 1), ("fenced", 0), ("invalid", 0), ("length", 0)]
|
"kind,reward", [("native", 1), ("fenced", 0), ("invalid", 0), ("length", 0)]
|
||||||
)
|
)
|
||||||
async def test_one_action_through_real_interception(kind, reward):
|
async def test_one_action_through_real_interception(kind, reward, monkeypatch):
|
||||||
|
monkeypatch.setenv("NEMOTRON_TC_TEST_KEY", "test-only")
|
||||||
requests = []
|
requests = []
|
||||||
|
|
||||||
async def completion(request):
|
async def completion(request):
|
||||||
@@ -221,18 +223,18 @@ async def test_one_action_through_real_interception(kind, reward):
|
|||||||
runner = web.AppRunner(app)
|
runner = web.AppRunner(app)
|
||||||
await runner.setup()
|
await runner.setup()
|
||||||
await web.TCPSite(runner, "127.0.0.1", 0).start()
|
await web.TCPSite(runner, "127.0.0.1", 0).start()
|
||||||
client = EvalClient(
|
client = EvalClientConfig(
|
||||||
base_url=f"http://127.0.0.1:{runner.addresses[0][1]}/v1", api_key="test-only"
|
base_url=f"http://127.0.0.1:{runner.addresses[0][1]}/v1",
|
||||||
|
api_key_var="NEMOTRON_TC_TEST_KEY",
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
config = AgentConfig(
|
config = AgentConfig(
|
||||||
model="test",
|
model="test",
|
||||||
harness={
|
client=client,
|
||||||
"id": "nemotron-tool-calling-v1",
|
harness={"id": "nemotron-tool-calling-v1"},
|
||||||
"runtime": {"type": "subprocess"},
|
runtime={"type": "subprocess"},
|
||||||
},
|
|
||||||
)
|
)
|
||||||
async with Agent(config, client=client) as agent:
|
async with Agent(config) as agent:
|
||||||
trace = await agent.run(task())
|
trace = await agent.run(task())
|
||||||
assert trace.ok, trace.errors
|
assert trace.ok, trace.errors
|
||||||
assert trace.stop_condition == "agent_completed"
|
assert trace.stop_condition == "agent_completed"
|
||||||
@@ -246,7 +248,6 @@ async def test_one_action_through_real_interception(kind, reward):
|
|||||||
assert not any(node.message.role == "tool" for node in trace.nodes)
|
assert not any(node.message.role == "tool" for node in trace.nodes)
|
||||||
assert "unknown tool" not in trace.model_dump_json()
|
assert "unknown tool" not in trace.model_dump_json()
|
||||||
finally:
|
finally:
|
||||||
await client.close()
|
|
||||||
await runner.cleanup()
|
await runner.cleanup()
|
||||||
|
|
||||||
|
|
||||||
@@ -261,14 +262,16 @@ async def test_one_action_through_real_interception(kind, reward):
|
|||||||
("extra_call", 0),
|
("extra_call", 0),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
async def test_training_client_with_real_tokenizer_and_token_capture(kind, reward):
|
async def test_training_client_with_real_tokenizer_and_token_capture(
|
||||||
|
kind, reward, monkeypatch
|
||||||
|
):
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from huggingface_hub import hf_hub_download
|
from huggingface_hub import hf_hub_download
|
||||||
from openai import AsyncOpenAI
|
|
||||||
from renderers.configs import DefaultRendererConfig
|
from renderers.configs import DefaultRendererConfig
|
||||||
from transformers import AutoTokenizer
|
from transformers import AutoTokenizer
|
||||||
from verifiers.v1.clients import TrainClient
|
|
||||||
|
monkeypatch.setenv("NEMOTRON_TC_TEST_KEY", "test-only")
|
||||||
|
|
||||||
snapshot = str(
|
snapshot = str(
|
||||||
Path(
|
Path(
|
||||||
@@ -317,7 +320,10 @@ async def test_training_client_with_real_tokenizer_and_token_capture(kind, rewar
|
|||||||
"token_ids": completion_ids,
|
"token_ids": completion_ids,
|
||||||
"finish_reason": "stop",
|
"finish_reason": "stop",
|
||||||
"logprobs": {
|
"logprobs": {
|
||||||
"content": [{"logprob": -0.1} for _ in completion_ids]
|
"content": [
|
||||||
|
{"token": f"token_id:{token}", "logprob": -0.1}
|
||||||
|
for token in completion_ids
|
||||||
|
]
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -330,23 +336,20 @@ async def test_training_client_with_real_tokenizer_and_token_capture(kind, rewar
|
|||||||
runner = web.AppRunner(app)
|
runner = web.AppRunner(app)
|
||||||
await runner.setup()
|
await runner.setup()
|
||||||
await web.TCPSite(runner, "127.0.0.1", 0).start()
|
await web.TCPSite(runner, "127.0.0.1", 0).start()
|
||||||
client = TrainClient(
|
client = TrainClientConfig(
|
||||||
AsyncOpenAI(
|
base_url=f"http://127.0.0.1:{runner.addresses[0][1]}/v1",
|
||||||
base_url=f"http://127.0.0.1:{runner.addresses[0][1]}/v1",
|
api_key_var="NEMOTRON_TC_TEST_KEY",
|
||||||
api_key="test-only",
|
renderer=DefaultRendererConfig(tool_parser="hermes", reasoning_parser="think"),
|
||||||
),
|
|
||||||
config=DefaultRendererConfig(tool_parser="hermes", reasoning_parser="think"),
|
|
||||||
renderer_model_name=snapshot,
|
renderer_model_name=snapshot,
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
config = AgentConfig(
|
config = AgentConfig(
|
||||||
model="test",
|
model="test",
|
||||||
harness={
|
client=client,
|
||||||
"id": "nemotron-tool-calling-v1",
|
harness={"id": "nemotron-tool-calling-v1"},
|
||||||
"runtime": {"type": "subprocess"},
|
runtime={"type": "subprocess"},
|
||||||
},
|
|
||||||
)
|
)
|
||||||
async with Agent(config, client=client) as agent:
|
async with Agent(config) as agent:
|
||||||
trace = await agent.run(task())
|
trace = await agent.run(task())
|
||||||
assert trace.ok, trace.errors
|
assert trace.ok, trace.errors
|
||||||
assert trace.num_turns == len(trace.calls) == len(requests) == 1
|
assert trace.num_turns == len(trace.calls) == len(requests) == 1
|
||||||
@@ -358,9 +361,8 @@ async def test_training_client_with_real_tokenizer_and_token_capture(kind, rewar
|
|||||||
assert "available_actions" not in prompt and "```json" not in prompt
|
assert "available_actions" not in prompt and "```json" not in prompt
|
||||||
sampled = [n for n in trace.nodes if n.sampled]
|
sampled = [n for n in trace.nodes if n.sampled]
|
||||||
assert len(sampled) == 1
|
assert len(sampled) == 1
|
||||||
assert sampled[0].token_ids[-len(completion_ids) :] == completion_ids
|
assert sampled[0].token_ids[-len(completion_ids) :].tolist() == completion_ids
|
||||||
assert len(sampled[0].logprobs) == len(completion_ids)
|
assert len(sampled[0].logprobs) == len(completion_ids)
|
||||||
assert not any(n.message.role == "tool" for n in trace.nodes)
|
assert not any(n.message.role == "tool" for n in trace.nodes)
|
||||||
finally:
|
finally:
|
||||||
await client.close()
|
|
||||||
await runner.cleanup()
|
await runner.cleanup()
|
||||||
|
|||||||
+1
-1
Submodule prime-rl updated: 6087c3addb...87afa63d19
@@ -8,7 +8,8 @@ git -C "$ROOT" -c url.https://github.com/.insteadOf=git@github.com: \
|
|||||||
submodule update --init --recursive
|
submodule update --init --recursive
|
||||||
|
|
||||||
cd "$ROOT/prime-rl"
|
cd "$ROOT/prime-rl"
|
||||||
uv sync --frozen --no-dev --package prime-rl --extra flash-attn --extra quack
|
# torch/vLLM moved out of the base dependencies into the `gpu` extra.
|
||||||
|
uv sync --frozen --no-dev --package prime-rl --extra gpu --extra flash-attn --extra quack
|
||||||
python="$(uv run --no-sync python -c 'import sys; print(sys.executable)')"
|
python="$(uv run --no-sync python -c 'import sys; print(sys.executable)')"
|
||||||
|
|
||||||
# Env dependencies missing from PRIME-RL's lock, constrained to the versions it resolved.
|
# Env dependencies missing from PRIME-RL's lock, constrained to the versions it resolved.
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Render configs/rl.toml, check credentials and the judge, then start training.
|
# Render configs/rl.toml, check credentials and the judge, then start training.
|
||||||
# Usage: JUDGE_BASE_URL=http://HOST:PORT/v1 scripts/launch.sh [extra `rl` args, e.g. --dry-run]
|
# Usage: JUDGE_BASE_URL=http://HOST:PORT/v1 scripts/launch.sh [extra `rl` args, e.g. --dry-run]
|
||||||
|
# `rl` starts inference, the trainer, the orchestrator and one env-worker-pool per source.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
[[ -f "$ROOT/.env" ]] && set -a && source "$ROOT/.env" && set +a
|
[[ -f "$ROOT/.env" ]] && set -a && source "$ROOT/.env" && set +a
|
||||||
@@ -8,7 +9,6 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
|||||||
|
|
||||||
# The guard's subtask mixing seeds its shuffles with hash(subtask).
|
# The guard's subtask mixing seeds its shuffles with hash(subtask).
|
||||||
export PYTHONHASHSEED=0
|
export PYTHONHASHSEED=0
|
||||||
export VLLM_ALLOW_RUNTIME_LORA_UPDATING=True
|
|
||||||
|
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
mkdir -p outputs
|
mkdir -p outputs
|
||||||
|
|||||||
+23
-12
@@ -1,5 +1,9 @@
|
|||||||
"""Validate configs/rl.toml and prewarm every train/eval taskset loader, without rollouts.
|
"""Validate configs/rl.toml and prewarm every train/eval taskset loader, without rollouts.
|
||||||
|
|
||||||
|
Loads each source's taskset exactly as the orchestrator does
|
||||||
|
(`vf.load_taskset(env.taskset).select(source.select)`, materialized), and checks the task
|
||||||
|
keys are unique, which the orchestrator's task sampler requires.
|
||||||
|
|
||||||
Usage (from the repo root): uv run --project prime-rl --no-sync python scripts/prepare_data.py
|
Usage (from the repo root): uv run --project prime-rl --no-sync python scripts/prepare_data.py
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -10,9 +14,9 @@ import tempfile
|
|||||||
from collections import Counter
|
from collections import Counter
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
import verifiers.v1 as vf
|
||||||
from prime_rl.configs.rl import RLConfig
|
from prime_rl.configs.rl import RLConfig
|
||||||
from pydantic_config import cli
|
from pydantic_config import cli
|
||||||
from verifiers.v1.loaders import taskset_class
|
|
||||||
|
|
||||||
assert os.environ.get("PYTHONHASHSEED") == "0", "run with PYTHONHASHSEED=0 to match training"
|
assert os.environ.get("PYTHONHASHSEED") == "0", "run with PYTHONHASHSEED=0 to match training"
|
||||||
|
|
||||||
@@ -25,19 +29,26 @@ with tempfile.NamedTemporaryFile("w", suffix=".toml") as rendered:
|
|||||||
|
|
||||||
assert config.deployment.num_train_gpus == 2
|
assert config.deployment.num_train_gpus == 2
|
||||||
assert config.deployment.num_infer_gpus == 6
|
assert config.deployment.num_infer_gpus == 6
|
||||||
assert (config.inference.parallel.tp, config.inference.parallel.dp) == (2, 3)
|
vllm = config.inference.vllm
|
||||||
|
assert (vllm.tensor_parallel_size, vllm.data_parallel_size) == (2, 3)
|
||||||
assert config.trainer.model.optimization_dtype == "float32"
|
assert config.trainer.model.optimization_dtype == "float32"
|
||||||
assert config.trainer.model.reduce_dtype == "float32"
|
assert config.trainer.model.reduce_dtype == "float32"
|
||||||
print("CONFIG_VALID", flush=True)
|
print("CONFIG_VALID", flush=True)
|
||||||
|
|
||||||
for panel, envs in (("train", config.orchestrator.train.env), ("eval", config.orchestrator.eval.env)):
|
for split, source in config.orchestrator.env_sources:
|
||||||
for env in envs:
|
print("LOADING", split, source.resolved_name, flush=True)
|
||||||
print("LOADING", panel, env.name, flush=True)
|
taskset = vf.load_taskset(source.env.taskset).select(source.select)
|
||||||
taskset = taskset_class(env.env.taskset.id)(env.env.taskset)
|
tasks = list(taskset)
|
||||||
tasks = list(taskset.load())
|
assert tasks, (split, source.resolved_name, "empty taskset")
|
||||||
assert tasks, (panel, env.name, "empty taskset")
|
duplicates = [key for key, count in Counter(task.key for task in tasks).items() if count > 1]
|
||||||
subtasks = Counter(getattr(task.data, "subtask", "decensor") for task in tasks)
|
assert not duplicates, (split, source.resolved_name, f"{len(duplicates)} duplicate task keys")
|
||||||
print(json.dumps({"panel": panel, "environment": env.name, "rows": len(tasks), "subtasks": dict(subtasks)}), flush=True)
|
subtasks = Counter(getattr(task.data, "subtask", "decensor") for task in tasks)
|
||||||
del tasks, taskset
|
print(
|
||||||
gc.collect()
|
json.dumps(
|
||||||
|
{"split": split, "environment": source.resolved_name, "rows": len(tasks), "subtasks": dict(subtasks)}
|
||||||
|
),
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
del tasks, taskset
|
||||||
|
gc.collect()
|
||||||
print("DATA_READY", flush=True)
|
print("DATA_READY", flush=True)
|
||||||
|
|||||||
Reference in New Issue
Block a user