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).
  • RewardManagerWorker: evals trajectory reward asynchronously.
  • BatchExecutor: micro-batches blocking computations (e.g., reward).
  • 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/images
pip install -U pillow

Run a local OpenAI-compatible server (example: Qwen 7B instruct):

python -m vllm.entrypoints.openai.api_server \
  --model Qwen/Qwen2.5-7B-Instruct \
  --dtype bfloat16 \
  --port 8001 \
  --max-model-len 32768 \
  --tensor-parallel-size 1

You can also let VERL’s rollout replica wrapper launch servers; starting vLLM explicitly is great for first runs.


3) Core Code Walkthrough

3.1 AsyncLLMServerManager

  • Maintains a heap of servers with “least requests” count.
  • Sticky session: maps request_id → server (LRU cache) so multi-turn conversations reuse KV cache.
  • generate(request_id, prompt_ids, sampling_params, image_data) -> TokenOutput.

Why this matters: multi-turn cost plummets with KV cache; keep the same session on the same replica.


3.2 ToolAgentLoop: the Agent Workflow

Registered as "tool_agent" via @register("tool_agent"). Its run(...) is a state machine:

  • PENDING → build initial prompt_ids using tokenizer/processor with tool schemas included in the chat template.
  • GENERATING → call LLM; append generated response_ids and extend response_mask with 1s (LLM tokens).
  • Parse tool calls; if found → PROCESSING_TOOLS.
  • PROCESSING_TOOLS:
    • call tools in parallel (up to max_parallel_calls);
    • each tool returns ToolResponse(text/image/video) + optional reward;
    • append tool messages to the chat and to prompt_ids, but mark response_mask with 0s (not LLM tokens).
  • (Optional) INTERACTING:
    • query a registered BaseInteraction to synthesize a user message; append with 0 mask.
  • Repeat until response_length or turn limits; then build AgentLoopOutput.

Masking discipline:

  • 1 for model-generated tokens → they receive policy loss.
  • 0 for tool/user insertions & padding → no policy loss.

3.3 AgentLoopWorker (per-batch executor)

  • Instantiates the agent loop (via registry/Hydra).
  • Calls run(...), then pads/concats:
    • Prompts are left-padded; responses right-padded.
    • Builds attention_mask, position_ids.
      • If VLM (e.g., Qwen2-VL), compute vision position ids and concat with text positions.
  • (Async) reward: if agent didn’t set it, send a DataProto to RewardManagerWorker.
  • Emits a batched DataProto with:
    • prompts, responses, response_mask, input_ids, attention_mask, position_ids, optional rollout_log_probs.
    • rm_scores as a sparse tensor placed on the last response token (sequence-level reward).
    • Non-tensor “extras” (e.g., reward_extra_info, multimodal inputs).

3.4 RewardManagerWorker + BatchExecutor

  • Wraps a reward_manager(...) that you define/configure (LLM-as-judge, heuristics, etc.).
  • Runs in a thread pool (blocking call), optionally through BatchExecutor to micro-batch multiple requests.
  • Returns a scalar score plus extra info for logging.

3.5 AgentLoopManager

  • Computes how many rollout replicas to launch (TP×DP).
  • Initializes rollout replicas (OpenAI-compatible servers) once and keeps their actor handles.
  • Spawns AgentLoopWorker actors across nodes/CPUs (NodeAffinitySchedulingStrategy).
  • Splits a big input batch across workers, gathers results, and computes timing metrics.

4) Define Your Tools

Create a package, e.g., research_agent/tools. Tools implement the VERL tool interface and return a ToolResponse.

# research_agent/tools/search.py
from pydantic import BaseModel, Field
from verl.tools.base import BaseTool
from verl.tools.schemas import ToolResponse
 
class SearchArgs(BaseModel):
    query: str = Field(..., description="Web query")
    top_k: int = Field(5, ge=1, le=10)
 
