-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Add per-sample tool filtering to GRPOTrainer via tools column
#5398
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lailanelkoussy
wants to merge
21
commits into
huggingface:main
Choose a base branch
from
lailanelkoussy:feat/per-sample-tool-filtering
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 19 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 6387ff1
Merge upstream/main, resolve conflict in _tokenize_prompts
lailanelkoussy f702d78
Address PR review feedback for per-sample tool filtering in GRPOTrainer
lailanelkoussy 3bf0291
Modify Calculator example for a more realistic but safe version
lailanelkoussy 0891055
Address remaining PR review feedback: backward-compat and VLM fix
lailanelkoussy dae7d7d
Address PR review feedback on per-sample tool filtering
lailanelkoussy 43e3a3b
fix tools_column_name docstring format to match repository convention
lailanelkoussy 1f73687
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy d444f3d
Simplify per-sample tool filtering: auto-detect tools column, remove …
lailanelkoussy d942afd
Merge branch 'feat/per-sample-tool-filtering' of https://github.com/l…
lailanelkoussy 731bf0d
fix IndexError in per-sample tool filtering during evaluation
lailanelkoussy a0200e0
document tools column + environment_factory limitation
lailanelkoussy 9fd5c8a
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy b6a465a
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy aee3b1d
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy f74131f
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy eb0c348
Fix incorrect test assertions for tools column + environment_factory
lailanelkoussy 79367c8
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy bebd006
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy 56a739a
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy 049b300
Merge branch 'main' into feat/per-sample-tool-filtering
lailanelkoussy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
|
|
||
lailanelkoussy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ## 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: +, -, *, /") | ||
|
|
||
|
|
||
lailanelkoussy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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. | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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_toolsentry uses 2-space indentation instead of 4-space, placing it at the top-level YAML list rather than inside thesectionslist of "How-to guides." This causes thetitle: How-to guideson line 44 to detach from its section and become a duplicatetitlekey on the new standalone item. The "How-to guides" section loses its title, and the documentation navigation breaks.