Skip to main content

Triotune

PyTRIO-native training recipes and trainer building blocks.

Triotune handles data preparation, rewards, advantages, token alignment, and training loops through the public PyTRIO client API. PyTRIO supplies model execution, tokenization, sampling, optimization, and checkpoint storage.

中文文档

🗂️ Contents

👋 Introduction

Choose from four PyTRIO-backed trainers:

  • PPO: one asynchronous trainer for PPO, GRPO, RLOO, GSPO, SAPO, CISPO, DAPO, and related presets.
  • DPO: chosen/rejected preference pairs, optional reference-policy scoring, and a local pairwise loss submitted through PyTRIO.
  • SFT: text-only supervised fine-tuning with prompt/completion masking and an asynchronous training path.
  • OPD: on-policy distillation in which a student samples completions and a fixed teacher supplies token-level scores.

PPO, DPO, and OPD include asynchronous training paths where the underlying PyTRIO client supports them. Shared utilities handle text, token-ID, and chat-message inputs, checkpoint naming, and SwanLab metrics.

For multi-turn agents, triotune.agentrl adds tool execution, trajectory export, scoring, and evaluation to the PPO trainer.

📰 News

  • 0.1.3 · 2026-10-27: Multi-turn Agent RL, tool execution, trajectory and reward alignment, OpenAI integration, and bilingual training examples.
  • 0.1.2 · 2026-10-19: Fixed package exports so the PyPI distribution and Python import both use triotune; updated examples and documentation.
  • 0.1.1 · 2026-10-19: Standardized dataset preprocessing, renamed the distribution and source layout to triotune, and added modular PPO, on-policy distillation, and YAML recipe configuration.
  • 0.1.0 · 2026-10-12: Initial release as pytrio-cookbook on PyPI.

🚀 Get Started

📦 Installation

  • Python 3.12 (>=3.12,<3.13)
  • Access to a PyTRIO-compatible training service and the models used by your recipe

Install uv on macOS or Linux:

curl -LsSf https://astral.sh/uv/install.sh | sh

On Windows, run the official installer in PowerShell:

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

Then clone the repository and create the complete locked environment:

git clone https://github.com/SwanHubX/triotune.git
cd triotune
uv python install 3.12
uv sync --locked --all-extras
uv run python -c "import triotune; print(triotune.__name__)"

📚 Quick Start

Run the GSM8K PPO example with its YAML configuration:

uv run python examples/ppo/gsm8k_ppo.py --config examples/ppo/gsm8k_ppo_args.yaml

🔧 Supported Features

🧠 Algorithms

Algorithm Documentation Example Paper
GRPO 📖 Docs 🔧 Example 📄 Paper
PPO 📖 Docs 🔧 Example 📄 Paper
DPO 📖 Docs 🔧 Example 📄 Paper
OPD 📖 Docs 🔧 Example 📄 Paper
SFT 📖 Docs 🔧 Example

📖 Models

PyTRIO currently supports the following models:

  • Qwen/Qwen3.5-4B
  • Qwen/Qwen3.8-27B

🐍 Python API

The minimal GRPO training loop uses the default four generations per prompt:

import asyncio

from triotune.trainer import PPOConfig, PPOTrainer


asyncio.run(
    PPOTrainer(
        model="your-pytrio-model-id",
        args=PPOConfig.for_algorithm("grpo"),
        reward_fn=lambda row, completion, **_: float(row["answer"] in completion),
        train_dataset=[{"messages": "What is 2 + 2?", "answer": "4"}],
    ).train()
)

Agent RL

Install the ppo extra and configure PyTRIO credentials. Define a tool and an episode reward, then train with GRPO:

import asyncio

from triotune import PPOConfig, PPOTrainer
from triotune.agentrl import (
    AgentConfig, AgentTrainingLoop, EpisodeScore, FunctionToolExecutor, function_tool,
)


@function_tool
def add(a: int, b: int) -> int:
    """Add two integers."""
    return a + b