class WebSearchTool(BaseTool):
    name = "web_search"
    description = "Search the web"
    tool_schema = SearchArgs  # used to build function/tool schemas in the chat template
 
    async def create(self, create_kwargs=None):
        return "search-instance", {}  # optional stateful init
 
    async def execute(self, instance_id, args: dict):
        p = SearchArgs(**args)
        # ... do the search ...
        text = "\n".join([f"{i+1}. Dummy hit for: {p.query}" for i in range(p.top_k)])
        reward = 0.0
        extra = {}
        return ToolResponse(text=text), reward, extra
 
    async def release(self, instance_id):
        return

Wire multiple tools via YAML:

# research_agent/configs/tools.yaml
tools:
  - _target_: research_agent.tools.search.WebSearchTool
  - _target_: research_agent.tools.fetch.FetchTool
  - _target_: research_agent.tools.summarize.SummarizeTool

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.

# research_agent/interactions/scripted_user.py
from verl.interactions.base import BaseInteraction
 
class ScriptedUser(BaseInteraction):
    async def start_interaction(self, request_id, **kwargs):
        self.round = 0
 
    async def generate_response(self, request_id, messages, **kwargs):
        self.round += 1
        user_msg = "Please add 3 sources with dates."
        should_terminate = self.round >= kwargs.get("max_rounds", 2)
        reward, metrics = None, {}
        return should_terminate, user_msg, reward, metrics

Register them:

# research_agent/configs/interactions.yaml
interactions:
  scripted_user:
    _target_: research_agent.interactions.scripted_user.ScriptedUser

How it’s used:

  • 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.yaml
trainer:
  project_name: agent-training
  experiment_name: qwen7b_tools
  nnodes: 1
  n_gpus_per_node: 8
 
actor_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  # optional
 
reward_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):

python -m verl.trainer.main_ppo \
  algorithm.adv_estimator=grpo \
  +experiment=train_agent.yaml \
  actor_rollout_ref.model.path=Qwen/Qwen2.5-7B-Instruct \
  data.train_files=/data/train.jsonl \
  data.val_files=/data/val.jsonl \
  data.return_raw_chat=true

Common runtime knobs:

  • actor_rollout_ref.rollout.agent.num_workers=16 (increase rollout concurrency)
  • actor_rollout_ref.rollout.response_length=768 (shorten responses to speed up)
  • algorithm.ppo_train_minibatches=8 (ensure multiple minibatches per batch)
  • PEFT: configure LoRA to cut training memory if you want 1-GPU training + more inference GPUs.

9) Efficiency on 8 GPUs (practical recipes)

Goal: both rollout and training stay busy; avoid killing servers constantly.

  • Template A (steady split)
    • 6 GPUs for inference (6× 1-GPU replicas), 2 GPUs for training.
    • Raise num_workers until trainer doesn’t starve (e.g., 48–96 in-flight episodes).
    • Use multiple PPO minibatches and gradient accumulation on the 2 training GPUs.
  • Template B (LoRA training)
    • 7 GPUs inference, 1 GPU training.
    • Best when rollouts are slow (10-minute episodes). Trainer keeps up fine with LoRA.
  • Template C (elastic)
    • Launch several 1-GPU servers so you can add/remove one if the trainer starves/servers idle.
    • Accept a small reload penalty when resizing (better than long-term idle).
  • Template D (phased)
    • 8× inference for N minutes → buffer full → 8× training for M steps → repeat.
    • Simple and deterministic if you like batch collect → batch train.

Other levers

  • Reduce token budget (response_length, turns), nudge model succinctness (lower temperature, moderate top_p).
  • 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

Dataset chooses:

{"agent_name":"tool_agent_research", "raw_prompt":[...]}
{"agent_name":"tool_agent_coding",   "raw_prompt":[...]}

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.

12) Minimal End-to-End Skeleton

Tools YAML

tools:
  - _target_: research_agent.tools.search.WebSearchTool

Interactions YAML (optional)

interactions:
  scripted_user:
    _target_: research_agent.interactions.scripted_user.ScriptedUser

Sample (JSONL)

