Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c935497d71 | ||
|
|
cd2f3daeb2 | ||
|
|
897b935cae | ||
|
|
81f9e9512b | ||
|
|
d4385029c8 | ||
|
|
c654dc1d4d | ||
|
|
6ba37c2c21 |
@@ -14,7 +14,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
|
||||
@@ -28,23 +28,20 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
- name: Run unit tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
|
||||
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
|
||||
# This is to allow running tests on forks without WANDB_API_KEY
|
||||
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
@@ -63,21 +60,30 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- test: base
|
||||
- test: reverse_text_sft
|
||||
runner: vm
|
||||
pytest_args: "tests/integration -m gpu --ignore=tests/integration/test_rl_lora.py --ignore=tests/integration/test_rl_multi_run_lora.py --ignore=tests/integration/test_benchmark_regression.py --ignore=tests/integration/test_alphabet_sort.py"
|
||||
- test: rl_lora
|
||||
pytest_args: "tests/integration/test_reverse_text_sft.py"
|
||||
- test: reverse_text_sft_lora
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_rl_lora.py -m gpu"
|
||||
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
|
||||
- test: reverse_text
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text.py"
|
||||
- test: alphabet_sort
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py -m gpu"
|
||||
- test: rl_multi_run
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py"
|
||||
- test: reverse_text_lora
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_lora.py"
|
||||
- test: reverse_text_moe
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_moe.py"
|
||||
- test: reverse_text_multi_run
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_rl_multi_run_lora.py -m gpu"
|
||||
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py -m gpu"
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
@@ -87,23 +93,20 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
- name: Run integration tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
|
||||
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
|
||||
# This is to allow running tests on forks without WANDB_API_KEY
|
||||
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
|
||||
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
|
||||
@@ -111,4 +114,4 @@ jobs:
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
VLLM_WORKER_MULTIPROC_METHOD: spawn
|
||||
run: uv run pytest ${{ matrix.pytest_args }}
|
||||
run: uv run pytest -vvs ${{ matrix.pytest_args }}
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
|
||||
- name: Build matrix from nightly test files
|
||||
id: build-matrix
|
||||
@@ -75,7 +75,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
|
||||
@@ -24,6 +24,12 @@ jobs:
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: crazy-max/ghaction-docker-meta@v2
|
||||
|
||||
@@ -16,8 +16,9 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
# Submodules are excluded from ruff via pyproject.toml; no need to fetch them.
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Run ruff
|
||||
uses: astral-sh/ruff-action@v3
|
||||
with:
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
.vscode/*
|
||||
.claude/scheduled_tasks.lock
|
||||
*.ipynb
|
||||
*.jsonl
|
||||
configs/endpoints.py
|
||||
@@ -200,4 +201,4 @@ debug_I2_zero_band
|
||||
|
||||
outputs/
|
||||
|
||||
third_party/
|
||||
third_party/
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
[submodule "verifiers"]
|
||||
path = deps/verifiers
|
||||
url = git@github.com:PrimeIntellect-ai/verifiers.git
|
||||
[submodule "renderers"]
|
||||
path = deps/renderers
|
||||
url = git@github.com:PrimeIntellect-ai/renderers.git
|
||||
[submodule "research-environments"]
|
||||
path = deps/research-environments
|
||||
url = git@github.com:PrimeIntellect-ai/research-environments.git
|
||||
[submodule "configs/private"]
|
||||
path = configs/private
|
||||
url = git@github.com:PrimeIntellect-ai/research-configs.git
|
||||
@@ -43,6 +43,7 @@ COPY uv.lock /app/uv.lock
|
||||
COPY README.md /app/README.md
|
||||
COPY src/ /app/src/
|
||||
COPY packages/ /app/packages/
|
||||
COPY deps/ /app/deps/
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
|
||||
@@ -91,14 +91,20 @@ git clone https://github.com/PrimeIntellect-ai/prime-rl.git
|
||||
cd prime-rl
|
||||
```
|
||||
|
||||
2. Install [uv](https://docs.astral.sh/uv/)
|
||||
2. Initialize submodules
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
```
|
||||
|
||||
3. Install [uv](https://docs.astral.sh/uv/)
|
||||
|
||||
```bash
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
source $HOME/.local/bin/env
|
||||
```
|
||||
|
||||
3. Install dependencies from the lock file
|
||||
4. Install dependencies from the lock file
|
||||
|
||||
```bash
|
||||
uv sync --all-extras
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 10
|
||||
max_steps = 5
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
@@ -1,29 +0,0 @@
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
num_infer_gpus = 1
|
||||
num_train_gpus = 1
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
|
||||
[inference]
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
max_steps = 25
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 20
|
||||
resume_step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 20
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
max_steps = 25
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 20
|
||||
resume_step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 20
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
+3
@@ -9,6 +9,9 @@ name = "samsja/mini-glm-moe"
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
+1
@@ -1,6 +1,7 @@
|
||||
max_steps = 10
|
||||
|
||||
[ckpt]
|
||||
resume_step = 5
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
max_steps = 20
|
||||
max_steps = 5
|
||||
|
||||
[ckpt]
|
||||
resume_step = 10
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
max_steps = 20
|
||||
max_steps = 10
|
||||
|
||||
[ckpt]
|
||||
resume_step = 10
|
||||
resume_step = 5
|
||||
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 10
|
||||
max_steps = 5
|
||||
|
||||
[ckpt]
|
||||
|
||||
Submodule
+1
Submodule configs/private added at 74c1330008
+1
Submodule deps/renderers added at 17d0584f87
+1
Submodule deps/research-environments added at d141472268
+1
Submodule deps/verifiers added at 711a7c705e
@@ -6,6 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
RendererConfig,
|
||||
SlurmConfig,
|
||||
TrainerLogConfig,
|
||||
WandbConfig,
|
||||
@@ -172,6 +173,21 @@ class SFTConfig(BaseConfig):
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The renderer configuration (only used when use_renderer=True)
|
||||
renderer: RendererConfig = RendererConfig()
|
||||
|
||||
use_renderer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"If True, tokenize SFT samples through the `renderers` library "
|
||||
"(single render() + message_indices mask) instead of the default "
|
||||
"`build_incremental_token_mask` path. Required for chat templates "
|
||||
"that render position-dependently (e.g. Qwen3, Qwen3.5)."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
# The data configuration
|
||||
data: DataConfig = SFTDataConfig()
|
||||
|
||||
@@ -357,6 +373,55 @@ class SFTConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_vs_vlm(self):
|
||||
if self.use_renderer and self.model.vlm is not None:
|
||||
raise ValueError(
|
||||
"use_renderer is not supported for VLMs. The renderer tokenizes "
|
||||
"text-only message dicts client-side and cannot handle image inputs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_args(self):
|
||||
# pool_size is orchestrator-only. An in-process renderer pool exists
|
||||
# to amortize tokenization across concurrent rollouts in the
|
||||
# orchestrator (many async requests render at once, HF fast
|
||||
# tokenizers release the GIL during Rust encoding, so a pool of N
|
||||
# tokenizer copies parallelizes well). SFT has no such concurrency:
|
||||
# the StatefulDataLoader is constructed with num_workers=0, so the
|
||||
# main process tokenizes one example at a time, between training
|
||||
# steps. Across DP, each rank already owns its own renderer — an
|
||||
# implicit pool of size world_size. Pooling within a rank gives
|
||||
# nothing on top of that. Reject so callers don't silently set a
|
||||
# knob that does nothing; if SFT tokenization ever becomes a
|
||||
# bottleneck the fix is num_workers on the dataloader, not a pool.
|
||||
if self.renderer.pool_size is not None:
|
||||
raise ValueError(
|
||||
f"renderer.pool_size={self.renderer.pool_size!r} is only used by the orchestrator. "
|
||||
"SFT tokenizes synchronously (num_workers=0) and already gets one renderer per DP "
|
||||
"rank — an in-process pool adds nothing. If tokenization is a bottleneck, raise "
|
||||
"num_workers on the dataloader instead."
|
||||
)
|
||||
|
||||
if self.use_renderer:
|
||||
return self
|
||||
|
||||
renderer_args_set = []
|
||||
if self.renderer.name != "auto":
|
||||
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
|
||||
if self.renderer.tool_parser is not None:
|
||||
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
|
||||
if self.renderer.reasoning_parser is not None:
|
||||
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
|
||||
|
||||
if renderer_args_set:
|
||||
raise ValueError(
|
||||
"Renderer-specific args set without use_renderer=True: "
|
||||
f"{', '.join(renderer_args_set)}. Either enable the renderer or remove these knobs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
|
||||
+90
-52
@@ -31,7 +31,7 @@ dependencies = [
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers",
|
||||
"renderers==0.1.6",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
"flash-linear-attention",
|
||||
@@ -59,20 +59,33 @@ flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"reverse-text",
|
||||
"alphabet-sort",
|
||||
"wiki-search",
|
||||
"math-python",
|
||||
"math-env",
|
||||
"code-env",
|
||||
"science-env",
|
||||
"logic-env",
|
||||
"color-codeword",
|
||||
"math500",
|
||||
"aime2024",
|
||||
"aime2025",
|
||||
"mini_swe_agent_plus",
|
||||
"deepdive"
|
||||
"alphabet-sort",
|
||||
"code-env",
|
||||
"color-codeword",
|
||||
"deepdive",
|
||||
"gpqa",
|
||||
"hle",
|
||||
"ifeval",
|
||||
"livecodebench",
|
||||
"logic-env",
|
||||
"math-env",
|
||||
"math-python",
|
||||
"math500",
|
||||
"mini-swe-agent-plus",
|
||||
"mini-swe-agent-plus-rlm",
|
||||
"mmlu-pro",
|
||||
"opencode-cp",
|
||||
"opencode-deepdive",
|
||||
"opencode-math",
|
||||
"opencode-science",
|
||||
"opencode-swe",
|
||||
"reverse-text",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
"wiki-search",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
@@ -109,7 +122,38 @@ dev = [
|
||||
|
||||
|
||||
[tool.uv.workspace]
|
||||
members = ["packages/*"]
|
||||
members = [
|
||||
"packages/prime-rl-configs",
|
||||
"deps/verifiers",
|
||||
"deps/renderers",
|
||||
"deps/verifiers/environments/alphabet_sort",
|
||||
"deps/verifiers/environments/math_python",
|
||||
"deps/verifiers/environments/reverse_text",
|
||||
"deps/verifiers/environments/wiki_search",
|
||||
"deps/research-environments/environments/aime2024",
|
||||
"deps/research-environments/environments/aime2025",
|
||||
"deps/research-environments/environments/code_env",
|
||||
"deps/research-environments/environments/color_codeword",
|
||||
"deps/research-environments/environments/deepdive",
|
||||
"deps/research-environments/environments/gpqa",
|
||||
"deps/research-environments/environments/hle",
|
||||
"deps/research-environments/environments/ifeval",
|
||||
"deps/research-environments/environments/livecodebench",
|
||||
"deps/research-environments/environments/logic_env",
|
||||
"deps/research-environments/environments/math500",
|
||||
"deps/research-environments/environments/math_env",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus_rlm",
|
||||
"deps/research-environments/environments/mmlu_pro",
|
||||
"deps/research-environments/environments/opencode_cp",
|
||||
"deps/research-environments/environments/opencode_deepdive",
|
||||
"deps/research-environments/environments/opencode_math",
|
||||
"deps/research-environments/environments/opencode_science",
|
||||
"deps/research-environments/environments/opencode_swe",
|
||||
"deps/research-environments/environments/science_env",
|
||||
"deps/research-environments/environments/simpleqa_verified",
|
||||
"deps/research-environments/environments/tau2_bench",
|
||||
]
|
||||
|
||||
[tool.uv]
|
||||
exclude-newer = "7 days"
|
||||
@@ -125,35 +169,20 @@ override-dependencies = [
|
||||
"nvidia-cudnn-cu12>=9.15",
|
||||
"nvidia-cutlass-dsl>=4.4.1",
|
||||
"transformers>=5.1.0.dev0",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# we want latest vllm, remove next patch
|
||||
vllm = false
|
||||
flash_attn_3 = false
|
||||
# Self-vendored packages on our primeintellect index
|
||||
reverse-text = false
|
||||
alphabet-sort = false
|
||||
wiki-search = false
|
||||
math-python = false
|
||||
math-env = false
|
||||
code-env = false
|
||||
science-env = false
|
||||
logic-env = false
|
||||
color-codeword = false
|
||||
math500 = false
|
||||
aime2024 = false
|
||||
aime2025 = false
|
||||
deepdive = false
|
||||
mini_swe_agent_plus = false
|
||||
# PrimeIntellect-published on PyPI (trusted publisher)
|
||||
prime = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
verifiers = false
|
||||
renderers = false
|
||||
vllm-router = false
|
||||
dion = false
|
||||
pydantic-config = false
|
||||
@@ -163,10 +192,38 @@ nixl-cu12 = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { workspace = true }
|
||||
verifiers = { workspace = true }
|
||||
renderers = { workspace = true }
|
||||
aime2024 = { workspace = true }
|
||||
aime2025 = { workspace = true }
|
||||
alphabet-sort = { workspace = true }
|
||||
code-env = { workspace = true }
|
||||
color-codeword = { workspace = true }
|
||||
deepdive = { workspace = true }
|
||||
gpqa = { workspace = true }
|
||||
hle = { workspace = true }
|
||||
ifeval = { workspace = true }
|
||||
livecodebench = { workspace = true }
|
||||
logic-env = { workspace = true }
|
||||
math-env = { workspace = true }
|
||||
math-python = { workspace = true }
|
||||
math500 = { workspace = true }
|
||||
mini-swe-agent-plus = { workspace = true }
|
||||
mini-swe-agent-plus-rlm = { workspace = true }
|
||||
mmlu-pro = { workspace = true }
|
||||
opencode-cp = { workspace = true }
|
||||
opencode-deepdive = { workspace = true }
|
||||
opencode-math = { workspace = true }
|
||||
opencode-science = { workspace = true }
|
||||
opencode-swe = { workspace = true }
|
||||
reverse-text = { workspace = true }
|
||||
science-env = { workspace = true }
|
||||
simpleqa-verified = { workspace = true }
|
||||
tau2-bench = { workspace = true }
|
||||
wiki-search = { workspace = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "aa428f3" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
|
||||
@@ -177,20 +234,6 @@ vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
reverse-text = { index = "primeintellect" }
|
||||
alphabet-sort = { index = "primeintellect" }
|
||||
wiki-search = { index = "primeintellect" }
|
||||
math-python = { index = "primeintellect" }
|
||||
math-env = { index = "primeintellect" }
|
||||
code-env = { index = "primeintellect" }
|
||||
science-env = { index = "primeintellect" }
|
||||
logic-env = { index = "primeintellect" }
|
||||
color-codeword = { index = "primeintellect" }
|
||||
math500 = { index = "primeintellect" }
|
||||
aime2024 = { index = "primeintellect" }
|
||||
aime2025 = { index = "primeintellect" }
|
||||
deepdive = { index = "primeintellect" }
|
||||
mini_swe_agent_plus = { index = "primeintellect" }
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
@@ -205,17 +248,11 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
[tool.uv.extra-build-variables]
|
||||
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "primeintellect"
|
||||
url = "https://hub.primeintellect.ai/primeintellect/simple/"
|
||||
explicit = true
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128"
|
||||
url = "https://download.pytorch.org/whl/cu128"
|
||||
explicit = true
|
||||
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu128"
|
||||
@@ -233,6 +270,7 @@ known-first-party = ["prime_rl"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
extend-exclude = ["deps"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
addopts = "--strict-markers"
|
||||
|
||||
@@ -66,6 +66,29 @@ ensure_known_hosts() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Initialize each submodule independently so that a missing private repo
|
||||
# (e.g. configs/private when the user lacks access) does not abort the install.
|
||||
init_submodules() {
|
||||
if [ ! -f .gitmodules ]; then
|
||||
return 0
|
||||
fi
|
||||
local paths failures
|
||||
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
|
||||
failures=()
|
||||
for path in $paths; do
|
||||
log_info "Initializing submodule: ${path}"
|
||||
if git submodule update --init --recursive -- "$path"; then
|
||||
:
|
||||
else
|
||||
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
|
||||
failures+=("$path")
|
||||
fi
|
||||
done
|
||||
if [ "${#failures[@]}" -gt 0 ]; then
|
||||
log_warn "Skipped submodules: ${failures[*]}"
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
assert_supported_platform
|
||||
|
||||
@@ -98,6 +121,13 @@ main() {
|
||||
cd ${REPO_ID}
|
||||
fi
|
||||
|
||||
if ! has_ssh_access; then
|
||||
git config url."https://github.com/".insteadOf "git@github.com:"
|
||||
fi
|
||||
|
||||
log_info "Initializing submodules..."
|
||||
init_submodules
|
||||
|
||||
log_info "Installing uv..."
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
|
||||
|
||||
@@ -177,4 +177,5 @@ In TOML, an empty section header does the same:
|
||||
- `src/prime_rl/utils/config.py` — re-exports `BaseConfig` and `cli` from pydantic_config
|
||||
- `src/prime_rl/configs/` — all domain-specific config classes
|
||||
- `configs/debug/` — minimal debug configs for testing
|
||||
- `configs/private/` — private configs via git submodule (internal only)
|
||||
- `examples/` — full example configs for various tasks
|
||||
|
||||
@@ -88,4 +88,5 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
- `src/prime_rl/entrypoints/` — top-level entrypoints (`rl`, `sft`, `inference`)
|
||||
- `src/prime_rl/configs/` — all config classes
|
||||
- `configs/debug/` — minimal configs for quick testing
|
||||
- `configs/private/` — private configs submodule (if access granted)
|
||||
- `examples/` — full example configs for various tasks
|
||||
|
||||
@@ -5,13 +5,37 @@ description: How to install prime-rl and its optional dependencies. Use when set
|
||||
|
||||
# Installation
|
||||
|
||||
## Cloning
|
||||
|
||||
prime-rl is a monorepo with submodules. Clone the repo first, then initialize submodules explicitly:
|
||||
|
||||
```bash
|
||||
git clone git@github.com:PrimeIntellect-ai/prime-rl.git
|
||||
cd prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
```
|
||||
|
||||
For an existing clone, initialize the public submodules by passing explicit paths:
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
```
|
||||
|
||||
Do **not** use `git submodule update --init --recursive` without explicit paths — it will also attempt to clone `configs/private` (a private submodule) and fail with "Repository not found" for users without access. Git will retry the clone once internally before aborting, which is expected behavior.
|
||||
|
||||
The public submodules live under `deps/`: `deps/verifiers/`, `deps/renderers/`, and `deps/research-environments/`. Each is also a uv workspace member, so source edits inside them apply to the prime-rl venv without re-sync.
|
||||
|
||||
The install script (`scripts/install.sh`) handles the private submodule gracefully — it iterates each submodule individually so a failed `configs/private` init does not abort the rest.
|
||||
|
||||
## Basic
|
||||
```bash
|
||||
uv sync # core dependencies only
|
||||
uv sync --group dev # dev tools: pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: includes flash-attn, flash-attn-cute, etc.
|
||||
uv sync --all-extras # recommended: includes envs, flash-attn, flash-attn-cute, etc.
|
||||
```
|
||||
|
||||
The `envs` extra installs the env packages listed in `pyproject.toml > [tool.uv.workspace] members`. Adding a new env means adding it there, in the `envs` extra, and in `[tool.uv.sources]`.
|
||||
|
||||
## Advanced
|
||||
|
||||
### Mamba-SSM (NemotronH models)
|
||||
|
||||
@@ -145,6 +145,8 @@ These tell you whether training is healthy or diverging.
|
||||
|--------|--------|-------------|
|
||||
| `mismatch_kl/mean` | trainer | KL divergence between trainer and (old) inference policy |
|
||||
| `entropy/mean` | trainer | policy entropy |
|
||||
| `masked_advantage_positive/mean` | trainer | fraction of DPPO-masked trainable tokens with positive advantage (W&B) |
|
||||
| `masked_advantage_negative/mean` | trainer | fraction of DPPO-masked trainable tokens with negative advantage (W&B) |
|
||||
| `optim/grad_norm` | trainer | gradient norm — spikes may precede divergence |
|
||||
|
||||
#### Performance
|
||||
|
||||
@@ -349,10 +349,10 @@ def rl_local(config: RLConfig):
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Monitor all processes for failures
|
||||
logger.success("Startup complete. Showing trainer logs...")
|
||||
logger.success("Startup complete. Showing orchestrator logs...")
|
||||
|
||||
tail_process = Popen(
|
||||
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
|
||||
f"tail -F '{log_dir / 'orchestrator.log'}'",
|
||||
shell=True,
|
||||
)
|
||||
processes.append(tail_process)
|
||||
|
||||
@@ -91,7 +91,8 @@ def postprocess(
|
||||
pass_configs={
|
||||
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
|
||||
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
|
||||
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: True,
|
||||
# Avoid TileLang MLA backward NaNs: https://github.com/tile-ai/tilelang/issues/2199
|
||||
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: False,
|
||||
},
|
||||
)
|
||||
def bwd(
|
||||
|
||||
@@ -127,11 +127,14 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
probs_diff = trainer_probs - inference_probs
|
||||
dppo_invalid_mask_high = probs_diff > loss_config.dppo_mask_high
|
||||
dppo_invalid_mask_low = probs_diff < -loss_config.dppo_mask_low
|
||||
dppo_invalid_mask = torch.where(advantages > 0, dppo_invalid_mask_high, dppo_invalid_mask_low)
|
||||
positive_advantages = advantages > 0
|
||||
negative_advantages = advantages < 0
|
||||
dppo_invalid_mask = torch.where(positive_advantages, dppo_invalid_mask_high, dppo_invalid_mask_low)
|
||||
|
||||
is_masked = dppo_invalid_mask
|
||||
is_masked_high = (advantages > 0) & dppo_invalid_mask_high
|
||||
is_masked_low = (advantages < 0) & dppo_invalid_mask_low
|
||||
is_masked_high = positive_advantages & dppo_invalid_mask_high
|
||||
is_masked_low = negative_advantages & dppo_invalid_mask_low
|
||||
drop_mask = loss_mask & is_masked
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
@@ -156,6 +159,8 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
|
||||
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
|
||||
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
|
||||
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
|
||||
}
|
||||
if teacher_kl is not None:
|
||||
metrics["teacher_kl"] = _safe_mean(teacher_kl, loss_mask)
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import Literal, TypedDict, cast
|
||||
import torch
|
||||
from datasets import Dataset, interleave_datasets, load_dataset
|
||||
from jaxtyping import Bool, Int
|
||||
from renderers.base import Renderer, build_training_sample
|
||||
from torch import Tensor
|
||||
from torch.distributed.checkpoint.stateful import Stateful
|
||||
from torch.utils.data import IterableDataset, get_worker_info
|
||||
@@ -127,6 +128,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
loss_mask_config: LossMaskConfig = LossMaskConfig(),
|
||||
max_examples: int | None = None,
|
||||
max_epochs: int | None = None,
|
||||
renderer: Renderer | None = None,
|
||||
):
|
||||
super().__init__()
|
||||
self.logger = get_logger()
|
||||
@@ -139,6 +141,8 @@ class SFTDataset(StatefulIterableDataset):
|
||||
self.loss_mask_config = loss_mask_config
|
||||
self.max_examples = max_examples
|
||||
self.max_epochs = max_epochs
|
||||
self.renderer = renderer
|
||||
self._warned_chat_template_kwargs = False
|
||||
|
||||
if self.tokenizer is None:
|
||||
self.logger.warning("No tokenizer provided, will not process examples")
|
||||
@@ -190,7 +194,30 @@ class SFTDataset(StatefulIterableDataset):
|
||||
|
||||
# Parse available tools, if present - assumes OAI format
|
||||
# Reference: https://platform.openai.com/docs/guides/function-calling#function-tool-example
|
||||
tools = json.loads(example.get("tools") or "[]")
|
||||
# Accepts either `tools` or `tool_defs` (the verifiers rollout format),
|
||||
# as either a JSON-encoded string of a list or a list of dicts. Tools
|
||||
# arriving in the verifiers shape are converted to OAI form so any
|
||||
# downstream chat template can consume them.
|
||||
raw_tools = example.get("tools", example.get("tool_defs"))
|
||||
if not raw_tools:
|
||||
tools = []
|
||||
else:
|
||||
if isinstance(raw_tools, str):
|
||||
raw_tools = json.loads(raw_tools)
|
||||
tools = [
|
||||
t
|
||||
if isinstance(t, dict) and t.get("type") == "function" and "function" in t
|
||||
else {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": t.get("name"),
|
||||
"description": t.get("description"),
|
||||
"parameters": t.get("parameters"),
|
||||
**({} if t.get("strict") is None else {"strict": t["strict"]}),
|
||||
},
|
||||
}
|
||||
for t in raw_tools
|
||||
]
|
||||
|
||||
def should_mask(message: dict) -> bool:
|
||||
assert "role" in message, "Message must have a role"
|
||||
@@ -206,18 +233,35 @@ class SFTDataset(StatefulIterableDataset):
|
||||
case _:
|
||||
raise ValueError(f"Invalid message role: {message['role']}")
|
||||
|
||||
try:
|
||||
input_ids, loss_mask = build_incremental_token_mask(
|
||||
self.tokenizer,
|
||||
if self.renderer is not None:
|
||||
if example.get("chat_template_kwargs") and not self._warned_chat_template_kwargs:
|
||||
self.logger.warning(
|
||||
"Example carries chat_template_kwargs but use_renderer=True; "
|
||||
"renderers don't forward chat_template_kwargs (model-specific "
|
||||
"renderers bake their template behavior in). These kwargs will "
|
||||
"be ignored. Further warnings suppressed for this dataset."
|
||||
)
|
||||
self._warned_chat_template_kwargs = True
|
||||
|
||||
input_ids, loss_mask = build_training_sample(
|
||||
self.renderer,
|
||||
messages,
|
||||
role_to_mask=should_mask,
|
||||
tools=tools,
|
||||
chat_template_kwargs=example.get("chat_template_kwargs", {}),
|
||||
collapse_consecutive_tool_messages=True,
|
||||
)
|
||||
except IncrementalTokenizationError as e:
|
||||
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
|
||||
return None
|
||||
else:
|
||||
try:
|
||||
input_ids, loss_mask = build_incremental_token_mask(
|
||||
self.tokenizer,
|
||||
messages,
|
||||
role_to_mask=should_mask,
|
||||
tools=tools,
|
||||
chat_template_kwargs=example.get("chat_template_kwargs", {}),
|
||||
collapse_consecutive_tool_messages=True,
|
||||
)
|
||||
except IncrementalTokenizationError as e:
|
||||
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
|
||||
return None
|
||||
|
||||
# If EOS token is not found, manually append it
|
||||
if not self.tokenizer.eos_token_id in input_ids:
|
||||
@@ -537,6 +581,7 @@ def setup_dataset(
|
||||
*,
|
||||
max_epochs: int | None = None,
|
||||
raw_dataset: Dataset | None = None,
|
||||
renderer: Renderer | None = None,
|
||||
) -> StatefulIterableDataset:
|
||||
if config.type == "fake":
|
||||
return FakeDataset(
|
||||
@@ -554,6 +599,7 @@ def setup_dataset(
|
||||
loss_mask_config=config.loss_mask,
|
||||
non_dp_size=non_dp_size,
|
||||
max_epochs=max_epochs,
|
||||
renderer=renderer,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Invalid dataset type: {config.type}")
|
||||
|
||||
@@ -4,6 +4,8 @@ import time
|
||||
from contextlib import nullcontext
|
||||
from datetime import timedelta
|
||||
|
||||
from renderers.base import create_renderer
|
||||
from renderers.default import DefaultRenderer
|
||||
from ring_flash_attn import substitute_hf_flash_attn
|
||||
from torch.nn import CrossEntropyLoss
|
||||
|
||||
@@ -157,6 +159,24 @@ def train(config: SFTConfig):
|
||||
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
renderer = None
|
||||
if config.use_renderer:
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
renderer=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
)
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
raise ValueError(
|
||||
f"use_renderer=True for {config.tokenizer.name!r} resolved to DefaultRenderer. "
|
||||
"DefaultRenderer falls back to incremental apply_chat_template and does NOT "
|
||||
"fix position-dependent chat templates — the bug use_renderer is meant to solve. "
|
||||
"Either use a model with a hand-coded renderer (see renderers.base.MODEL_RENDERER_MAP), "
|
||||
"set [renderer] name=<hand-coded renderer> explicitly, or set use_renderer=false."
|
||||
)
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
|
||||
|
||||
# Set up the optimizer
|
||||
logger.info(f"Initializing optimizer ({config.optim})")
|
||||
optimizer = setup_optimizer(
|
||||
@@ -175,7 +195,7 @@ def train(config: SFTConfig):
|
||||
|
||||
# Set up the dataset and dataloader
|
||||
logger.info(f"Initializing data ({config.data})")
|
||||
dataset = setup_dataset(tokenizer, config.data, config.model.cp)
|
||||
dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer)
|
||||
dataloader = setup_dataloader(dataset, config.data)
|
||||
dataiter = iter(dataloader)
|
||||
|
||||
@@ -283,7 +303,12 @@ def train(config: SFTConfig):
|
||||
|
||||
def run_validation(step: int) -> None:
|
||||
val_dataset = setup_dataset(
|
||||
tokenizer, config.val.data, config.model.cp, max_epochs=1, raw_dataset=val_raw_dataset
|
||||
tokenizer,
|
||||
config.val.data,
|
||||
config.model.cp,
|
||||
max_epochs=1,
|
||||
raw_dataset=val_raw_dataset,
|
||||
renderer=renderer,
|
||||
)
|
||||
val_dataloader = setup_dataloader(val_dataset, config.val.data)
|
||||
|
||||
|
||||
@@ -389,6 +389,8 @@ def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) ->
|
||||
"is_masked/",
|
||||
"is_masked_low/",
|
||||
"is_masked_high/",
|
||||
"masked_advantage_positive/",
|
||||
"masked_advantage_negative/",
|
||||
"mismatch_kl/",
|
||||
"masked_mismatch_kl/",
|
||||
"unmasked_mismatch_kl/",
|
||||
|
||||
@@ -47,7 +47,10 @@ class WandbMonitor(Monitor):
|
||||
self.logger.info(f"Initializing {self.__class__.__name__} ({config})")
|
||||
self._maybe_overwrite_wandb_command()
|
||||
|
||||
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1"
|
||||
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
|
||||
# requires a server connection and can't work offline.
|
||||
_wandb_mode = os.environ.get("WANDB_MODE")
|
||||
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and _wandb_mode not in ("disabled", "offline")
|
||||
if shared_mode:
|
||||
run_id = os.environ.get("WANDB_SHARED_RUN_ID")
|
||||
label = os.environ.get("WANDB_SHARED_LABEL")
|
||||
@@ -65,9 +68,8 @@ class WandbMonitor(Monitor):
|
||||
else:
|
||||
run_id = None
|
||||
primary = False
|
||||
settings = wandb.Settings(
|
||||
mode="offline" if config.offline else "online",
|
||||
)
|
||||
mode = os.environ.get("WANDB_MODE", "offline" if config.offline else "online")
|
||||
settings = wandb.Settings(mode=mode)
|
||||
|
||||
def init_wandb(max_retries: int):
|
||||
for attempt in range(max_retries):
|
||||
|
||||
@@ -4,7 +4,13 @@ from typing import Callable
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_reward_goes_up, check_reward_in_range, strip_escape_codes
|
||||
from tests.utils import (
|
||||
check_avg_mismatch_kl_in_range,
|
||||
check_no_error,
|
||||
check_reward_goes_up,
|
||||
check_reward_in_range,
|
||||
strip_escape_codes,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
@@ -12,23 +18,16 @@ pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
TIMEOUT = 900 # 15 minutes
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_output_dir(output_dir: Path) -> Path:
|
||||
rl_dir = output_dir / "alphabet_sort_start"
|
||||
rl_dir.mkdir(parents=True, exist_ok=True)
|
||||
return rl_dir
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for alphabet sort RL CI integration tests."""
|
||||
return f"test-alphabet-sort-{branch_name}"
|
||||
return f"test-alphabet-sort:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
rl_output_dir: Path,
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
@@ -37,32 +36,39 @@ def rl_process(
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/alphabet_sort/start.toml",
|
||||
"configs/ci/integration/alphabet_sort.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
rl_output_dir.as_posix(),
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, rl_output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, rl_output_dir)
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, rl_output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process."""
|
||||
with open(rl_output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, rl_output_dir: Path):
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the reward is in range in the RL process."""
|
||||
with open(rl_output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.05)
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.10)
|
||||
|
||||
|
||||
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the average mismatch KL is below 0.15 across the last 5 steps."""
|
||||
with open(output_dir / "logs" / "trainer.log", "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_avg_mismatch_kl_in_range(trainer_stdout, last_n_steps=5, max_threshold=0.15)
|
||||
|
||||
@@ -4,7 +4,13 @@ from typing import Callable
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_reward_goes_up, check_reward_in_range, strip_escape_codes
|
||||
from tests.utils import (
|
||||
check_avg_mismatch_kl_in_range,
|
||||
check_no_error,
|
||||
check_reward_goes_up,
|
||||
check_reward_in_range,
|
||||
strip_escape_codes,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
@@ -15,7 +21,7 @@ TIMEOUT = 600 # 10 minutes
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"test-rl-{branch_name}"
|
||||
return f"test-reverse-text:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -30,7 +36,7 @@ def rl_process(
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl/start.toml",
|
||||
"configs/ci/integration/reverse_text/start.toml",
|
||||
"--clean-output-dir",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
@@ -58,7 +64,7 @@ def rl_resume_process(
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl/resume.toml",
|
||||
"configs/ci/integration/reverse_text/resume.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
@@ -90,6 +96,13 @@ def test_reward_in_range(rl_process: ProcessResult, test_no_error, output_dir: P
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
|
||||
|
||||
|
||||
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the average mismatch KL is below 0.01 across all steps"""
|
||||
with open(output_dir / "logs" / "trainer.log", "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_avg_mismatch_kl_in_range(trainer_stdout, last_n_steps=3, max_threshold=0.01)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_resume(rl_resume_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL resume process does not fail."""
|
||||
@@ -15,7 +15,7 @@ TIMEOUT = 600 # 10 minutes
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"test-rl-lora-{branch_name}"
|
||||
return f"test-reverse-text-lora:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -30,7 +30,7 @@ def rl_process(
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_lora/start.toml",
|
||||
"configs/ci/integration/reverse_text_lora/start.toml",
|
||||
"--clean-output-dir",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
@@ -58,7 +58,7 @@ def rl_resume_process(
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_lora/resume.toml",
|
||||
"configs/ci/integration/reverse_text_lora/resume.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
@@ -0,0 +1,50 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
TIMEOUT = 900 # 15 minutes
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
return f"test-reverse-text-moe:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
output_dir: Path,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/reverse_text_moe/start.toml",
|
||||
"--trainer.model.impl",
|
||||
"custom",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
f"{wandb_name}-custom",
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
def test_moe_runs(rl_process: ProcessResult, test_no_error):
|
||||
"""MoE RL with custom model impl completes without error."""
|
||||
+4
-4
@@ -88,7 +88,7 @@ def wait_for_log(
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for multi-run RL CI integration tests."""
|
||||
return f"test-rl-multi-run-{branch_name}"
|
||||
return f"test-reverse-text-multi-run:{branch_name}"
|
||||
|
||||
|
||||
INFERENCE_PORTS = [8000, 8001]
|
||||
@@ -111,7 +111,7 @@ def start_inference_and_trainer(
|
||||
"run",
|
||||
"inference",
|
||||
"@",
|
||||
"configs/ci/integration/rl_multi_run/inference.toml",
|
||||
"configs/ci/integration/reverse_text_multi_run/inference.toml",
|
||||
"--server.port",
|
||||
str(port),
|
||||
],
|
||||
@@ -134,7 +134,7 @@ def start_inference_and_trainer(
|
||||
"-m",
|
||||
"prime_rl.trainer.rl.train",
|
||||
"@",
|
||||
"configs/ci/integration/rl_multi_run/trainer.toml",
|
||||
"configs/ci/integration/reverse_text_multi_run/trainer.toml",
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--wandb.project",
|
||||
@@ -200,7 +200,7 @@ def start_orchestrator(
|
||||
"run",
|
||||
"orchestrator",
|
||||
"@",
|
||||
"configs/ci/integration/rl_multi_run/orchestrator.toml",
|
||||
"configs/ci/integration/reverse_text_multi_run/orchestrator.toml",
|
||||
"--output-dir",
|
||||
run_dir.as_posix(),
|
||||
"--max-steps",
|
||||
@@ -14,7 +14,7 @@ TIMEOUT = 300 # 5 minutes
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for SFT CI integration tests."""
|
||||
return f"test-sft-{branch_name}"
|
||||
return f"test-reverse-text-sft:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -30,7 +30,7 @@ def sft_process(
|
||||
"run",
|
||||
"sft",
|
||||
"@",
|
||||
"configs/ci/integration/sft/start.toml",
|
||||
"configs/ci/integration/reverse_text_sft/start.toml",
|
||||
"--deployment.num-gpus",
|
||||
"2",
|
||||
"--clean-output-dir",
|
||||
@@ -60,7 +60,7 @@ def sft_resume_process(
|
||||
"run",
|
||||
"sft",
|
||||
"@",
|
||||
"configs/ci/integration/sft/resume.toml",
|
||||
"configs/ci/integration/reverse_text_sft/resume.toml",
|
||||
"--deployment.num-gpus",
|
||||
"2",
|
||||
"--wandb.project",
|
||||
+5
-5
@@ -24,7 +24,7 @@ def assert_adapter_checkpoint(adapter_dir: Path) -> None:
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for SFT LoRA CI integration tests."""
|
||||
return f"test-sft-lora-{branch_name}"
|
||||
return f"test-reverse-text-sft-lora:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -40,7 +40,7 @@ def sft_lora_process(
|
||||
"run",
|
||||
"sft",
|
||||
"@",
|
||||
"configs/ci/integration/sft_lora/start.toml",
|
||||
"configs/ci/integration/reverse_text_sft_lora/start.toml",
|
||||
"--deployment.num-gpus",
|
||||
"2",
|
||||
"--clean-output-dir",
|
||||
@@ -70,7 +70,7 @@ def sft_lora_resume_process(
|
||||
"run",
|
||||
"sft",
|
||||
"@",
|
||||
"configs/ci/integration/sft_lora/resume.toml",
|
||||
"configs/ci/integration/reverse_text_sft_lora/resume.toml",
|
||||
"--deployment.num-gpus",
|
||||
"2",
|
||||
"--wandb.project",
|
||||
@@ -100,7 +100,7 @@ def test_loss_goes_down(sft_lora_process: ProcessResult, output_dir: Path):
|
||||
|
||||
def test_adapter_checkpoint_written(sft_lora_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the adapter checkpoint is written with valid PEFT-compatible keys."""
|
||||
adapter_dir = output_dir / "weights" / "step_10" / "lora_adapters"
|
||||
adapter_dir = output_dir / "weights" / "step_5" / "lora_adapters"
|
||||
assert_adapter_checkpoint(adapter_dir)
|
||||
|
||||
|
||||
@@ -120,5 +120,5 @@ def test_loss_goes_down_resume(sft_lora_resume_process: ProcessResult, output_di
|
||||
|
||||
def test_adapter_checkpoint_written_resume(sft_lora_resume_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the adapter checkpoint is written after resuming with valid PEFT-compatible keys."""
|
||||
adapter_dir = output_dir / "weights" / "step_20" / "lora_adapters"
|
||||
adapter_dir = output_dir / "weights" / "step_10" / "lora_adapters"
|
||||
assert_adapter_checkpoint(adapter_dir)
|
||||
@@ -1,104 +0,0 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
TIMEOUT = 900 # 15 minutes
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
return f"test-rl-moe-{branch_name}"
|
||||
|
||||
|
||||
# --- MoE with HF impl (default) ---
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_hf_output_dir(output_dir: Path) -> Path:
|
||||
d = output_dir / "rl_moe_hf"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_hf_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
moe_hf_output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_moe/start.toml",
|
||||
"--trainer.model.impl",
|
||||
"hf",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
f"{wandb_name}-hf",
|
||||
"--output-dir",
|
||||
moe_hf_output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_hf(moe_hf_process: ProcessResult, moe_hf_output_dir: Path):
|
||||
check_no_error(moe_hf_process, moe_hf_output_dir)
|
||||
|
||||
|
||||
def test_moe_hf_runs(moe_hf_process: ProcessResult, test_no_error_hf):
|
||||
"""MoE RL with HF model impl completes without error."""
|
||||
|
||||
|
||||
# --- MoE with custom impl ---
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_custom_output_dir(output_dir: Path) -> Path:
|
||||
d = output_dir / "rl_moe_custom"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_custom_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
moe_custom_output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_moe/start.toml",
|
||||
"--trainer.model.impl",
|
||||
"custom",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
f"{wandb_name}-custom",
|
||||
"--output-dir",
|
||||
moe_custom_output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_custom(moe_custom_process: ProcessResult, moe_custom_output_dir: Path):
|
||||
check_no_error(moe_custom_process, moe_custom_output_dir)
|
||||
|
||||
|
||||
def test_moe_custom_runs(moe_custom_process: ProcessResult, test_no_error_custom):
|
||||
"""MoE RL with custom model impl completes without error."""
|
||||
@@ -25,8 +25,9 @@ CONFIG_CLASSES = [
|
||||
|
||||
|
||||
def get_config_files() -> list[Path]:
|
||||
"""Any TOML file inside `configs/` or `examples/`"""
|
||||
config_files = list(Path("configs").rglob("*.toml"))
|
||||
"""Any TOML file inside `configs/` or `examples/` (skips the configs/private/ submodule)."""
|
||||
private = Path("configs/private")
|
||||
config_files = [p for p in Path("configs").rglob("*.toml") if private not in p.parents]
|
||||
example_files = list(Path("examples").rglob("*.toml"))
|
||||
|
||||
return config_files + example_files
|
||||
|
||||
+35
-2
@@ -14,10 +14,10 @@ def check_no_error(process: ProcessResult, output_dir: Path) -> None:
|
||||
if process.returncode != 0:
|
||||
print("=== Inference Outputs ===")
|
||||
with open(output_dir / "logs" / "inference.log", "r") as f:
|
||||
print(*f.readlines()[-100:], sep="\n")
|
||||
print(*f.readlines()[-100:], sep="")
|
||||
print("=== Orchestrator Outputs ===")
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
print(*f.readlines()[-1000:], sep="\n")
|
||||
print(*f.readlines()[-1000:], sep="")
|
||||
assert process.returncode == 0, f"Process has non-zero return code ({process})"
|
||||
|
||||
|
||||
@@ -157,6 +157,39 @@ def check_avg_reward_in_range(
|
||||
)
|
||||
|
||||
|
||||
def check_avg_mismatch_kl_in_range(
|
||||
lines: list[str],
|
||||
last_n_steps: int,
|
||||
min_threshold: float | None = None,
|
||||
max_threshold: float | None = None,
|
||||
):
|
||||
"""Helper to assert that the average mismatch KL over the last N steps is within a threshold"""
|
||||
pattern = r"Mismatch KL:\s*(\d+\.\d{4})"
|
||||
step_lines = [line for line in lines if "SUCCESS" in line and "Step" in line and re.search(pattern, line)]
|
||||
assert len(step_lines) >= last_n_steps, (
|
||||
f"Not enough step lines found. Expected at least {last_n_steps}, got {len(step_lines)}"
|
||||
)
|
||||
|
||||
recent_lines = step_lines[-last_n_steps:]
|
||||
kl_values = []
|
||||
for line in recent_lines:
|
||||
match = re.search(pattern, line)
|
||||
assert match is not None, f"Could not find Mismatch KL in line: {line}"
|
||||
kl_values.append(float(match.group(1)))
|
||||
|
||||
avg_kl = sum(kl_values) / len(kl_values)
|
||||
if min_threshold is not None:
|
||||
assert avg_kl >= min_threshold, (
|
||||
f"Average mismatch KL over last {last_n_steps} steps did not reach minimum threshold. "
|
||||
f"Found avg_kl={avg_kl:.4f} < {min_threshold} (kl_values={kl_values})"
|
||||
)
|
||||
if max_threshold is not None:
|
||||
assert avg_kl <= max_threshold, (
|
||||
f"Average mismatch KL over last {last_n_steps} steps exceeded maximum threshold. "
|
||||
f"Found avg_kl={avg_kl:.4f} > {max_threshold} (kl_values={kl_values})"
|
||||
)
|
||||
|
||||
|
||||
def check_mismatch_kl_in_range(
|
||||
lines: list[str],
|
||||
step: int = -1,
|
||||
|
||||
Reference in New Issue
Block a user