class AnswerScorer:
    async def score(self, row, episode):
        used_tool = any(
            not result.is_error
            for turn in episode.turns for result in turn.tool_results
        )
        success = (
            episode.status == "completed" and used_tool
            and episode.final_text.strip() == row["answer"]
        )
        return EpisodeScore(float(success), success)


async def main():
    trainer = PPOTrainer(
        model="Qwen/Qwen3.5-4B",
        args=PPOConfig.for_algorithm("grpo", batch_size=1, max_steps=1),
        train_dataset=[{
            "messages": [
                {"role": "system", "content": (
                    'Use add. Reply with JSON: '
                    '{"tool_calls":[{"name":"add","arguments":{"a":2,"b":3}}]}. '
                    'After tool_results, reply with {"final":"5"}.'
                )},
                {"role": "user", "content": "What is 2 + 3?"},
            ],
            "answer": "5",
        }],
    )
    agent = AgentConfig()
    snapshot = await trainer.create_sampling_snapshot(stop=agent.stop)
    workflow = agent.build_workflow(
        tokenizer=snapshot.tokenizer,
        tools=FunctionToolExecutor([add]),
        scorer=AnswerScorer(),
    )
    state = await AgentTrainingLoop(trainer, workflow, config=agent).train()
    print(state.checkpoint_path)


asyncio.run(main())

See the AgentRL guide for evaluation and custom workflows.

🧩 Data Contracts

The trainers accept:

  • a string;
  • a non-empty list of token IDs; or
  • a non-empty list of {role, content} chat messages.

Algorithm-specific fields are:

  • GRPO: messages and a string answer used by the reward function;
  • DPO: shared messages, plus chosen and rejected responses;
  • SFT: text, messages, prompt/completion, or pre-tokenized input_ids (optionally with labels);
  • OPD: prompt rows; the teacher scores completions sampled by the student.

See the trainer guide for validation rules and complete JSONL examples.

Token Usage Metrics

PyTRIO records training, prefill, and sampler tokens. Triotune reports these counts and their running totals in SwanLab, using PyTRIO's sampling counters when available and submitted compute requests for training usage.

Fallback counting, failed requests, or retries may cause differences. PyTRIO's server-side records are authoritative.

Documentation

🗃 Repository Layout

triotune/
├── api/           # Public configuration and client contracts
├── agentrl/       # Agent execution, trajectories, and training loops
├── dataset/       # Shared validation and tokenization
├── trainer/       # Algorithm trainers and components
└── utils/         # Shared runtime utilities

🎯 Current Scope

Triotune targets text-only training through PyTRIO. Custom model modules must implement PyTRIO's public client contract to use the trainer interfaces. Web UI, Megatron integration, multimodal training, and a general plugin registry are outside the current scope.

Metadata

Release files for triotune 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for triotune 0.1.3
File Size Uploaded Provenance Actions
triotune-0.1.3.tar.gz 252.9 kB With provenance Details for triotune-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for triotune 0.1.3
File Interpreter ABI Platform Actions
triotune-0.1.3-py3-none-any.whl Python 3 none any Details for triotune-0.1.3-py3-none-any.whl

Total release size: 545.1 kB

Release files / triotune-0.1.3.tar.gz

Download URL triotune-0.1.3.tar.gz
Size 252.9 kB
Tags Source
SHA-256 checksum
How to use checksums
7219a1d289bd0103f300dca4c53b3fdb2d12d00dfe667941bedb22f83cc9171b
BLAKE2b-256 checksum
How to use checksums
f10b1d61f89ab5c00841892f3a03ea1629d1b934ea8abbc6b13a3fd21df6dcfe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Release files / triotune-0.1.3-py3-none-any.whl

Download URL triotune-0.1.3-py3-none-any.whl
Size 292.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
165de3bc921c1ceeb359f33906de735bce0751ebd1b768abf39f0c113a940362
BLAKE2b-256 checksum
How to use checksums
4f99d23efbe3786ced24533ec13be37e3d813045076cfc8ff51beb99f04e5be7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Security for triotune 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for triotune-0.1.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page