{"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}}}

Hydra

trainer: {project_name: demo, experiment_name: demo, nnodes: 1, n_gpus_per_node: 8}
actor_rollout_ref:
  model: {path: Qwen/Qwen2.5-7B-Instruct}
  rollout:
    name: vllm_openai
    prompt_length: 4096
    response_length: 768
    agent: {num_workers: 8}
    multi_turn:
      format: "openai"
      tool_config_path: research_agent/configs/tools.yaml
      interaction_config_path: research_agent/configs/interactions.yaml
reward_model: {enable: true, enable_resource_pool: false}
data:
  train_files: /data/train.jsonl
  val_files: /data/val.jsonl
  return_raw_chat: true

Run

python -m verl.trainer.main_ppo +experiment=train_agent.yaml

13) Checklist

  • 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:
    1. It builds a DataProto that contains the final packed tensors (input_ids, attention_mask, position_ids, etc.) plus some non-tensor metadata.

    2. RewardManagerWorker.compute_score(...) calls your configured reward_manager(...) (blocking, often LLM-as-judge or heuristics), then reduces its output to a scalar:

      reward_score = result["reward_tensor"].sum(dim=-1).item()

      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 vector reward_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:
      1. Modify RewardManagerWorker.compute_score(...) to not sum; instead return a 1D vector whose length matches the response length.
      2. 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:

  1. At the data level: feed repeated rows with the same index; get_trajectory_info(...) sets rollout_n for you.
  2. 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 own rm_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)

  1. Return a vector reward_tensor shaped to the response length (zeros where response_mask==0).
  2. Remove the .sum(...).item() reduction in RewardManagerWorker.compute_score.
  3. 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 scalar
    reward_extra_info = { ... }
  • Where it’s placed into the batch
    In AgentLoopWorker._postprocess(...):
    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
    Change this to fill a whole vector if you switch to dense rewards.
  • Where per-turn signals are kept
    In ToolAgentLoop.run(...):
    output.extra_fields.update({
      "turn_scores": agent_data.turn_scores,
      "tool_rewards": agent_data.tool_rewards
    })
    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.py
index 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:

# inside your reward_manager(...)
# return_dict=True
return {
    "reward_tensor": torch.tensor([judge_scalar], dtype=torch.float32),  # kept for compatibility
    "judge_score": float(judge_scalar),                                   # explicit
    "reward_extra_info": {"coverage": coverage, "citations": citations}
}

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):

  1. Plan (LLM): generate 5–8 sub-queries across aspects (history, data, counterpoints).
  2. For each sub-query: Search (tool) → Fetch (tool) → Extract (LLM) key claims + metadata.
  3. Aggregate (LLM): deduplicate + cluster claims across sources.
  4. Colorize (LLM): assign Green/Yellow/Red labels with short justifications + citations.
  5. Compose (LLM): write the final brief with colored bullets and inline citations.

Tools used. web_search, fetch_page, url_metadata, cite_formatter.

Reward model (dense).

  • Judge (LLM-as-judge): accuracy/coverage/coherence/citation quality (scalar).
  • Process signals:
    • diversity_bonus: unique domains + unique aspects covered.
    • consistency_penalty: contradictions without marking Red.
    • recency_bonus: sources ≤ 18 months old.
  • Dense reward shaping:
    • Allocate + weights more reward to tokens inside the final brief section (e.g., last assistant turn).
    • Small positive reward to tokens that render proper citations […] and color tags [Green], [Yellow], [Red].

Workflow B — “Iterative Improve-and-Verify” (proposal → critique → revise loop)

Goal. Solve a complex task (coding/math/policy) via iterative cycles:

  • Propose (LLM): create candidate solution (code/proof/policy).
  • Execute/Verify (tool): run tests / checkers / static analyzers / formal verifiers.
  • Reflect (LLM): analyze failures and produce a revision plan.
  • Revise (LLM): update solution using plan; repeat until pass or budget.

LLM calls per cycle:

  1. Propose
  2. Reflect (if failures)
  3. Revise (if failures)
    (Repeat 2–3×; configurable)

