CoolFace
Apppublic

bird-of-paradise/ReTool-Implementation

sourceHugging Facemitupdated 1y agoView on Hugging Face
1likes
App README

ReTool: Reinforcement Learning for Strategic Tool Use in LLMs

A PyTorch implementation of ReTool from the paper "ReTool: Reinforcement Learning for Strategic Tool Use in LLMs" by Feng et al. (2025).

ReTool enhances long-form reasoning by integrating code interpreter execution into the RL training loop, enabling models to learn when and how to invoke computational tools for mathematical problem solving.

<div align="center"> <img src="assets/retoolrolloutprocess.png" alt="ReTool Rollout Process" width="80%"> <p><em>Figure 2: Comparison of standard text-based RL vs ReTool's code-integrated training process</em></p> </div>

๐Ÿš€ Key Features

  • โ€”Multi-turn Generation: Dynamic code execution during reasoning with KV-cache optimization
  • โ€”Strategic Tool Use: Learns when and how to invoke code interpreters through RL
  • โ€”Interpreter Masking: Excludes external tool outputs from gradient computation
  • โ€”Production Ready: Built on HuggingFace Transformers with proper batching and distributed training support

๐Ÿ“Š Performance

<div align="center"> <img src="assets/aime_results.png" alt="AIME Results" width="70%"> <p><em>Figure 1: ReTool achieves 67% accuracy on AIME 2024, significantly outperforming text-based RL (40%)</em></p> </div>

๐Ÿ› ๏ธ Installation

bash
git clone https://github.com/yourusername/retool-implementation.git
cd  retool-implementation/scr
pip install -r requirements.txt

๐Ÿšง Current Status

This is a research implementation based on the ReTool paper. The core components are implemented but not yet fully tested.

What's Implemented โœ…

  • โ€”Multi-turn generation with KV-cache optimization
  • โ€”Interpreter token masking for RL training
  • โ€”Modified PPO loss computation
  • โ€”Complete training pipeline structure
  • โ€”Proper tensor handling and batching

What Needs Testing/Integration ๐Ÿ”ง

  • โ€”End-to-end training verification
  • โ€”Code execution sandbox integration
  • โ€”Edge case handling for truncated sequences
  • โ€”Memory optimization for large models

For Researchers & Developers

This implementation serves as a foundation for:

  • โ€”Understanding ReTool's architecture
  • โ€”Building upon the multi-turn generation approach
  • โ€”Integrating custom code execution environments
  • โ€”Extending to other tool-use scenarios

๐Ÿ“Š Dataset Format

Your dataset should contain dictionaries with:

python
{
    "prompt": "Solve this math problem: ...",
    "answer": "42"  # Ground truth for reward computation
}

๐Ÿ” How It Works

  1. 1.Multi-turn Generation: Model generates reasoning step-by-step
  2. 2.Code Detection: When </code> is generated, extract and execute code
  3. 3.Tool Integration: Append <interpreter>result</interpreter> to context
  4. 4.Continued Reasoning: Model continues with tool feedback
  5. 5.Reward Computation: Binary reward based on final answer correctness
  6. 6.RL Training: PPO updates exclude interpreter tokens from loss

โš™๏ธ Key Components

ReToolTrainer Class

  • โ€”_retool_generate_with_interpreter(): Multi-turn generation with tool execution
  • โ€”_create_interpreter_mask(): Creates masks for excluding tool outputs
  • โ€”_compute_loss(): Modified PPO loss with interpreter masking
  • โ€”_compute_rewards_and_advantages(): Binary reward computation

Configuration Options

python
trainer = ReToolTrainer(
    # ... model and data ...
    max_turns=10,              # Maximum reasoning turns
    temperature=0.7,           # Generation temperature
    max_completion_length=1024, # Max tokens per turn
    mask_truncated_completions=True,  # Handle incomplete sequences
)

๐Ÿ’ก Usage Example (Conceptual)

python
from retool_trainer import ReToolTrainer
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments

# This shows the intended API - full testing in progress
trainer = ReToolTrainer(
    model=AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-32B-Instruct"),
    processing_class=AutoTokenizer.from_pretrained("Qwen/Qwen2.5-32B-Instruct"),
    args=TrainingArguments(...),
    train_dataset=your_math_dataset,
    max_turns=10,
)

# trainer.train()  # Full integration testing in progress

๐Ÿ“ˆ Results From Paper

  • โ€”AIME 2024: 67% accuracy (vs 40% text-based RL)
  • โ€”AIME 2025: 49.3% accuracy (vs 36.7% text-based RL)
  • โ€”Efficiency: Converges in 400 steps vs 1080 for baseline
  • โ€”Token Efficiency: 40% reduction in response length

๐Ÿšง Limitations & TODOs

  • โ€”[ ] Code execution sandbox integration
  • โ€”[ ] Support for multiple reward functions
  • โ€”[ ] Advanced error handling for malformed code
  • โ€”[ ] Distributed training optimizations
  • โ€”[ ] Tool selection beyond code interpreter
  • โ€”[ ] [June 2, 2025 update] Add DAPO trainer

๐Ÿ“š Citation

bibtex
@article{feng2025retool,
  title={ReTool: Reinforcement Learning for Strategic Tool Use in LLMs},
  author={Feng, Jiazhan and Huang, Shijue and Qu, Xingwei and Zhang, Ge and Qin, Yujia and Zhong, Baoquan and Jiang, Chengquan and Chi, Jinxin and Zhong, Wanjun},
  journal={arXiv preprint arXiv:2504.11536},
  year={2025}
}

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿค Collaboration welcome: Looking for teammates with complementary skills:

  • โ€”Systems engineers: Distributed sandbox architecture with load balancing
  • โ€”Compute sponsors: Academic institutions or cloud providers for training runs
  • โ€”Experimenters: End-to-end validation and benchmarking on mathematical reasoning tasks

๐Ÿ™ Acknowledgments

  • โ€”Original paper authors for the ReTool framework
  • โ€”HuggingFace team for the transformers library
  • โ€”TRL team for GRPO implementation patterns

<div align="center"> <strong>Built with โค๏ธ for advancing AI reasoning capabilities</strong> </div>