Skip to content
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
7d2e510
feat: add per-sample tool filtering to GRPOTrainer via tools_column_name
lailanelkoussy Mar 27, 2026
6387ff1
Merge upstream/main, resolve conflict in _tokenize_prompts
lailanelkoussy Mar 27, 2026
f702d78
Address PR review feedback for per-sample tool filtering in GRPOTrainer
lailanelkoussy Mar 28, 2026
3bf0291
Modify Calculator example for a more realistic but safe version
lailanelkoussy Mar 28, 2026
0891055
Address remaining PR review feedback: backward-compat and VLM fix
lailanelkoussy Mar 28, 2026
dae7d7d
Address PR review feedback on per-sample tool filtering
lailanelkoussy Mar 28, 2026
43e3a3b
fix tools_column_name docstring format to match repository convention
lailanelkoussy Mar 28, 2026
1f73687
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy Mar 28, 2026
d444f3d
Simplify per-sample tool filtering: auto-detect tools column, remove …
lailanelkoussy Mar 30, 2026
d942afd
Merge branch 'feat/per-sample-tool-filtering' of https://github.com/l…
lailanelkoussy Mar 30, 2026
731bf0d
fix IndexError in per-sample tool filtering during evaluation
lailanelkoussy Mar 30, 2026
a0200e0
document tools column + environment_factory limitation
lailanelkoussy Mar 30, 2026
9fd5c8a
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy Mar 30, 2026
b6a465a
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy Mar 30, 2026
aee3b1d
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy Mar 31, 2026
f74131f
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy Mar 31, 2026
eb0c348
Fix incorrect test assertions for tools column + environment_factory
lailanelkoussy Apr 1, 2026
79367c8
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy Apr 1, 2026
bebd006
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy Apr 1, 2026
56a739a
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy Apr 1, 2026
049b300
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy Apr 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/_toctree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
title: Distributing Training
- local: use_model
title: Using Trained Models
- local: per_sample_tools
title: Per-Sample Tool Filtering
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong toctree indentation breaks How-to guides section

Medium Severity

The new per_sample_tools entry uses 2-space indentation instead of 4-space, placing it at the top-level YAML list rather than inside the sections list of "How-to guides." This causes the title: How-to guides on line 44 to detach from its section and become a duplicate title key on the new standalone item. The "How-to guides" section loses its title, and the documentation navigation breaks.

Fix in Cursor Fix in Web

title: How-to guides
- sections:
- local: deepspeed_integration
Expand Down
108 changes: 108 additions & 0 deletions docs/source/per_sample_tools.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Per-Sample Tool Filtering in GRPOTrainer

## Motivation

In many agentic settings, different training samples require different subsets of tools.
For example, a math question might only need a `calculator`, while a translation task
might only need a `translator`. Exposing all tools on every sample can confuse the model
and dilute the training signal.

`GRPOTrainer` automatically detects a `tools` column in your dataset and uses it to restrict
**which tools are available per sample**, drawn from the global `tools` pool.

## How It Works

1. **Global tool pool** — You pass the full set of tools to the trainer via `tools=[...]` as before.
2. **Per-sample tool column** — Your dataset includes a `"tools"` column containing a list of tool
**names** (strings matching `tool.__name__`) allowed for each sample.
3. **Automatic filtering** — For each rollout, only the specified tools appear in the model's
system prompt (chat template) and are available for execution. If the column value is `None`
for a sample, all tools are used as a fallback.

## Example

```python
from datasets import Dataset
from trl import GRPOTrainer, GRPOConfig


# Define tool functions
def calculator(number_a: float, operation: str, number_b: float) -> str:
"""Perform a basic arithmetic operation on two numbers.

Args:
number_a: The first operand.
operation: The operation to perform. One of '+', '-', '*', '/'.
number_b: The second operand.

Returns:
The result of the operation as a string.

Raises:
ValueError: If the operation is not supported or division by zero is attempted.
"""
try:
number_a = float(number_a)
except (TypeError, ValueError):
raise TypeError(f"number_a must be convertible to a number, got {type(number_a).__name__!r}")
try:
number_b = float(number_b)
except (TypeError, ValueError):
raise TypeError(f"number_b must be convertible to a number, got {type(number_b).__name__!r}")
if operation == "+":
return str(number_a + number_b)
elif operation == "-":
return str(number_a - number_b)
elif operation == "*":
return str(number_a * number_b)
elif operation == "/":
if number_b == 0:
raise ValueError("Division by zero is not allowed.")
return str(number_a / number_b)
else:
raise ValueError(f"Unsupported operation '{operation}'. Use one of: +, -, *, /")


def translator(text: str, target_language: str) -> str:
"""Translate text to a target language.

Args:
text: The text to translate.
target_language: ISO language code, e.g. 'fr', 'es', 'de'.

Returns:
The translated text.
"""
# Placeholder — in practice, call a translation API
return f"[{target_language}] {text}"


# Build dataset with per-sample tool column
dataset = Dataset.from_dict({
"prompt": [
[{"role": "user", "content": "What is 123 * 456?"}],
[{"role": "user", "content": "Translate 'good morning' to French."}],
[{"role": "user", "content": "Compute 2^10 and translate the result to Spanish."}],
],
"tools": [
["calculator"], # only calculator available
["translator"], # only translator available
["calculator", "translator"], # both available
],
})

# The trainer automatically detects the "tools" column and applies per-sample filtering
trainer = GRPOTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
reward_funcs=my_reward,
tools=[calculator, translator],
train_dataset=dataset,
)

trainer.train()
```

## Backward Compatibility

When the dataset has no `tools` column, behavior is identical to the existing API — all
tools in the `tools` list are used for every sample.
Loading