Tools used. sandbox_run (execute tests), unit_coverage, static_check, diff_view.

Reward model (dense).

  • Judge (LLM-as-judge): quality/robustness/readability (scalar).
  • Process signals:
    • test_pass_rate (from sandbox), coverage_improvement, lint_score.
    • convergence_bonus: if failures decrease across iterations.
    • iteration_penalty: mild penalty for too many cycles without improvement.
  • Dense shaping:
    • Heavier reward on tokens inside final solution turn (last assistant output).
    • Small incremental per-token reward for additions that close diff gaps (measured by diff_view).

Code: Agents, Tools, Reward Manager

Folder layout:

wf_examples/
  agents/
    research_agent.py
    iterative_agent.py
  tools/
    search.py
    fetch.py
    meta.py
    cite.py
    sandbox.py
    static.py
    diff.py
  rewards/
    workflow_reward_manager.py
  configs/
    tools_research.yaml
    tools_iterative.yaml
    interactions.yaml
    train.yaml

A) Agents (each makes multiple LLM calls via the server manager)

wf_examples/agents/research_agent.py

from typing import Any, Dict, List
import asyncio, time, json
from verl.experimental.agent_loop.agent_loop import AgentLoopBase, AgentLoopOutput, register
from verl.experimental.agent_loop.tool_parser import ToolParser
from verl.tools.schemas import ToolResponse
 
