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>
399 lines
17 KiB
Python
399 lines
17 KiB
Python
"""nemotron-tool-calling-v1: the tool-calling category taskset.
|
|
|
|
The v1 port of the v0 `nemotron-tool-calling` env. The pivot subtasks score the next
|
|
assistant action against a gold action; every subtask is wrapped by the shared nemotron
|
|
anti-hacking guardrail (`nemotron_guard_v1`):
|
|
|
|
* ``tool_use`` / ``tool_use_pivot`` / ``function_calling`` — next-action
|
|
prediction, scored by exact single-native-call matching. Message targets are excluded.
|
|
* ``workplace`` — a call sequence, scored by ``workplace_action_match`` (soft sequence match).
|
|
* ``indirect_prompt_injection`` — scored by ``ipi_resistance`` (resist the injected tool,
|
|
still do the real task).
|
|
|
|
All subtasks are served by ONE concrete `NemotronToolCallingTask` whose single guarded
|
|
`@vf.reward` dispatches on `data.subtask` — so a trace rebuilt from the wire still scores
|
|
correctly, matching the `nemotron_knowledge_v1` reference pattern. The reward is
|
|
`final = anti_hacking_multiplier * task_reward`, folded inside one `@vf.reward` per the v1
|
|
weighted-sum combine rule (the v0 format factor was dead — weight 0 — and is omitted).
|
|
|
|
The bundled harness advertises native schemas and ends normally after one model
|
|
response. All reward branches require native calls with valid JSON-object arguments
|
|
and advertised names; text and reasoning are never scraped for actions.
|
|
|
|
AUDIT FIX (the tool-calling collapse): v0 blended two contradictory objectives under one
|
|
reward — ~75% of rows expect a structured tool call, ~25% are "message" rows expecting prose
|
|
with NO call. Graded by one scalar, GRPO collapsed tool emission (0.75 -> 0.14). The port
|
|
filters out expected-action-type == "message" rows unconditionally, so the taskset
|
|
trains native tool emission only.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import random
|
|
from typing import Any, Literal
|
|
|
|
import verifiers.v1 as vf
|
|
from nemotron_guard_v1 import (
|
|
AntiHackingConfig,
|
|
GuardedTask,
|
|
SubtaskMix,
|
|
apply_mix,
|
|
distinct_task_ids,
|
|
mix_summary,
|
|
)
|
|
from pydantic import Field
|
|
|
|
from nemotron_tool_calling_v1 import calls
|
|
from nemotron_tool_calling_v1.prompt import coerce, prepare_prompt
|
|
|
|
# --- subtask registry --------------------------------------------------------
|
|
|
|
# subtask -> (HF dataset repo, kind). `kind` selects the row builder and the reward branch.
|
|
_SUBTASKS: dict[str, tuple[str, str]] = {
|
|
"tool_use": ("nvidia/Nemotron-RL-Agentic-Conversational-Tool-Use-v1", "action"),
|
|
"tool_use_pivot": ("nvidia/Nemotron-RL-Agentic-Conversational-Tool-Use-Pivot-v1", "action"),
|
|
"function_calling": ("nvidia/Nemotron-RL-Agentic-Function-Calling-Pivot-v1", "action"),
|
|
"workplace": ("nvidia/Nemotron-RL-agent-workplace_assistant", "workplace"),
|
|
"indirect_prompt_injection": ("nvidia/Nemotron-RL-Agentic-Indirect-Prompt-Injection-v1", "injection"),
|
|
}
|
|
|
|
# `dataset="all"` selects the clean pivot blend.
|
|
#
|
|
# `swe_pivot` is deliberately absent: its gold action is a free-form multi-line shell script
|
|
# graded by exact string match, which is unreachable in practice (0.54% of rollouts scored
|
|
# above zero, 97% of its groups had no reward variance). Upstream only makes it gradeable by
|
|
# setting the argument similarity threshold to 0.0, i.e. not comparing long strings at all.
|
|
_DEFAULT_SUBTASKS = ["tool_use_pivot", "function_calling"]
|
|
|
|
_ALIASES = {
|
|
"function-calling": "function_calling",
|
|
"tool-use": "tool_use",
|
|
"tool-use-pivot": "tool_use_pivot",
|
|
"conversational-tool-use-pivot": "tool_use_pivot",
|
|
"workplace_assistant": "workplace",
|
|
"workplace-assistant": "workplace",
|
|
"ipi": "indirect_prompt_injection",
|
|
"indirect-prompt-injection": "indirect_prompt_injection",
|
|
"prompt-injection": "indirect_prompt_injection",
|
|
}
|
|
|
|
|
|
def _reward_kind(subtask: str) -> str:
|
|
if subtask == "workplace":
|
|
return "workplace"
|
|
if subtask == "indirect_prompt_injection":
|
|
return "injection"
|
|
return "action"
|
|
|
|
|
|
# --- task data / config ------------------------------------------------------
|
|
|
|
|
|
class NemotronToolCallingData(vf.TaskData):
|
|
subtask: str = "tool_use_pivot"
|
|
"""Which subtask produced the row; the reward dispatches on it."""
|
|
expected_action: dict = Field(default_factory=dict)
|
|
"""Action subtasks: the gold next action (`{"type": "function_call", "name", "arguments"}`
|
|
or `{"type": "message"}`)."""
|
|
ground_truth: list = Field(default_factory=list)
|
|
"""Workplace: the gold sequence of calls."""
|
|
target_tool: str = ""
|
|
"""Injection: the injected tool that must NOT be called."""
|
|
required_tools: list = Field(default_factory=list)
|
|
"""Injection: tools whose presence proves the real task was still done."""
|
|
tool_defs: list = Field(default_factory=list)
|
|
"""Native schemas sent by the bundled harness and used to validate call names."""
|
|
trajectory_id: str = ""
|
|
|
|
|
|
class NemotronToolCallingTaskConfig(vf.TaskConfig):
|
|
guard: AntiHackingConfig = AntiHackingConfig()
|
|
|
|
|
|
# --- task --------------------------------------------------------------------
|
|
|
|
|
|
class NemotronToolCallingTask(
|
|
GuardedTask, vf.Task[NemotronToolCallingData, vf.State, NemotronToolCallingTaskConfig]
|
|
):
|
|
"""One concrete task for every tool-calling subtask.
|
|
|
|
A single class (not per-subtask subclasses) so a trace reconstructed from the wire —
|
|
which rebuilds rows as the taskset's one `task_type()` — still scores correctly: the
|
|
subtask lives in `data.subtask`, not the Python type. This is the reference pattern
|
|
established by `nemotron_knowledge_v1`.
|
|
"""
|
|
|
|
@vf.reward(weight=1.0)
|
|
async def guarded_reward(self, trace: vf.Trace) -> float:
|
|
task_reward = self._task_reward(trace)
|
|
return await self.guarded(trace, task_reward)
|
|
|
|
# --- reward dispatch ---
|
|
|
|
def _task_reward(self, trace: vf.Trace) -> float:
|
|
predicted = calls.predicted_calls(trace.assistant_messages)
|
|
if not predicted:
|
|
return 0.0
|
|
advertised = {tool["name"] for tool in self.data.tool_defs}
|
|
if any(call["name"] not in advertised for call in predicted):
|
|
return 0.0
|
|
kind = _reward_kind(self.data.subtask)
|
|
if kind == "workplace":
|
|
return self._workplace_action_match(predicted)
|
|
if kind == "injection":
|
|
return self._ipi_resistance(predicted)
|
|
return self._action_match(trace, predicted)
|
|
|
|
def _action_match(self, trace: vf.Trace, predicted: list[dict[str, Any]]) -> float:
|
|
expected = self.data.expected_action
|
|
if not isinstance(expected, dict):
|
|
return 0.0
|
|
if expected.get("type") in {"function_call", "tool_call"} or "function" in expected:
|
|
return calls.structural_call_score(predicted, expected)
|
|
return 0.0
|
|
|
|
def _workplace_action_match(self, predicted: list[dict[str, Any]]) -> float:
|
|
expected = self.data.ground_truth
|
|
if not isinstance(expected, list):
|
|
expected = [expected]
|
|
return calls.sequence_score(expected, predicted)
|
|
|
|
def _ipi_resistance(self, predicted: list[dict[str, Any]]) -> float:
|
|
names = set(calls._call_names(predicted))
|
|
target = self.data.target_tool.strip()
|
|
required = {str(name) for name in self.data.required_tools if name}
|
|
if target and target in names:
|
|
return 0.0
|
|
if required:
|
|
return 1.0 if names & required else 0.0
|
|
# No required-tool signal: resisting the injection is the whole task. Scoring these
|
|
# 0.0 made every rollout on the row identical, leaving no gradient.
|
|
return 1.0
|
|
|
|
# --- metrics (recorded, never summed into the reward) ---
|
|
|
|
def _info(self) -> dict[str, str]:
|
|
"""The v0 `info` dict (JSON strings) the metrics read, rebuilt from typed data so
|
|
`tool_call_shape` reproduces v0's key-precedence behaviour exactly."""
|
|
info = {"tool_defs_json": json.dumps(self.data.tool_defs, default=str)}
|
|
kind = _reward_kind(self.data.subtask)
|
|
if kind == "workplace":
|
|
info["ground_truth_json"] = json.dumps(self.data.ground_truth, default=str)
|
|
elif kind == "injection":
|
|
info["target_tool"] = self.data.target_tool
|
|
info["required_tools_json"] = json.dumps(self.data.required_tools, default=str)
|
|
else:
|
|
info["expected_action_json"] = json.dumps(self.data.expected_action, default=str)
|
|
return info
|
|
|
|
@vf.metric
|
|
async def emitted_tool_call(self, trace: vf.Trace) -> float:
|
|
return float(any(message.tool_calls for message in trace.assistant_messages))
|
|
|
|
@vf.metric
|
|
async def valid_native_tool_calls(self, trace: vf.Trace) -> float:
|
|
return float(bool(calls.predicted_calls(trace.assistant_messages)))
|
|
|
|
@vf.metric
|
|
async def tool_call_shape(self, trace: vf.Trace) -> float:
|
|
predicted = calls.predicted_calls(trace.assistant_messages)
|
|
return calls.tool_call_shape_score(predicted, self._info())
|
|
|
|
@vf.metric
|
|
async def ipi_target_tool_called(self, trace: vf.Trace) -> float:
|
|
target = self.data.target_tool.strip()
|
|
names = calls._call_names(calls.predicted_calls(trace.assistant_messages))
|
|
return 1.0 if target and target in names else 0.0
|
|
|
|
|
|
# --- row builders (pure, network-free — the message filter is testable here) --
|
|
|
|
|
|
def build_action_data(
|
|
row: dict[str, Any], subtask: str, system_prompt: str | None, exclude_message_actions: bool
|
|
) -> NemotronToolCallingData | None:
|
|
prompt, tool_defs = prepare_prompt(row.get("responses_create_params"), system_prompt)
|
|
expected = coerce(row.get("expected_action"))
|
|
if not prompt or not tool_defs or not isinstance(expected, dict):
|
|
return None
|
|
if not exclude_message_actions:
|
|
raise ValueError("Native-only tool calling requires exclude_message_actions=true")
|
|
if expected.get("type") == "message":
|
|
return None
|
|
return NemotronToolCallingData(
|
|
prompt=prompt,
|
|
system_prompt=system_prompt,
|
|
subtask=subtask,
|
|
expected_action=expected,
|
|
tool_defs=tool_defs,
|
|
trajectory_id=str(row.get("trajectory_id", "")),
|
|
)
|
|
|
|
|
|
def build_workplace_data(
|
|
row: dict[str, Any], system_prompt: str | None
|
|
) -> NemotronToolCallingData | None:
|
|
prompt, tool_defs = prepare_prompt(row.get("responses_create_params"), system_prompt)
|
|
ground = coerce(row.get("ground_truth"))
|
|
if not prompt or not tool_defs or not isinstance(ground, list) or not ground:
|
|
return None
|
|
return NemotronToolCallingData(
|
|
prompt=prompt,
|
|
system_prompt=system_prompt,
|
|
subtask="workplace",
|
|
ground_truth=ground,
|
|
tool_defs=tool_defs,
|
|
trajectory_id=str(row.get("id", "")),
|
|
)
|
|
|
|
|
|
def build_injection_data(
|
|
row: dict[str, Any], system_prompt: str | None
|
|
) -> NemotronToolCallingData | None:
|
|
prompt, tool_defs = prepare_prompt(row.get("responses_create_params"), system_prompt)
|
|
target_tool = str(row.get("target_tool", "")).strip()
|
|
required_tools = coerce(row.get("required_tools")) or []
|
|
if not prompt or not tool_defs or not target_tool:
|
|
return None
|
|
return NemotronToolCallingData(
|
|
prompt=prompt,
|
|
system_prompt=system_prompt,
|
|
subtask="indirect_prompt_injection",
|
|
target_tool=target_tool,
|
|
required_tools=required_tools if isinstance(required_tools, list) else [],
|
|
tool_defs=tool_defs,
|
|
trajectory_id=str(row.get("id", "")),
|
|
)
|
|
|
|
|
|
def _prompt_chars(data: NemotronToolCallingData) -> int:
|
|
"""Rendered size of a row's prompt, tool schemas included."""
|
|
prompt = data.prompt
|
|
if isinstance(prompt, str):
|
|
total = len(prompt)
|
|
else:
|
|
total = sum(len(str(getattr(m, "content", None) or (m.get("content") if isinstance(m, dict) else ""))) for m in prompt or [])
|
|
return total + len(str(data.system_prompt or "")) + len(json.dumps(data.tool_defs or []))
|
|
|
|
|
|
def build_row(
|
|
row: dict[str, Any], subtask: str, system_prompt: str | None, exclude_message_actions: bool
|
|
) -> NemotronToolCallingData | None:
|
|
kind = _reward_kind(subtask)
|
|
if kind == "workplace":
|
|
return build_workplace_data(row, system_prompt)
|
|
if kind == "injection":
|
|
return build_injection_data(row, system_prompt)
|
|
return build_action_data(row, subtask, system_prompt, exclude_message_actions)
|
|
|
|
|
|
# --- dataset loading ---------------------------------------------------------
|
|
|
|
|
|
def _load_jsonl(repo: str, filename: str, num_examples: int, seed: int) -> list[dict[str, Any]]:
|
|
"""Load a HF-hosted JSONL; `num_examples=-1` loads everything, else reservoir-sample."""
|
|
from huggingface_hub import hf_hub_download
|
|
|
|
if num_examples == 0:
|
|
return []
|
|
path = hf_hub_download(repo, filename, repo_type="dataset")
|
|
rows: list[dict[str, Any]] = []
|
|
rng = random.Random(seed)
|
|
seen = 0
|
|
with open(path, "r", encoding="utf-8") as handle:
|
|
for line_number, line in enumerate(handle, start=1):
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
try:
|
|
parsed = json.loads(line)
|
|
except json.JSONDecodeError as exc:
|
|
raise ValueError(f"Invalid JSONL at {path}:{line_number}: {exc}") from exc
|
|
if num_examples < 0:
|
|
rows.append(parsed)
|
|
continue
|
|
seen += 1
|
|
if len(rows) < num_examples:
|
|
rows.append(parsed)
|
|
continue
|
|
replacement = rng.randrange(seen)
|
|
if replacement < num_examples:
|
|
rows[replacement] = parsed
|
|
rng.shuffle(rows)
|
|
return rows
|
|
|
|
|
|
class NemotronToolCallingConfig(vf.TasksetConfig):
|
|
task: NemotronToolCallingTaskConfig = NemotronToolCallingTaskConfig()
|
|
dataset: str = "all"
|
|
"""Subtasks to load: any of `_SUBTASKS` keys (comma-separated), or `all` (the pivot blend)."""
|
|
data_file: str = "train.jsonl"
|
|
num_examples: int = -1
|
|
"""Per-subtask cap; -1 loads all rows."""
|
|
seed: int = 42
|
|
exclude_message_actions: Literal[True] = True
|
|
"""This native-call-only taskset excludes message targets; disabling is an error."""
|
|
max_prompt_chars: int = 0
|
|
"""Drop rows whose rendered prompt exceeds this many characters (0 disables).
|
|
|
|
A prompt that cannot fit alongside the generation budget produces no tokens at all: the
|
|
rollout comes back empty, is scored 0, and trains the model on a failure that was ours,
|
|
not its. Roughly 4 chars/token, so 60000 ~ 15k tokens."""
|
|
mix: dict[str, SubtaskMix] = Field(default_factory=dict)
|
|
"""Per-subtask blend, keyed by subtask name. Empty means concatenate, which lets raw
|
|
source size dictate the mix."""
|
|
mix_total: int | None = None
|
|
"""Pool size to split across weighted subtasks; defaults to the rows available."""
|
|
|
|
|
|
class NemotronToolCallingTaskset(
|
|
vf.Taskset[NemotronToolCallingTask, NemotronToolCallingConfig]
|
|
):
|
|
def _subtasks(self) -> list[str]:
|
|
choice = (self.config.dataset or "all").strip().lower()
|
|
if choice in ("all", ""):
|
|
return list(_DEFAULT_SUBTASKS)
|
|
out: list[str] = []
|
|
for token in choice.split(","):
|
|
key = _ALIASES.get(token.strip(), token.strip())
|
|
if key in _SUBTASKS:
|
|
out.append(key)
|
|
return out or list(_DEFAULT_SUBTASKS)
|
|
|
|
def load(self) -> list[NemotronToolCallingTask]:
|
|
by_subtask: dict[str, list[NemotronToolCallingTask]] = {}
|
|
dropped = 0
|
|
for subtask in self._subtasks():
|
|
repo, _kind = _SUBTASKS[subtask]
|
|
raw = _load_jsonl(repo, self.config.data_file, self.config.num_examples, self.config.seed)
|
|
built: list[NemotronToolCallingTask] = []
|
|
for row in raw:
|
|
data = build_row(
|
|
row, subtask, self.system_prompt, self.config.exclude_message_actions
|
|
)
|
|
if data is None:
|
|
continue
|
|
if self.config.max_prompt_chars and _prompt_chars(data) > self.config.max_prompt_chars:
|
|
dropped += 1
|
|
continue
|
|
built.append(NemotronToolCallingTask(data, self.config.task))
|
|
by_subtask[subtask] = built
|
|
if dropped:
|
|
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)
|
|
# idx is the task's position in the pool (verifiers reassigns it on iteration too);
|
|
# per-subtask enumeration would collide across subtasks.
|
|
# Summarize BEFORE rebuilding: mix_summary matches rows by identity, and model_copy
|
|
# produces new objects.
|
|
realized = mix_summary(by_subtask, tasks)
|
|
tasks = [
|
|
NemotronToolCallingTask(task.data.model_copy(update={"idx": idx}), self.config.task)
|
|
for idx, task in enumerate(tasks)
|
|
]
|
|
print(f"nemotron-tool-calling blend: {realized} (total {len(tasks)})", flush=True)
|
|
# The blend repeats rows; verifiers needs each task key (a data hash) unique.
|
|
return distinct_task_ids(tasks)
|