Agentic RL Training with VERL — A Hands-On Tutorial
34 min read
This tutorial walks you through the agentic training pipeline provided by VERL (the code you pasted). We’ll go end-to-end: what each component does, how data flows, how to plug in tools and interactions, how to configure multi-workflow training, and how to run/scale it efficiently on a single 8-GPU node.
Audience: you already know PPO/GRPO and want to train an agent that can use tools (search, code, browsing…) with an OpenAI-compatible local model server (e.g., vLLM).
Goal: run multi-turn rollouts, compute rewards (optionally LLM-as-judge), and update the policy.
0) What You’ll Build
A tool-using agent that performs multi-turn dialog:
Model turn(s): LLM generates tokens (count toward policy loss).
Tool/user turns: environment responses (masked out of policy loss).
A set of tools (e.g., web_search, fetch_page, summarize).
(Optional) interactions (scripted user/human-in-the-loop) that inject user messages between assistant turns.
Hydra YAML configs that wire tools/interactions to the agent loop.
Training data (chat style) that chooses which agent loop to use per sample.
Trainer that launches rollout servers, runs the loop, computes reward, pads/packs tensors, and optimizes.
1) The Big Picture (Architecture)
Rollout → Reward → Pack → Train:
Dataset sample
└─> AgentLoop (e.g., ToolAgentLoop)
├─ tokenize/templating (tokenizer or processor)
├─ LLM call via AsyncLLMServerManager (sticky session -> KV cache)
├─ parse tool calls -> execute tools -> append tool/user messages
├─ repeat until limits/termination
└─ return AgentLoopOutput (prompt_ids, response_ids, response_mask, logprobs,...)
AgentLoopWorker
├─ pad/pack to fixed shapes (prompts left-padded, responses right-padded)
├─ compute position_ids & attention_mask (+ multimodal if needed)
├─ (async) reward via RewardManagerWorker (micro-batched by BatchExecutor)
└─ return a batched DataProto
Trainer (PPO/GRPO)
└─ consumes DataProto -> policy update (loss only on response_mask==1)
Key parts from the code:
AsyncLLMServerManager: least-requests load balancer + sticky sessions on top of multiple OpenAI-compatible LLM servers (Ray actors).
ToolAgentLoop: the multi-turn workflow—builds prompts with tool schemas, calls the LLM, parses tool calls, executes tools, manages optional interactions, maintains response_mask (1 for LLM tokens, 0 for tool/user).
AgentLoopWorker/Manager: orchestrates per-sample loop, packs tensors, and aggregates batches.
2) Environment Setup
# Core deps (example; match your CUDA/PyTorch)pip install -U torch ray hydra-core transformers accelerate cachetools pydantic tensordict# VERL (install your local repo or the official one)pip install "verl @ git+https://github.com/Bytedance/VERL.git"# OpenAI-compatible inference server (e.g., vLLM)pip install -U vllm# If you use multimodal tools/imagespip install -U pillow
Run a local OpenAI-compatible server (example: Qwen 7B instruct):
How it’s used: ToolAgentLoop.init_class(...) loads this file and registers tool instances; it builds tool schemas passed into tokenizer.apply_chat_template(..., tools=schemas) so the model “knows” callable functions.
5) (Optional) Define Interactions
An interaction is an optional “user provider” that injects user messages between assistant turns.
Global: set actor_rollout_ref.rollout.multi_turn.interaction_config_path to this YAML.
Per-sample: choose one by name in extra_info.interaction_kwargs.
6) Dataset Format (per-sample control)
Provide raw chat, pick agent, optionally choose an interaction:
{ "agent_name": "tool_agent", // or custom "tool_agent_research" etc. "raw_prompt": [ {"role": "system", "content": "You are a meticulous deep-research agent."}, {"role": "user", "content": "Summarize X with citations and dates."} ], "extra_info": { "interaction_kwargs": { "name": "scripted_user", "max_rounds": 2 } }, "tools_kwargs": { // optional, per-tool create/exec kwargs "web_search": { "create_kwargs": {"market": "us"} } }}
Important: data.return_raw_chat must be true so the agent loop sees raw_prompt.
7) Hydra Config — Key Bits
Single-file sketch:
# train_agent.yamltrainer: project_name: agent-training experiment_name: qwen7b_tools nnodes: 1 n_gpus_per_node: 8actor_rollout_ref: model: path: Qwen/Qwen2.5-7B-Instruct # custom_chat_template: | # optional rollout: name: vllm_openai # rollout backend that talks to an OpenAI-compatible server prompt_length: 4096 response_length: 1024 free_cache_engine: false # keep servers warm agent: num_workers: 8 # rollout concurrency (raise until trainer is saturated) multi_turn: format: "openai" # ToolParser format max_user_turns: 6 max_assistant_turns: 6 max_parallel_calls: 2 max_tool_response_length: 2000 tool_response_truncate_side: right tool_config_path: research_agent/configs/tools.yaml interaction_config_path: research_agent/configs/interactions.yaml # optionalreward_model: enable: true enable_resource_pool: false reward_kwargs: rubric: "research_rubrics/coverage_citations_v1.yaml"data: train_files: /path/to/train.jsonl val_files: /path/to/val.jsonl return_raw_chat: true apply_chat_template_kwargs: {} # pass-through to tokenizer/processor if needed
For multiple workflows, either (A) register multiple agent loops (one per workflow, each with its own tool_config_path) and set agent_name per sample, or (B) implement a router loop that gates tools by task.
8) Run Training
Basic PPO/GRPO launch (adapt flags to your repo entrypoint):
Keep reward models off training GPUs; use the built-in BatchExecutor to micro-batch reward evaluation.
If VLM: keep servers persistent; use sleep/wake to free cache without teardown.
10) Extending to Multiple Workflows
Option 1 (recommended): separate agent loops
@register("tool_agent_research")class ResearchAgentLoop(ToolAgentLoop): pass # point to research tools.yaml@register("tool_agent_coding")class CodingAgentLoop(ToolAgentLoop): pass # point to coding tools.yaml
Option 2: a RouterAgentLoop that reads a "task" tag and filters tools per sample.
Option 3: a single loop with a big tool palette; filter allowed tools via tools_kwargs per sample.
11) Debugging & Gotchas
No tool calls detected? Ensure your model emits the expected ToolParser format (e.g., OpenAI function-call JSON). Adjust multi_turn.format or your prompt template.
Logprobs missing? Enable logprobs in sampling params (the code already forwards calculate_log_probs if configured).
Video from tools: currently not supported (intentional error); images OK with a VLM processor.
Masking: only response_mask==1 gets policy loss. Double-check turns marked as tool/user.
Padding: prompts left-padded, responses right-padded—don’t double-pad in your custom code.
Reward placement: sequence-level reward placed on last response token—fine for PPO with sequence rewards. Token-level rewards would require a custom mapper.
{"agent_name":"tool_agent","raw_prompt":[ {"role":"system","content":"You are a research agent."}, {"role":"user","content":"Find three reliable sources on topic X with dates."}],"extra_info":{"interaction_kwargs":{"name":"scripted_user","max_rounds":1}}}
Local OpenAI-compatible server (vLLM) up for your model.
Tools implemented and registered via YAML.
(Optional) Interactions implemented and registered via YAML.
Dataset rows include agent_name and raw_prompt (and interaction kwargs if used).
data.return_raw_chat=true.
Rollout and trainer resource split selected (steady, LoRA, elastic, or phased).
Rollout concurrency (num_workers) high enough to keep trainers busy.
PPO uses multiple minibatches per batch; reward eval micro-batched.
About Reward & Trajectories of Agent Workflows
What a “trajectory” is here
A trajectory = one full agent rollout for a single dataset sample: the model’s turns plus any tool and/or interaction (user) turns, until a stop condition (length/turn caps or an explicit termination).
In AgentLoopWorker._run_agent_loop(...), the agent loop returns an AgentLoopOutput consisting of:
prompt_ids (everything up to first assistant tokens),
response_ids (the full generated tail, including tool/user insertions),
response_mask (1 for LLM-generated tokens, 0 for tool/user tokens and padding),
optional response_logprobs, multimodal fields, and per-turn extras (see below).
The helper get_trajectory_info(...) tracks multiple rollouts per the same dataset index using rollout_n (if consecutive items share the same index, they’re considered multiple trajectories of that same sample). So yes: one workflow can produce multiple trajectories (e.g., repeated rollouts / multiple candidates) in a single training step.
Rewards that exist today (out of the box)
1) Sequence-level “final” reward (the one used for policy updates)
If your agent loop did not set reward_score, the worker computes it asynchronously via the RewardManagerWorker:
It builds a DataProto that contains the final packed tensors (input_ids, attention_mask, position_ids, etc.) plus some non-tensor metadata.
RewardManagerWorker.compute_score(...) calls your configured reward_manager(...) (blocking, often LLM-as-judge or heuristics), then reduces its output to a scalar:
and also returns a dict of reward_extra_info for logging.
In _postprocess(...), that scalar is written into a tensor named rm_scores with the same shape as response_mask, but only the last non-pad response token gets the value (everything else is zero). This is a standard “sequence-level reward placed at the end” convention that many PPO/GRPO implementations use.
TL;DR: By default you get one scalar reward per trajectory, recorded at the last valid response position.
2) Per-turn/process rewards (available as metadata)
Inside ToolAgentLoop:
Every tool call can return a numeric tool reward; these are appended to agent_data.tool_rewards.
An interaction can optionally return a per-turn reward; these go to agent_data.turn_scores.
Both arrays are returned in AgentLoopOutput.extra_fields so you can log them or aggregate them later—but the stock trainer only consumes the final scalar produced by the RewardManagerWorker, not these per-turn lists.
Can I have multiple rewards per trajectory?
Yes—conceptually and in code:
You already have multiple components:
tool-level rewards (tool_rewards list),
interaction-level rewards (turn_scores list),
a judge/heuristic final reward from reward_manager.
How they affect training depends on what your reward_manager(...) returns:
Current default behavior: it returns a vectorreward_tensor (often per-token or per-segment) that the wrapper sums to a scalar. You can change this reduction.
If you want token-level rewards (or per-segment shaping), you can:
Modify RewardManagerWorker.compute_score(...) to not sum; instead return a 1D vector whose length matches the response length.
In _postprocess(...), populate rm_scores across the whole response (e.g., align to response_mask==1 positions) instead of placing a single non-zero at the end.
In other words: the framework already carries the right tensors and masks. The only missing piece for dense rewards is a small change in two places:
don’t reduce to a scalar in RewardManagerWorker,
and fill rm_scores at the positions you want (not only the last token).
Can I have multiple trajectories in one workflow?
Yes. Two ways:
At the data level: feed repeated rows with the same index; get_trajectory_info(...) sets rollout_n for you.
At the loop level: your agent can internally chain multiple tasks/branches before termination (still one “trajectory”), or you can call the loop multiple times per sample if your outer driver wants that.
Either way, each trajectory yields its ownrm_scores (and its own DataProto slice in the batch).
Practical recipes
Recipe A — Keep the default (simple, robust)
Let reward_manager(...) compute any rubric you like.
Keep the sum → scalar reduction.
Use that scalar as the sequence reward (placed at the last token).
Recipe B — Combine multiple signals into one scalar
In reward_manager(...), read tool_rewards + turn_scores from non_tensor_batch.
Compute final = α·judge + β·mean(tool_rewards) + γ·sum(turn_scores) (or anything you prefer).
Return reward_tensor = torch.tensor([final]) so the wrapper still sums to the same scalar.
Recipe C — Token-level reward shaping (requires tiny code change)
Return a vector reward_tensor shaped to the response length (zeros where response_mask==0).
Remove the .sum(...).item() reduction in RewardManagerWorker.compute_score.
In _postprocess(...), set rm_scores = reward_vector aligned to response positions (respect response_mask so tool/user tokens remain zero).
This gives you dense rewards (e.g., correctness spikes at answer spans, penalties for verbosity) without changing the overall pipeline.
Quick pointers to the spots you’ll edit
Where the scalar is created now
In RewardManagerWorker.compute_score(...):
result = self.reward_manager(data, return_dict=True)reward_score = result["reward_tensor"].sum(dim=-1).item() # <-- reduce to scalarreward_extra_info = { ... }
Where it’s placed into the batch
In AgentLoopWorker._postprocess(...):
You can have your reward_manager(...)consume these from the non_tensor_batch and fold them into the final reward (scalar or vector).
Bottom line
Multiple trajectories per workflow? ✔️ Supported (by repeating indices/rollouts).
Multiple reward components per trajectory? ✔️ Supported as metadata; you choose how to combine them.
Multiple rewards actually used by the optimizer: by default one scalar is applied at the last token; switch to dense rewards with a very small change if you want token-level shaping.
Here’s a minimal, surgical patch that (a) enables token-level rewards, and (b) combines a judge score with tool/turn rewards into a single per-token reward vector—while keeping full backward compatibility with the existing scalar-at-last-token behavior.
1) Pass response_mask to the reward worker, accept vectors back
File:.../agent_loop_runtime.py (the file that defines AgentLoopWorker and RewardManagerWorker; this matches the first code block you shared)
diff --git a/agent_loop_runtime.py b/agent_loop_runtime.pyindex 1111111..2222222 100644--- a/agent_loop_runtime.py+++ b/agent_loop_runtime.py@@ -377,6 +377,9 @@ class RewardManagerWorker:- async def compute_score(- self,- data: DataProto,- ) -> dict:+ async def compute_score(+ self,+ data: DataProto,+ ) -> dict: """Compute reward score for agent loop output. NOTE: Since `reward_manager.__call__` is blocking function, we run it in thread pool to@@ -392,15 +395,78 @@ class RewardManagerWorker: True, # return_dict )- reward_score = result["reward_tensor"].sum(dim=-1).item()- reward_extra_info = {k: v[0] for k, v in result.get("reward_extra_info", {}).items()}- return {"reward_score": reward_score, "reward_extra_info": reward_extra_info}+ # === NEW: build a token-level reward vector and a scalar summary ===+ # Inputs available in `data`:+ # - data.batch["attention_mask"]: [1, prompt_len + resp_len]+ # - data.batch["responses"]: [1, resp_len]+ # - data.batch["response_mask"]: [1, resp_len] (ADDED below in AgentLoopWorker)+ # - data.non_tensor_batch.get("tool_rewards"), "turn_scores" (optional lists)+ #+ # From reward_manager:+ # - result may contain:+ # * "reward_tensor" (scalar or vector)+ # * "judge_score" (scalar)+ # * "reward_extra_info" (dict)++ import torch++ # Pull shapes/masks+ responses = data.batch["responses"] # [1, R]+ R = responses.shape[1]+ response_mask = data.batch.get("response_mask", torch.ones_like(responses)) # [1, R]+ response_mask = response_mask.to(torch.bool)++ # Tool & turn rewards (lists) → simple scalars+ tool_rewards = data.non_tensor_batch.get("tool_rewards", [0.0])+ if isinstance(tool_rewards, (list, tuple)) and len(tool_rewards) == 0:+ tool_rewards = [0.0]+ tool_signal = float(sum(tool_rewards)) / max(1, len(tool_rewards))++ turn_scores = data.non_tensor_batch.get("turn_scores", [0.0])+ if isinstance(turn_scores, (list, tuple)) and len(turn_scores) == 0:+ turn_scores = [0.0]+ turn_signal = float(sum(turn_scores)) / max(1, len(turn_scores))++ # Judge signal: prefer explicit "judge_score", else reduce reward_tensor if scalar-like+ judge_signal = float(result.get("judge_score", 0.0))+ if judge_signal == 0.0 and "reward_tensor" in result:+ rt = result["reward_tensor"]+ # accept 0-dim or 1-dim single value+ try:+ judge_signal = float(rt.sum().item())+ except Exception:+ judge_signal = 0.0++ # Weights from config if present; else fall back to 1.0/0.5/0.5+ # You can add these under config.reward_model.reward_kwargs.{alpha,beta,gamma}+ cfg = getattr(self, "reward_manager", None)+ rwargs = getattr(cfg, "reward_kwargs", {}) if cfg is not None else {}+ alpha = float(rwargs.get("alpha", 1.0)) # judge+ beta = float(rwargs.get("beta", 0.5)) # tools+ gamma = float(rwargs.get("gamma", 0.5)) # turns++ # Build a per-token vector for the response region only.+ # Distribute scalar signals uniformly over model-generated tokens (response_mask==1).+ reward_vec = torch.zeros((R,), dtype=torch.float32)+ model_token_idxs = response_mask[0].nonzero(as_tuple=False).view(-1)+ n_model = int(model_token_idxs.numel())+ if n_model > 0:+ per_tok = (+ alpha * judge_signal + beta * tool_signal + gamma * turn_signal+ ) / float(n_model)+ reward_vec[model_token_idxs] = per_tok++ # Extra info passthrough+ reward_extra_info = {k: v[0] for k, v in result.get("reward_extra_info", {}).items()} if result.get("reward_extra_info") else {}++ # Keep backward compatibility: also return a scalar summary (sum of vector)+ reward_score = float(reward_vec.sum().item())+ return {+ "reward_score": reward_score,+ "reward_vector": reward_vec.tolist(),+ "reward_extra_info": reward_extra_info,+ } @ray.remote class AgentLoopWorker:@@ -610,6 +676,7 @@ class AgentLoopWorker: batch = TensorDict( { "prompts": prompt_output["input_ids"], # [1, prompt_length] "responses": response_output["input_ids"], # [1, response_length]+ "response_mask": response_mask, # [1, response_length] (NEW: needed for dense rewards) "attention_mask": attention_mask, # [1, prompt_length + response_length] "input_ids": input_ids, # [1, prompt_length + response_length] "position_ids": position_ids,@@ -636,7 +703,10 @@ class AgentLoopWorker: )- result = await self.reward_manager_worker.compute_score.remote(data)- output.reward_score = result["reward_score"]- output.extra_fields["reward_extra_info"] = result["reward_extra_info"]+ result = await self.reward_manager_worker.compute_score.remote(data)+ output.reward_score = result["reward_score"] # keep scalar summary for logs+ # NEW: carry vector + extras forward (will be consumed in _postprocess)+ output.extra_fields["reward_vector"] = result.get("reward_vector", None)+ output.extra_fields["reward_extra_info"] = result.get("reward_extra_info", {}) return _InternalAgentLoopOutput( prompt_ids=prompt_output["input_ids"],@@ -719,20 +789,43 @@ class AgentLoopWorker: batch = TensorDict( { "prompts": prompt_ids, # [bsz, prompt_length] "responses": response_ids, # [bsz, response_length] "response_mask": response_mask, # [bsz, response_length] "input_ids": input_ids, # [bsz, prompt_length + response_length] "attention_mask": attention_mask, # [bsz, prompt_length + response_length] # position_ids: [bsz, 3, prompt_length + response_length] or [bsz, prompt_length + response_length] "position_ids": position_ids, **optional_outputs, }, batch_size=len(inputs), )- scores = [input.reward_score for input in inputs]- if all(score is not None for score in scores):- prompt_length = prompt_ids.size(1)- response_length = attention_mask[:, prompt_length:].sum(dim=1) - 1- rm_scores = torch.zeros_like(response_mask, dtype=torch.float32)- rm_scores[torch.arange(response_mask.size(0)), response_length] = torch.tensor(scores, dtype=torch.float32)- batch["rm_scores"] = rm_scores+ # === NEW: prefer dense rewards if provided; else fall back to scalar-at-last-token ===+ dense_vectors = [inp.extra_fields.get("reward_vector", None) for inp in inputs]+ if all((vec is not None) for vec in dense_vectors):+ # Each vec is a Python list length == response_length+ try:+ rm_scores = torch.tensor([list(map(float, v)) for v in dense_vectors], dtype=torch.float32)+ # Sanity clamp to response_mask (no reward on tool/user tokens)+ rm_scores = rm_scores * response_mask.to(torch.float32)+ batch["rm_scores"] = rm_scores+ except Exception:+ # Fallback to scalar if vector materialization fails+ scores = [inp.reward_score for inp in inputs]+ if all(score is not None for score in scores):+ prompt_length = prompt_ids.size(1)+ response_length = attention_mask[:, prompt_length:].sum(dim=1) - 1+ rm_scores = torch.zeros_like(response_mask, dtype=torch.float32)+ rm_scores[torch.arange(response_mask.size(0)), response_length] = torch.tensor(scores, dtype=torch.float32)+ batch["rm_scores"] = rm_scores+ else:+ scores = [inp.reward_score for inp in inputs]+ if all(score is not None for score in scores):+ prompt_length = prompt_ids.size(1)+ response_length = attention_mask[:, prompt_length:].sum(dim=1) - 1+ rm_scores = torch.zeros_like(response_mask, dtype=torch.float32)+ rm_scores[torch.arange(response_mask.size(0)), response_length] = torch.tensor(scores, dtype=torch.float32)+ batch["rm_scores"] = rm_scores non_tensor_batch = { "__num_turns__": np.array([input.num_turns for input in inputs], dtype=np.int32),@@ -742,6 +835,7 @@ class AgentLoopWorker: reward_extra_infos = [input.extra_fields.get("reward_extra_info", {}) for input in inputs] reward_extra_keys = list(reward_extra_infos[0].keys()) for key in reward_extra_keys: non_tensor_batch[key] = np.array([info[key] for info in reward_extra_infos])+ # reward_vector is not mirrored to non_tensor_batch; it's already materialized into rm_scores above. # Add multi_modal_inputs to non_tensor_batch if any samples have them multi_modal_inputs_list = [input.multi_modal_inputs for input in inputs]
What changed:
Reward worker now builds a per-token vector by combining:
Judge score (alpha)
Mean tool reward (beta)
Mean interaction turn score (gamma)
Distributes the sum uniformly over model-generated tokens (response_mask==1).
We pass response_mask into the reward worker (so it knows which tokens are model tokens).
We still return a scalar summary (reward_score) for logs/compatibility.
In _postprocess, if a reward vector is present, we fill rm_scores densely (masked); otherwise we keep the existing scalar-at-last-token behavior.
You can change the distribution rule (e.g., weight later tokens more) by modifying the few lines that compute reward_vec.
2) (Optional) Example judge that returns a scalar
If your existing reward_manager(...) returned only reward_tensor, you don’t have to change it. But if you’d like to explicitly return a scalar judge score and any extra info:
The new worker will prefer "judge_score" (if present) and fall back to reward_tensor.sum() otherwise.
3) Tweaking the combination weights (alpha/beta/gamma)
You can thread weights through your existing config:
reward_model: enable: true reward_kwargs: alpha: 1.0 # weight for judge score beta: 0.5 # weight for mean tool reward gamma: 0.5 # weight for mean turn score
They’re read in the patch via:
cfg = getattr(self, "reward_manager", None)rwargs = getattr(cfg, "reward_kwargs", {}) if cfg is not None else {}alpha = float(rwargs.get("alpha", 1.0))beta = float(rwargs.get("beta", 0.5))gamma = float(rwargs.get("gamma", 0.5))
Notes & validation
Back-compat safe: if reward_vector isn’t produced (or vector materialization fails), training still uses the single scalar at the last token, exactly like before.
Mask safety: dense rewards are zeroed on tool/user tokens via response_mask.
Minimal surface area: no changes to your tool/interaction code or dataset are required.
Two Complex Agentic Workflows (with Code) + Workflow-Based Rewards + Training Setup
Below are two concrete workflows that each make multiple LLM calls and use tools. For each workflow, I give:
a definition (what the steps are and how they call the LLM),
a workflow-specific reward model (judge + process signals → dense per-token vector),
runnable-ish code stubs that plug into the VERL agent loop framework you shared,
a training config showing how to wire tools, agents, and rewards.
I keep the code consistent with the structure of your files (AgentLoopBase, AsyncLLMServerManager, tool schema, etc.). You can drop these files into your repo under a new package (e.g., wf_examples/).
Workflow A — “Multicolored Research” (multi-source, multi-pass reasoning)
Goal. Produce a short brief with colored evidence tags:
Green = strong support (≥2 reputable sources agree)
Yellow = tentative (only 1 source or weak confidence)
Red = contradicted (sources disagree)
LLM calls per sample (typical):
Plan (LLM): generate 5–8 sub-queries across aspects (history, data, counterpoints).
For each sub-query: Search (tool) → Fetch (tool) → Extract (LLM) key claims + metadata.
Aggregate (LLM): deduplicate + cluster claims across sources.
Colorize (LLM): assign Green/Yellow/Red labels with short justifications + citations.
Compose (LLM): write the final brief with colored bullets and inline citations.
(You can add meta.py and cite.py similarly, or fold their functionality into prompts.)
C) Workflow-Based Reward Manager (dense, per token)
This implementation combines:
a judge score (from an LLM-as-judge you call internally or a rubric),
process signals (tool rewards, pass rate, diversity, etc.),
and returns a per-token reward vector (aligned to response tokens where response_mask==1).
Assumes you applied the tiny patch earlier to carry response_mask to the reward worker and to accept reward_vector back into rm_scores.
wf_examples/rewards/workflow_reward_manager.py
import torchfrom typing import Dict, Anyclass WorkflowRewardManager: """ A minimal 'reward_manager' that: - computes/reads a judge score (stubbed here), - extracts process signals from non_tensor_batch, - returns dict with reward_tensor (vector) + judge_score + reward_extra_info. """ def __init__(self, tokenizer=None, num_examine=0, **reward_kwargs): self.kw = reward_kwargs or {} # weights self.alpha = float(self.kw.get("alpha", 1.0)) # judge self.beta = float(self.kw.get("beta", 0.6)) # tool signals self.gamma = float(self.kw.get("gamma", 0.4)) # turn signals self.delta = float(self.kw.get("delta", 0.6)) # domain-specific (e.g., test pass, diversity) def _fake_judge(self, text: str) -> float: # TODO: call a judge model with a rubric prompt score = 0.7 + 0.3 * (text.count("[") > 2) # bonus if uses citations/marks return float(min(1.0, max(0.0, score))) def __call__(self, data, return_dict: bool = False): """ data.batch: - responses: [1, R] - response_mask: [1, R] (1 on model tokens) - input_ids, attention_mask, position_ids ... data.non_tensor_batch: dict with Python objects """ responses = data.batch["responses"] # [1, R] response_mask = data.batch["response_mask"] # [1, R] R = int(responses.shape[1]) # decode final assistant text to judge (optional; or judge on the whole input_ids) # For simplicity: judge the last response segment length ~ R # If you want: pass full context via data.batch["input_ids"] and attention. # We'll stub a judge here without decoding (pretend 0.75). judge_score = 0.75 # Process signals from non_tensor_batch nt = data.non_tensor_batch tool_rewards = nt.get("tool_rewards", [0.0]) if isinstance(tool_rewards, (list, tuple)) and len(tool_rewards)==0: tool_rewards=[0.0] tool_sig = float(sum(tool_rewards) / max(1, len(tool_rewards))) turn_scores = nt.get("turn_scores", [0.0]) if isinstance(turn_scores, (list, tuple)) and len(turn_scores)==0: turn_scores=[0.0] turn_sig = float(sum(turn_scores) / max(1, len(turn_scores))) # Optional domain-based signals pass_rate = 0.0 if "pass_rate" in nt: # when sandbox tool recorded it try: pass_rate = float(nt["pass_rate"]) except Exception: pass_rate = 0.0 diversity = float(nt.get("diversity", 0.0)) # e.g., unique domains/aspects from research workflow # Combine to trajectory scalar traj_scalar = ( self.alpha * judge_score + self.beta * tool_sig + self.gamma * turn_sig + self.delta * 0.5 * (pass_rate + diversity) ) # Distribute densely over model tokens (uniform for now) model_token_idxs = response_mask[0].nonzero(as_tuple=False).view(-1) reward_vec = torch.zeros((R,), dtype=torch.float32) if int(model_token_idxs.numel()) > 0: reward_vec[model_token_idxs] = traj_scalar / float(model_token_idxs.numel()) out = { "reward_tensor": reward_vec, # vector "judge_score": judge_score, "reward_extra_info": { "tool_sig": tool_sig, "turn_sig": turn_sig, "pass_rate": pass_rate, "diversity": diversity, "traj_scalar": float(traj_scalar), } } return out if return_dict else out["reward_tensor"]
Wire this class into your framework by pointing config.reward_model._target_ to it (see config below). If your runner expects load_reward_manager to construct it, adapt the import path accordingly.
Research row (uses tool_agent_research + research tools)
{ "agent_name": "tool_agent_research", "raw_prompt": [ {"role":"system","content":"You are a rigorous research agent."}, {"role":"user","content":"Produce a brief on {TOPIC} with colored evidence [Green]/[Yellow]/[Red] and citations."} ], "tools_kwargs": {}}
{ "agent_name": "tool_agent_iterative", "raw_prompt": [ {"role":"system","content":"You are a careful engineer."}, {"role":"user","content":"Write a function that parses log lines; include unit tests; iterate until all tests pass."} ], "extra_info": {"max_iters": 3}}
If you mix both in one dataset, just set agent_name per row; the loop registry will instantiate the right class for each sample.
Efficiency Notes (8-GPU single node)
Use many 1-GPU server replicas (e.g., 6) + 2 GPUs for training, and raiseagent.num_workers until the trainer never starves.
Prefer LoRA/QLoRA to shrink training footprint to 1 GPU if rollouts are slow.
Keep servers persistent; do not restart between batches.
Use multiple PPO minibatches and grad accumulation to keep the training GPUs busy while rollouts are in flight.
The (earlier) dense reward patch lets you shape learning at token granularity (e.g., more reward on final brief tokens or code deltas that fix tests).
What you can customize quickly
Color rules: adjust prompts so “Colorize” enforces strict criteria.
Judge: replace _fake_judge with a rubric-prompt to a (possibly separate) judge model.
Dense shaping: in the reward manager, spread more weight to final assistant turn tokens; set zeros on tool/user spans via response_mask.
Process signals: surface more metrics from tools (e.g., domain diversity, coverage, contradictions) through non_tensor_batch and feed them into reward.