@register("tool_agent_research")
class ResearchAgentLoop(AgentLoopBase):
    """
    Multicolored Research workflow with multiple LLM calls:
      plan -> per-aspect search/fetch -> extract -> aggregate -> colorize -> compose
    """
 
    @classmethod
    def init_class(cls, config, tokenizer, processor, **kwargs):
        if cls._class_initialized: return
        cls._class_initialized = True
        cls.tokenizer = tokenizer
        cls.processor = processor
        cls.prompt_len = config.actor_rollout_ref.rollout.prompt_length
        cls.response_len = config.actor_rollout_ref.rollout.response_length
        cls.apply_kwargs = config.data.get("apply_chat_template_kwargs", {})
        # Load tools
        from verl.tools.utils.tool_registry import initialize_tools_from_config
        tcfg = config.actor_rollout_ref.rollout.multi_turn.tool_config_path
        cls.tools = {t.name: t for t in (initialize_tools_from_config(tcfg) if tcfg else [])}
        cls.tool_parser = ToolParser.get_tool_parser("openai", tokenizer)
 
    async def _call_llm(self, request_id: str, text_ids: List[int], sampling_params: Dict[str, Any], image_data=None):
        out = await self.server_manager.generate(
            request_id=request_id,
            prompt_ids=text_ids,
            sampling_params=sampling_params,
            image_data=image_data,
        )
        return out.token_ids, out.log_probs or []
 
    async def _tool(self, name: str, args: dict, tools_kwargs: dict) -> ToolResponse:
        tool = self.tools[name]; inst = None
        kwargs = (tools_kwargs or {}).get(name, {})
        inst, _ = await tool.create(create_kwargs=kwargs.get("create_kwargs", {}))
        try:
            resp, _, _ = await tool.execute(inst, args)
        finally:
            await tool.release(inst)
        return resp
 
    def _encode_msgs(self, messages: List[Dict[str, Any]]) -> List[int]:
        # text-only for brevity; add image processor if your base model is VLM
        return self.tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, **self.apply_kwargs)
 
    async def run(self, sampling_params: dict, **kwargs) -> AgentLoopOutput:
        """
        The whole workflow runs inside this loop; we stitch all LLM turns and tool
        insertions into a single sequence and build response_mask accordingly.
        """
        messages = list(kwargs["raw_prompt"])
        tools_kwargs = kwargs.get("tools_kwargs", {})
        request_id = f"research-{time.time_ns()}"
        prompt_ids: List[int] = []
        response_ids: List[int] = []
        response_mask: List[int] = []
        response_logprobs: List[float] = []
        turn_scores: List[float] = []
        tool_rewards: List[float] = []
 
        # ---- 1) PLAN ----
        plan_prompt = messages + [
          {"role": "system",
           "content": "Plan 5-8 aspects and queries. Return JSON list: [{aspect, queries:[...] }]."}
        ]
        ids = self._encode_msgs(plan_prompt)
        toks, lps = await self._call_llm(request_id, prompt_ids + ids, sampling_params)
        prompt_ids += toks; response_ids += toks; response_mask += [1]*len(toks); response_logprobs += lps
        # naive parse from decoded text
        plan_text = self.tokenizer.decode(toks, skip_special_tokens=True)
        try:
            plan = json.loads(plan_text[plan_text.find("["): plan_text.rfind("]")+1])
        except Exception:
            plan = [{"aspect":"default","queries":[messages[-1]["content"]]}]
 
        # ---- 2) PER-ASPECT SEARCH/FETCH/EXTRACT ----
        claims: List[dict] = []
        for item in plan[:6]:
            for q in item.get("queries", [])[:2]:
                # tool: search
                tresp = await self._tool("web_search", {"query": q, "top_k": 4}, tools_kwargs)
                messages.append({"role":"tool","content": tresp.text})
                tool_rewards.append(0.1)  # small process reward
                ids = self._encode_msgs([{"role":"tool","content": tresp.text}])
                prompt_ids += ids; response_mask += [0]*len(ids); response_logprobs += [0.0]*len(ids)
 
                # choose one url (toy)
                url = tresp.text.splitlines()[0].split()[-1] if tresp.text.strip() else ""
                if not url: continue
                # tool: fetch
                fresp = await self._tool("fetch_page", {"url": url, "max_chars": 5000}, tools_kwargs)
                messages.append({"role":"tool","content": fresp.text[:4000]})
                ids = self._encode_msgs([{"role":"tool","content": fresp.text[:4000]}])
                prompt_ids += ids; response_mask += [0]*len(ids); response_logprobs += [0.0]*len(ids)
 
                # LLM: extract
                xprompt = messages + [{"role":"system","content":"Extract key claims with source, date, stance."}]
                ids = self._encode_msgs(xprompt)
                toks, lps = await self._call_llm(request_id, prompt_ids + ids, sampling_params)
                prompt_ids += toks; response_ids += toks; response_mask += [1]*len(toks); response_logprobs += lps
                text = self.tokenizer.decode(toks, skip_special_tokens=True)
                claims.append({"aspect": item["aspect"], "raw": text})
 
        # ---- 3) AGGREGATE ----
        agg_prompt = messages + [{"role":"system","content":"Aggregate & cluster claims; deduplicate; output JSON."}]
        ids = self._encode_msgs(agg_prompt)
        toks, lps = await self._call_llm(request_id, prompt_ids + ids, sampling_params)
        prompt_ids += toks; response_ids += toks; response_mask += [1]*len(toks); response_logprobs += lps
 
        # ---- 4) COLORIZE ----
        color_prompt = messages + [{"role":"system",
           "content":"Assign Green/Yellow/Red to claims with 1-sentence justification; include citations."}]
        ids = self._encode_msgs(color_prompt)
        toks, lps = await self._call_llm(request_id, prompt_ids + ids, sampling_params)
        prompt_ids += toks; response_ids += toks; response_mask += [1]*len(toks); response_logprobs += lps
 
        # ---- 5) COMPOSE FINAL BRIEF ----
        final_prompt = messages + [{"role":"system",
           "content":"Write final brief: bullets with [Green]/[Yellow]/[Red] and inline citations [1],[2] ..."}]
        ids = self._encode_msgs(final_prompt)
        toks, lps = await self._call_llm(request_id, prompt_ids + ids, sampling_params)
        prompt_ids += toks; response_ids += toks; response_mask += [1]*len(toks); response_logprobs += lps
 
        out = AgentLoopOutput(
            prompt_ids=prompt_ids[:-len(response_mask)] if response_mask else prompt_ids,
            response_ids=response_ids[: self.response_len],
            response_mask=response_mask[: self.response_len],
            response_logprobs=response_logprobs[: self.response_len] if response_logprobs else None,
            multi_modal_data={},
            num_turns=1,  # not used critically here
            metrics={"generate_sequences": 0.0, "tool_calls": 0.0}
        )
        out.extra_fields["turn_scores"] = []
        out.extra_fields["tool_rewards"] = tool_rewards
        return out

wf_examples/agents/iterative_agent.py

from typing import Any, Dict, List
import asyncio, time
from verl.experimental.agent_loop.agent_loop import AgentLoopBase, AgentLoopOutput, register
 
@register("tool_agent_iterative")
class IterativeImproveAgentLoop(AgentLoopBase):
    """
    Iterative Improve-and-Verify:
      propose -> run tests -> reflect -> revise (repeat up to K)
    """
 
    @classmethod
    def init_class(cls, config, tokenizer, processor, **kwargs):
        if cls._class_initialized: return
        cls._class_initialized = True
        cls.tokenizer = tokenizer
        cls.processor = processor
        cls.prompt_len = config.actor_rollout_ref.rollout.prompt_length
        cls.response_len = config.actor_rollout_ref.rollout.response_length
        cls.apply_kwargs = config.data.get("apply_chat_template_kwargs", {})
        from verl.tools.utils.tool_registry import initialize_tools_from_config
        tcfg = config.actor_rollout_ref.rollout.multi_turn.tool_config_path
        cls.tools = {t.name: t for t in (initialize_tools_from_config(tcfg) if tcfg else [])}
 
    def _encode(self, messages): 
        return self.tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, **self.apply_kwargs)
 
    async def _llm(self, rid, ids, sp, img=None):
        out = await self.server_manager.generate(request_id=rid, prompt_ids=ids, sampling_params=sp, image_data=img)
        return out.token_ids, out.log_probs or []
 
    async def _tool(self, name: str, args: dict, tools_kwargs: dict):
        t = self.tools[name]; inst = None
        kwargs = (tools_kwargs or {}).get(name, {})
        inst, _ = await t.create(create_kwargs=kwargs.get("create_kwargs", {}))
        try:
            resp, reward, extra = await t.execute(inst, args)
        finally:
            await t.release(inst)
        return resp, reward, extra
 
    async def run(self, sampling_params: dict, **kwargs) -> AgentLoopOutput:
        messages = list(kwargs["raw_prompt"])
        tools_kwargs = kwargs.get("tools_kwargs", {})
        request_id = f"iter-{time.time_ns()}"
 
        prompt_ids: List[int] = []
        response_ids: List[int] = []
        response_mask: List[int] = []
        response_logprobs: List[float] = []
        turn_scores: List[float] = []
        tool_rewards: List[float] = []
 
        max_iters = kwargs.get("extra_info",{}).get("max_iters", 3)
 
        # (0) PROPOSE INITIAL
        ids = self._encode(messages + [{"role":"system","content":"Propose an initial candidate solution."}])
        toks, lps = await self._llm(request_id, prompt_ids + ids, sampling_params)
        prompt_ids += toks; response_ids += toks; response_mask += [1]*len(toks); response_logprobs += lps
        current = self.tokenizer.decode(toks, skip_special_tokens=True)
 
        for step in range(max_iters):
            # (1) RUN TESTS
            run_resp, rwd, extra = await self._tool("sandbox_run", {"code_or_text": current}, tools_kwargs)
            tool_rewards.append(float(rwd or 0.0))
            ids = self._encode([{"role":"tool","content": run_resp.text[:3000]}])
            prompt_ids += ids; response_mask += [0]*len(ids); response_logprobs += [0.0]*len(ids)
 
            # short-circuit if all pass
            if "ALL_TESTS_PASS" in (run_resp.text or ""):
                break
 
            # (2) REFLECT
            refl_ids = self._encode([{"role":"system","content":"Analyze the failures above and outline a plan to fix them."}])
            toks, lps = await self._llm(request_id, prompt_ids + refl_ids, sampling_params)
            prompt_ids += toks; response_ids += toks; response_mask += [1]*len(toks); response_logprobs += lps
 
            # (3) REVISE
            rev_ids = self._encode([{"role":"system","content":"Rewrite the solution implementing the plan. Output only the final code or answer."}])
            toks, lps = await self._llm(request_id, prompt_ids + rev_ids, sampling_params)
            prompt_ids += toks; response_ids += toks; response_mask += [1]*len(toks); response_logprobs += lps
            current = self.tokenizer.decode(toks, skip_special_tokens=True)
 
            # (4) STATIC CHECKS (optional)
            chk_resp, lint_rwd, _ = await self._tool("static_check", {"code_or_text": current}, tools_kwargs)
            tool_rewards.append(float(lint_rwd or 0.0))
            ids = self._encode([{"role":"tool","content": chk_resp.text[:2000]}])
            prompt_ids += ids; response_mask += [0]*len(ids); response_logprobs += [0.0]*len(ids)
 
        out = AgentLoopOutput(
            prompt_ids=prompt_ids[:-len(response_mask)] if response_mask else prompt_ids,
            response_ids=response_ids[: self.response_len],
            response_mask=response_mask[: self.response_len],
            response_logprobs=response_logprobs[: self.response_len] if response_logprobs else None,
            multi_modal_data={},
            num_turns=1,
            metrics={"generate_sequences": 0.0, "tool_calls": 0.0}
        )
        out.extra_fields["turn_scores"] = turn_scores
        out.extra_fields["tool_rewards"] = tool_rewards
        return out

B) Tools (representative stubs; adapt to your infra)

wf_examples/tools/search.py

from pydantic import BaseModel, Field
from verl.tools.base import BaseTool
from verl.tools.schemas import ToolResponse
 
class SearchArgs(BaseModel):
    query: str = Field(..., description="Web search query")
    top_k: int = Field(4, ge=1, le=10)
 
class WebSearch(BaseTool):
    name = "web_search"
    description = "Search the web and return top results with titles and URLs"
    tool_schema = SearchArgs
 
    async def create(self, create_kwargs=None):
        return "search", {}
 
    async def execute(self, instance_id, args: dict):
        p = SearchArgs(**args)
        # TODO: replace with real search backend
        fake_lines = [f"{i+1}. {p.query} — https://example.com/{i}" for i in range(p.top_k)]
        text = "\n".join(fake_lines)
        reward = 0.0
        return ToolResponse(text=text), reward, {}
    async def release(self, instance_id): return

wf_examples/tools/fetch.py

from pydantic import BaseModel, Field
from verl.tools.base import BaseTool
from verl.tools.schemas import ToolResponse
 
class FetchArgs(BaseModel):
    url: str
    max_chars: int = Field(4000, ge=100, le=30000)
 
class FetchPage(BaseTool):
    name = "fetch_page"
    description = "Fetch page main text"
    tool_schema = FetchArgs
 
    async def create(self, create_kwargs=None): return "fetch", {}
 
    async def execute(self, instance_id, args: dict):
        p = FetchArgs(**args)
        # TODO: replace with real HTTP + boilerplate removal
        body = f"Article at {p.url}\n\n" + "Lorem ipsum " * 600
        text = body[: p.max_chars]
        reward = 0.0
        return ToolResponse(text=text), reward, {}
    async def release(self, instance_id): return

wf_examples/tools/sandbox.py

from pydantic import BaseModel
from verl.tools.base import BaseTool
from verl.tools.schemas import ToolResponse
import re
 
class SandboxArgs(BaseModel):
    code_or_text: str
 
class SandboxRun(BaseTool):
    name = "sandbox_run"
    description = "Run code/tests in sandbox; return summary"
    tool_schema = SandboxArgs
 
    async def create(self, create_kwargs=None): return "sbx", {}
 
    async def execute(self, instance_id, args: dict):
        p = SandboxArgs(**args)
        # TODO: integrate with real container runner + test suite
        passed = "def" in p.code_or_text and "assert" in p.code_or_text
        text = "ALL_TESTS_PASS" if passed else "FAILURES: 3/10 tests failed"
        reward = 1.0 if passed else 0.0
        extra = {"pass_rate": 1.0 if passed else 0.7}
        return ToolResponse(text=text), reward, extra
 
    async def release(self, instance_id): return

wf_examples/tools/static.py

from pydantic import BaseModel
from verl.tools.base import BaseTool
from verl.tools.schemas import ToolResponse
 
class StaticArgs(BaseModel):
    code_or_text: str
 
class StaticCheck(BaseTool):
    name = "static_check"
    description = "Static analysis/lint; returns score"
    tool_schema = StaticArgs
 
    async def create(self, create_kwargs=None): return "lint", {}
 
    async def execute(self, instance_id, args: dict):
        p = StaticArgs(**args)
        score = max(0.0, 1.0 - 0.01 * p.code_or_text.count("TODO"))
        return ToolResponse(text=f"LINT_SCORE={score:.2f}"), score, {"lint_score": score}
 
    async def release(self, instance_id): return

(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 torch
from typing import Dict, Any
 
class 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.


Config: Tools, Agents, Reward, Training

wf_examples/configs/tools_research.yaml

tools:
  - _target_: wf_examples.tools.search.WebSearch
  - _target_: wf_examples.tools.fetch.FetchPage

wf_examples/configs/tools_iterative.yaml

tools:
  - _target_: wf_examples.tools.sandbox.SandboxRun
  - _target_: wf_examples.tools.static.StaticCheck
  - _target_: wf_examples.tools.diff.DiffView  # (optional)

(You can add more tools and split per agent for least confusion.)

wf_examples/configs/interactions.yaml (optional)

interactions:
  scripted_user:
    _target_: verl.interactions.examples.scripted_user.ScriptedUser

wf_examples/configs/train.yaml

trainer:
  project_name: wf_demo
  experiment_name: wf_demo_qwen7b
  nnodes: 1
  n_gpus_per_node: 8
 
actor_rollout_ref:
  model:
    path: Qwen/Qwen2.5-7B-Instruct
  rollout:
    name: vllm_openai
    prompt_length: 4096
    response_length: 1024
    free_cache_engine: false
    agent:
      num_workers: 8
    multi_turn:
      format: "openai"
      max_user_turns: 8
      max_assistant_turns: 8
      max_parallel_calls: 2
      max_tool_response_length: 2000
      tool_response_truncate_side: right
      # IMPORTANT: you'll override this per-run with the agent you use
      tool_config_path: wf_examples/configs/tools_research.yaml
      interaction_config_path: wf_examples/configs/interactions.yaml
 
reward_model:
  enable: true
  enable_resource_pool: false
  _target_: wf_examples.rewards.workflow_reward_manager.WorkflowRewardManager
  reward_kwargs:
    alpha: 1.0
    beta: 0.6
    gamma: 0.4
    delta: 0.6
 
data:
  train_files: /data/train.jsonl
  val_files: /data/val.jsonl
  return_raw_chat: true
  apply_chat_template_kwargs: {}

Dataset Examples

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": {}
}

Iterative row (uses tool_agent_iterative + iterative tools)

{
  "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}
}

Launch (two ways)

Train Research Workflow

python -m verl.trainer.main_ppo \
  +experiment=wf_examples/configs/train.yaml \
  actor_rollout_ref.rollout.multi_turn.tool_config_path=wf_examples/configs/tools_research.yaml \
  data.train_files=/data/research_train.jsonl \
  data.val_files=/data/research_val.jsonl

Train Iterative Workflow

python -m verl.trainer.main_ppo \
  +experiment=wf_examples/configs/train.yaml \
  actor_rollout_ref.rollout.multi_turn.tool_config_path=wf_examples/configs/tools_iterative.yaml \
  data.train_files=/data/iter_train.jsonl \
  data.val_files=/data/iter_val.jsonl

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 raise agent.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.