Nightly CI (#1371)
* rename to test_configs * cleanup unit tests * update sft integration test * working sft tests * fix eval ci * synthesize integration tests * rl integration test * enable lora flag in inference config * add lora integration tests * Move utils and fixtures around * use tmp output dir * use shared wandb project * bring back world reset * update wandb names * remove reverse text configs (moved to ci) * fix rl examples * remove vllm server fixture * Minor changes * add nightly ci * Add nightly CI * install prime in ci to enable auto install * add pull pull request trigger * make workflow visible when pr against main * Add more experiments, auto-discovery, parallelize across runners * build matrix correct * fix configs * use tp for 7b * update configs * add wordle * remove tool install * add logging on fail * print logs on error and auto skip if failed * use fixture to auto skip on error * use team id and base url * log stdout on install error * use auto install in examples * Retrigger CI * use the same config for example and nightly reverse text * do not use default interval in shared ckpt config * match example * add inference * no lora in ci * add hendrycks math * update configs * do not use commit hash as its recorded by wandb anyways * use qwen 1.7b * increase batch size * add acereason * add cron schedule * name envs * higher bs and no online filtering * Split cpu tests into unit and integration and inject secrets * Retrigger CI * use util to check for error * kill stray process (make containerized soon) * try using docker setup * Retrigger CI * Retrigger CI * set 24h timeout * enable lora and no difficulty filtering in configs * make lora work * update wiki search configs * update alphabet sort example * disable ac * use 4 train gpus hendrycks * adjust configs from examples * only eval aime24 * udpate acerason * use 4 trainer, 4 inference for acereason * bring back sep bc otherwise i dont see logs?! * allow autosetup dp * longer cleanup timeout period * 200 steps alphabet sort * clean exit on orchestrator * revert changes to configs and examples unrelated to this pr * no online filtering in wiki search example * remove trigger to run nightly ci on pr against main [skip ci] * fix running integration tests * remove misplaced assert * remove legacy test [skip ci]
This commit is contained in:
@@ -2,13 +2,13 @@ name: CPU Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, refactor]
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
jobs:
|
||||
cpu-tests-units:
|
||||
name: All tests
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
@@ -23,6 +23,50 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: uv sync --locked
|
||||
- name: Run tests
|
||||
run: PYTEST_OUTPUT_DIR=/tmp/outputs uv run pytest tests -m "not gpu"
|
||||
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' }}
|
||||
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 }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
run: PYTEST_OUTPUT_DIR=/tmp/outputs uv run pytest tests/unit -m "not gpu"
|
||||
- name: Cleanup output_dir
|
||||
run: rm -rf /tmp/outputs
|
||||
|
||||
integration-tests:
|
||||
name: Integration tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --locked
|
||||
- name: Run 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' }}
|
||||
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 }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
run: PYTEST_OUTPUT_DIR=/tmp/outputs uv run pytest tests/integration -m "not gpu"
|
||||
- name: Cleanup output_dir
|
||||
run: rm -rf /tmp/outputs
|
||||
|
||||
@@ -2,7 +2,7 @@ name: GPU Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, refactor]
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
@@ -37,7 +37,19 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: uv sync --locked
|
||||
- name: Run unit tests
|
||||
run: PYTEST_OUTPUT_DIR=/tmp/outputs uv run pytest tests/unit -m gpu
|
||||
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' }}
|
||||
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 }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
run: uv run pytest tests/unit -m gpu
|
||||
|
||||
integration-tests:
|
||||
name: Integration tests
|
||||
@@ -77,6 +89,4 @@ jobs:
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
run: |
|
||||
uv run pytest tests/integration -m gpu --ignore=tests/integration/lora/test_rl.py
|
||||
uv run pytest tests/integration/lora -m gpu
|
||||
run: uv run pytest tests/integration -m gpu
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
name: Nightly Tests
|
||||
|
||||
on:
|
||||
# Allow to manually trigger the workflow
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
test_file:
|
||||
description: "Single nightly test file to run (e.g. tests/nightly/test_my_exp.py). Leave empty to run all."
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
# Scheduled run at 3AM PST (11AM UTC)
|
||||
schedule:
|
||||
- cron: "0 11 * * *"
|
||||
|
||||
jobs:
|
||||
discover-experiments:
|
||||
name: Discover experiments
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
outputs:
|
||||
matrix: ${{ steps.build-matrix.outputs.matrix }}
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Build matrix from nightly test files
|
||||
id: build-matrix
|
||||
run: |
|
||||
# Find all nightly test files
|
||||
files=$(ls tests/nightly/test_*.py)
|
||||
|
||||
# Filter to specific test file if provided in workflow_dispatch
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ github.event.inputs.test_file }}" ]; then
|
||||
# Filter to only the specified test file
|
||||
filtered=$(echo "$files" | grep -F "${{ github.event.inputs.test_file }}" || true)
|
||||
if [ -z "$filtered" ]; then
|
||||
echo "Error: Test file '${{ github.event.inputs.test_file }}' not found"
|
||||
exit 1
|
||||
fi
|
||||
files="$filtered"
|
||||
fi
|
||||
|
||||
echo "Discovered nightly tests:"
|
||||
echo "$files"
|
||||
|
||||
# Build JSON of the form: { "test_file": ["tests/nightly/test_a.py", ...] }
|
||||
json=$(printf '%s\n' "$files" | jq -R . | jq -sc '{test_file: .}')
|
||||
|
||||
echo "matrix=$json" >> "$GITHUB_OUTPUT"
|
||||
run-experiment:
|
||||
name: Run experiment
|
||||
needs: discover-experiments
|
||||
runs-on: research-cluster
|
||||
container:
|
||||
image: pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel
|
||||
options: --gpus all
|
||||
timeout-minutes: 1440 # 24 hours
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJSON(needs.discover-experiments.outputs.matrix) }}
|
||||
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y git
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --locked
|
||||
- name: Run experiment
|
||||
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' }}
|
||||
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 }}
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
run: |
|
||||
echo "Running test file: ${{ matrix.test_file }}"
|
||||
uv run pytest "${{ matrix.test_file }}"
|
||||
@@ -0,0 +1,15 @@
|
||||
num_examples = 5
|
||||
rollouts_per_example = 3
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/single-turn-math"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/single-turn-math"
|
||||
name = "hendrycks"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
@@ -0,0 +1,9 @@
|
||||
num_examples = 5
|
||||
rollouts_per_example = 3
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/single-turn-math"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
@@ -0,0 +1,26 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 25
|
||||
|
||||
[ckpt]
|
||||
resume_step = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
seq_len = 2048
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
@@ -0,0 +1,25 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 20
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
seq_len = 2048
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
@@ -0,0 +1,37 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 25
|
||||
|
||||
[ckpt]
|
||||
resume_step = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
[trainer.model.experimental.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[trainer.weight_broadcast]
|
||||
adapter_only = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
seq_len = 2048
|
||||
lora_name = "r8-1e-4"
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
enable_lora = true
|
||||
@@ -0,0 +1,36 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 20
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
[trainer.model.experimental.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[trainer.weight_broadcast]
|
||||
adapter_only = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
seq_len = 2048
|
||||
lora_name = "r8-1e-4"
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
enable_lora = true
|
||||
@@ -1,12 +1,12 @@
|
||||
max_steps = 20
|
||||
|
||||
[ckpt]
|
||||
resume_step = 10
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
[data]
|
||||
name = "PrimeIntellect/Reverse-Text-SFT"
|
||||
batch_size = 2
|
||||
seq_len = 1024
|
||||
|
||||
[optim]
|
||||
lr = 2e-5
|
||||
batch_size = 4
|
||||
seq_len = 1024
|
||||
@@ -0,0 +1,11 @@
|
||||
max_steps = 10
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
[data]
|
||||
name = "PrimeIntellect/Reverse-Text-SFT"
|
||||
batch_size = 4
|
||||
seq_len = 1024
|
||||
@@ -0,0 +1,15 @@
|
||||
num_examples = 5
|
||||
rollouts_per_example = 3
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/single-turn-math"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/single-turn-math"
|
||||
name = "hendrycks"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
@@ -0,0 +1,8 @@
|
||||
num_examples = 5
|
||||
rollouts_per_example = 3
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
@@ -0,0 +1,9 @@
|
||||
num_examples = 5
|
||||
rollouts_per_example = 3
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/single-turn-math"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
@@ -0,0 +1,30 @@
|
||||
# Run on 8xH200
|
||||
# Similar to configs/acereason_math/stage1.toml, but
|
||||
# - 300 instead of 500 steps
|
||||
# - No checkpointing
|
||||
# - No evals
|
||||
inference_gpu_ids = [0,1,2,3]
|
||||
trainer_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 300
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
seq_len = 8192
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 8192
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/single-turn-math"
|
||||
name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference]
|
||||
@@ -0,0 +1,31 @@
|
||||
# Similar to examples/alphabet_sort/rl.toml, but
|
||||
# - No LoRA (full fine-tune)
|
||||
# - No checkpointing
|
||||
# - No liger kernel
|
||||
# - LR 1e-6 (default), instead of 1e-5 (examples/alphabet_sort/rl.toml)
|
||||
# - Uses full node (4 trainer, 4 inference GPUs)
|
||||
|
||||
inference_gpu_ids = [0,1,2,3]
|
||||
trainer_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 200
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-1.7B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
seq_len = 2048
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 768
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 3, max_turns = 3, min_names_per_turn = 1, max_names_per_turn = 4, similarity_power = 8, power_per_turn = false }
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference]
|
||||
@@ -0,0 +1,46 @@
|
||||
inference_gpu_ids = [0,1,2,3]
|
||||
trainer_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 300
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 16
|
||||
seq_len = 2048
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/single-turn-math"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_fraction = 0.0
|
||||
hard_fraction = 0.0
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[orchestrator.val]
|
||||
interval = 5
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/math500"
|
||||
name = "math500"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference]
|
||||
@@ -1,13 +1,21 @@
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
seq_len = 2048
|
||||
# Matches examples/reverse_text/rl.toml exactly
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[sampling]
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
seq_len = 2048
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
|
||||
[[env]]
|
||||
[[orchestrator.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
@@ -0,0 +1,29 @@
|
||||
# Similar to examples/wiki_search/rl.toml, but
|
||||
# - 300 instead of 500 steps (short runtime)
|
||||
# - No LoRA
|
||||
|
||||
inference_gpu_ids = [0,1,2,3]
|
||||
trainer_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 300
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
seq_len = 4096
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
name = "wiki-search"
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
|
||||
[trainer] # Default trainer config
|
||||
@@ -1,2 +0,0 @@
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
@@ -1,7 +0,0 @@
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[optim]
|
||||
lr = 3e-6
|
||||
@@ -15,4 +15,6 @@ max_tokens = 128
|
||||
id = "reverse-text"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
+2
-2
@@ -66,7 +66,7 @@ class SharedWandbConfig(BaseSettings):
|
||||
class SharedCheckpointConfig(BaseSettings):
|
||||
"""Configures shared checkpoint configs."""
|
||||
|
||||
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = 50
|
||||
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
|
||||
|
||||
resume_step: Annotated[
|
||||
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
|
||||
@@ -397,7 +397,7 @@ def cleanup_processes(processes: list[Popen]):
|
||||
if process.poll() is None: # Process is still running
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
process.wait(timeout=60) # 60 seconds to terminate gracefully
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
|
||||
|
||||
@@ -42,12 +42,3 @@ def get_world() -> World:
|
||||
def reset_world():
|
||||
global _WORLD
|
||||
_WORLD = None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Used in tests/units/test_world_info.py to test init with torchrun
|
||||
import torch.distributed as dist
|
||||
|
||||
print(get_world())
|
||||
if dist.is_initialized():
|
||||
dist.destroy_process_group()
|
||||
|
||||
+33
-23
@@ -6,7 +6,7 @@ import time
|
||||
from collections import defaultdict
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import Any, Callable
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
@@ -92,32 +92,43 @@ def capitalize(s: str) -> str:
|
||||
return s[0].upper() + s[1:]
|
||||
|
||||
|
||||
def clean_exit(func):
|
||||
def clean_exit(func: Callable) -> Callable:
|
||||
"""
|
||||
A decorator that ensures the a torch.distributed process group is properly
|
||||
cleaned up after the decorated function runs or raises an exception.
|
||||
|
||||
Args:
|
||||
func: The function to decorate
|
||||
|
||||
Returns:
|
||||
The decorated function
|
||||
"""
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
try:
|
||||
ret = func(*args, **kwargs)
|
||||
wandb.finish()
|
||||
return ret
|
||||
except Exception as e:
|
||||
wandb.finish(exit_code=1)
|
||||
raise e
|
||||
finally:
|
||||
if dist.is_initialized():
|
||||
dist.destroy_process_group()
|
||||
@functools.wraps(func)
|
||||
async def async_wrapper(*args, **kwargs):
|
||||
try:
|
||||
ret = await func(*args, **kwargs)
|
||||
wandb.finish()
|
||||
return ret
|
||||
except Exception as e:
|
||||
wandb.finish(exit_code=1)
|
||||
raise e
|
||||
finally:
|
||||
if dist.is_initialized():
|
||||
dist.destroy_process_group()
|
||||
|
||||
return wrapper
|
||||
return async_wrapper
|
||||
else:
|
||||
|
||||
@functools.wraps(func)
|
||||
def sync_wrapper(*args, **kwargs):
|
||||
try:
|
||||
ret = func(*args, **kwargs)
|
||||
wandb.finish()
|
||||
return ret
|
||||
except Exception as e:
|
||||
wandb.finish(exit_code=1)
|
||||
raise e
|
||||
finally:
|
||||
if dist.is_initialized():
|
||||
dist.destroy_process_group()
|
||||
|
||||
return sync_wrapper
|
||||
|
||||
|
||||
def sync_wait_for_path(path: Path, interval: int = 1, log_interval: int = 10) -> None:
|
||||
@@ -313,8 +324,7 @@ def install_env(env_id: str) -> None:
|
||||
install_cmd = ["uv", "run", "--no-sync", "prime", "env", "install", env_id]
|
||||
result = subprocess.run(install_cmd, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"Failed to install environment {env_id}: {result.stderr}")
|
||||
raise RuntimeError(f"Failed to install environment {env_id}")
|
||||
raise RuntimeError(f"Failed to install environment {env_id} (stdout={result.stdout}, stderr={result.stderr})")
|
||||
logger.info(f"Successfully installed environment {env_id}")
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
from .conftest import Command, Environment, ProcessResult
|
||||
|
||||
__all__ = ["Command", "Environment", "ProcessResult"]
|
||||
|
||||
+63
-207
@@ -1,31 +1,19 @@
|
||||
import atexit
|
||||
import concurrent.futures
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Callable, Generator
|
||||
|
||||
import pytest
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
from prime_rl.trainer.world import reset_world
|
||||
from prime_rl.utils.logger import reset_logger, setup_logger
|
||||
|
||||
TIMEOUT = 120
|
||||
|
||||
|
||||
Environment = dict[str, str]
|
||||
Command = list[str]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_logging():
|
||||
"""
|
||||
Fixture to set and reset the logger after each test.
|
||||
"""
|
||||
"""Auto-fixture to setup logger between tests"""
|
||||
setup_logger("debug")
|
||||
yield
|
||||
reset_logger()
|
||||
@@ -33,9 +21,7 @@ def setup_logging():
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_env():
|
||||
"""
|
||||
Fixture to reset environment variables after each test.
|
||||
"""
|
||||
"""Auto-fixture to reset environment variables between tests"""
|
||||
original_env = dict(os.environ)
|
||||
yield
|
||||
os.environ.clear()
|
||||
@@ -44,34 +30,36 @@ def setup_env():
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_world():
|
||||
"""
|
||||
Fixture to reset the world info after each test.
|
||||
"""
|
||||
"""Auto-fixture to reset the world between tests."""
|
||||
yield
|
||||
reset_world()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def output_dir(tmp_path_factory: pytest.TempPathFactory) -> Generator[Path, None, None]:
|
||||
output_dir = Path(os.environ.get("PYTEST_OUTPUT_DIR", tmp_path_factory.mktemp("outputs")))
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
yield output_dir
|
||||
shutil.rmtree(output_dir, ignore_errors=True)
|
||||
@pytest.fixture(autouse=True, scope="module")
|
||||
def cleanup_zombies():
|
||||
"""Auto-fixture to cleanup zombies between module tests. Used in CI to avoid zombie processes from previous tests."""
|
||||
subprocess.run(["pkill", "-f", "torchrun"])
|
||||
subprocess.run(["pkill", "-f", "VLLM"])
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def free_port() -> int:
|
||||
"""Fixture to get a free port per tests"""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.bind(("", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def hf_api() -> HfApi:
|
||||
"""Hugging Face API to use for tests."""
|
||||
return HfApi()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def username() -> str:
|
||||
def user() -> str:
|
||||
"""Fixture for current user from environment for test session."""
|
||||
return os.environ.get("USERNAME_CI", os.environ.get("USER", "none"))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@pytest.fixture(scope="session")
|
||||
def branch_name() -> str:
|
||||
"""Fixture for current branch name for test session."""
|
||||
branch_name_ = os.environ.get("GITHUB_REF_NAME", None)
|
||||
|
||||
if branch_name_ is None:
|
||||
@@ -82,191 +70,59 @@ def branch_name() -> str:
|
||||
return branch_name
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def commit_hash() -> str:
|
||||
return subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).decode("utf-8").strip()
|
||||
@pytest.fixture(scope="session")
|
||||
def output_dir(tmp_path_factory: pytest.TempPathFactory) -> Generator[Path, None, None]:
|
||||
"""Fixture for temporary output directory for tests with automatic cleanup"""
|
||||
output_dir = Path(os.environ.get("PYTEST_OUTPUT_DIR", tmp_path_factory.mktemp("outputs")))
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
yield output_dir
|
||||
shutil.rmtree(output_dir, ignore_errors=True)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def get_wandb_project(user: str) -> Callable[[str], str]:
|
||||
"""Factory fixture to get W&B project name. Used to setup shared W&B projects for integration & nightly tests."""
|
||||
|
||||
def _get_wandb_project(wandb_project: str) -> str:
|
||||
if user != "CI_RUNNER":
|
||||
wandb_project += "-local"
|
||||
return wandb_project
|
||||
|
||||
return _get_wandb_project
|
||||
|
||||
|
||||
Environment = dict[str, str]
|
||||
Command = list[str]
|
||||
|
||||
|
||||
class ProcessResult:
|
||||
def __init__(self, returncode: int, pid: int):
|
||||
self.returncode = returncode
|
||||
self.pid = pid
|
||||
"""Result object containing process information and captured output."""
|
||||
|
||||
def __init__(self, process: subprocess.Popen):
|
||||
self.returncode = process.returncode
|
||||
self.pid = process.pid
|
||||
|
||||
def run_subprocess(command: Command, env: Environment, timeout: int = TIMEOUT) -> ProcessResult:
|
||||
"""Run a subprocess with given command and environment with a timeout"""
|
||||
process = subprocess.Popen(command, env={**os.environ, **env})
|
||||
try:
|
||||
process.wait(timeout=timeout)
|
||||
return ProcessResult(process.returncode, process.pid)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10) # Give it 10 seconds to terminate gracefully
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
return ProcessResult(1, process.pid)
|
||||
|
||||
|
||||
def run_subprocesses_in_parallel(
|
||||
commands: list[Command], envs: list[Environment], timeout: int = TIMEOUT
|
||||
) -> list[ProcessResult]:
|
||||
"""Start multiple processes in parallel using ProcessPoolExecutor and wait for completion."""
|
||||
assert len(commands) == len(envs), "Should have an environment for each command"
|
||||
with concurrent.futures.ProcessPoolExecutor(max_workers=len(commands)) as executor:
|
||||
futures = [executor.submit(run_subprocess, cmd, env, timeout) for cmd, env in zip(commands, envs)]
|
||||
results = []
|
||||
for i, future in enumerate(futures):
|
||||
try:
|
||||
result = future.result(timeout=timeout)
|
||||
results.append(result)
|
||||
except concurrent.futures.TimeoutError:
|
||||
raise TimeoutError(f"Process {i} did not complete within {timeout} seconds")
|
||||
|
||||
return results
|
||||
def __repr__(self):
|
||||
return f"ProcessResult(returncode={self.returncode}, pid={self.pid})"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_process() -> Callable[[Command, Environment, int], ProcessResult]:
|
||||
"""Factory fixture for running a single process."""
|
||||
return run_subprocess
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_processes() -> Callable[[list[Command], list[Environment], int], list[ProcessResult]]:
|
||||
"""Factory fixture for running multiple processes in parallel."""
|
||||
return run_subprocesses_in_parallel
|
||||
|
||||
|
||||
VLLM_SERVER_ENV = {"CUDA_VISIBLE_DEVICES": "0"}
|
||||
VLLM_SERVER_CMD = ["uv", "run", "inference", "@", "configs/reverse_text/rl/infer.toml", "--max-model-len", "2048"]
|
||||
|
||||
|
||||
def cleanup_process(process: subprocess.Popen):
|
||||
process.terminate()
|
||||
|
||||
# Wait for the process to terminate (with timeout)
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
# If it doesn't terminate gracefully, kill it
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def vllm_server(output_dir: Path) -> Generator[None, None, None]:
|
||||
"""Start a vLLM server for integration and e2e tests"""
|
||||
import asyncio
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
# Start the server as a subprocess
|
||||
env = {**os.environ, **VLLM_SERVER_ENV}
|
||||
with open(output_dir / "vllm.stdout", "w") as stdout, open(output_dir / "vllm.stderr", "w") as stderr:
|
||||
vllm_process = subprocess.Popen(
|
||||
VLLM_SERVER_CMD,
|
||||
env=env,
|
||||
stdout=stdout,
|
||||
stderr=stderr,
|
||||
)
|
||||
|
||||
# Register cleanup on unexpected termination
|
||||
atexit.register(cleanup_process, vllm_process)
|
||||
signal.signal(signal.SIGTERM, lambda signum, frame: cleanup_process(vllm_process))
|
||||
signal.signal(signal.SIGINT, lambda signum, frame: cleanup_process(vllm_process))
|
||||
|
||||
# Default vLLM server URL
|
||||
base_url = "http://localhost:8000"
|
||||
|
||||
async def wait_for_server_health(timeout: int = 180, interval: int = 1) -> bool:
|
||||
"""Wait for the server to be healthy by checking the /health endpoint."""
|
||||
health_url = f"{base_url}/health"
|
||||
start_time = time.perf_counter()
|
||||
|
||||
while time.perf_counter() - start_time < timeout:
|
||||
def _run_process(command: Command, env: Environment = {}, timeout: int | None = None) -> ProcessResult:
|
||||
"""Run a subprocess with given command and environment with a timeout"""
|
||||
process = subprocess.Popen(command, env={**os.environ, **env})
|
||||
try:
|
||||
process.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.terminate()
|
||||
try:
|
||||
with urllib.request.urlopen(health_url, timeout=5) as response:
|
||||
if response.status == 200:
|
||||
return True
|
||||
except (urllib.error.URLError, urllib.error.HTTPError):
|
||||
pass
|
||||
await asyncio.sleep(interval)
|
||||
process.wait(timeout=10) # Give it 10 seconds to terminate gracefully
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
return False
|
||||
return ProcessResult(process)
|
||||
|
||||
try:
|
||||
# Wait for the server to be healthy
|
||||
is_healthy = asyncio.run(wait_for_server_health())
|
||||
|
||||
if not is_healthy:
|
||||
raise RuntimeError("vLLM server did not become healthy within timeout")
|
||||
|
||||
# Yield to signal that the server is ready (can be used in tests that depend on it)
|
||||
yield
|
||||
finally:
|
||||
cleanup_process(vllm_process)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def vllm_server_dynamic_lora_loading(output_dir: Path) -> Generator[None, None, None]:
|
||||
"""Start a vLLM server for integration and e2e tests"""
|
||||
import asyncio
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
# Start the server as a subprocess
|
||||
env = {**os.environ, **VLLM_SERVER_ENV, "VLLM_ALLOW_RUNTIME_LORA_UPDATING": "True"}
|
||||
with open(output_dir / "vllm.stdout", "w") as stdout, open(output_dir / "vllm.stderr", "w") as stderr:
|
||||
vllm_process = subprocess.Popen(
|
||||
VLLM_SERVER_CMD + ["--enable-lora"],
|
||||
env=env,
|
||||
stdout=stdout,
|
||||
stderr=stderr,
|
||||
)
|
||||
|
||||
# Register cleanup on unexpected termination
|
||||
atexit.register(cleanup_process, vllm_process)
|
||||
signal.signal(signal.SIGTERM, lambda signum, frame: cleanup_process(vllm_process))
|
||||
signal.signal(signal.SIGINT, lambda signum, frame: cleanup_process(vllm_process))
|
||||
|
||||
# Default vLLM server URL
|
||||
base_url = "http://localhost:8000"
|
||||
|
||||
async def wait_for_server_health(timeout: int = 180, interval: int = 1) -> bool:
|
||||
"""Wait for the server to be healthy by checking the /health endpoint."""
|
||||
health_url = f"{base_url}/health"
|
||||
start_time = time.time()
|
||||
|
||||
while time.time() - start_time < timeout:
|
||||
try:
|
||||
with urllib.request.urlopen(health_url, timeout=5) as response:
|
||||
if response.status == 200:
|
||||
return True
|
||||
except (urllib.error.URLError, urllib.error.HTTPError):
|
||||
pass
|
||||
await asyncio.sleep(interval)
|
||||
|
||||
return False
|
||||
|
||||
try:
|
||||
# Wait for the server to be healthy
|
||||
is_healthy = asyncio.run(wait_for_server_health())
|
||||
|
||||
if not is_healthy:
|
||||
raise RuntimeError("vLLM server did not become healthy within timeout")
|
||||
|
||||
# Yield to signal that the server is ready (can be used in tests that depend on it)
|
||||
yield
|
||||
finally:
|
||||
cleanup_process(vllm_process)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def free_port() -> int:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.bind(("", 0))
|
||||
return s.getsockname()[1]
|
||||
return _run_process
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_project(get_wandb_project: Callable[[str], str]) -> str:
|
||||
"""Fixture for W&B project name for integration tests. This means all integration tests will use the same W&B project."""
|
||||
return get_wandb_project("integration-tests")
|
||||
@@ -1,159 +0,0 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests import Command, Environment, ProcessResult
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
|
||||
TIMEOUT = 600 # 10 minutes
|
||||
RL_CMD = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"--trainer",
|
||||
"@",
|
||||
"configs/reverse_text/rl/train.toml",
|
||||
"--orchestrator",
|
||||
"@",
|
||||
"configs/reverse_text/rl/orch.toml",
|
||||
"--orchestrator.sampling.max-tokens",
|
||||
"128",
|
||||
"--trainer.model.experimental.lora.rank",
|
||||
"8",
|
||||
"--trainer.ckpt.weights.save-adapter-separately",
|
||||
"--trainer.weight_broadcast.adapter_only",
|
||||
"--orchestrator.lora-name",
|
||||
"r8-1e-4",
|
||||
"--trainer.optim.lr",
|
||||
"1e-4",
|
||||
"--ckpt",
|
||||
]
|
||||
RL_RESUME_CMD = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"--trainer",
|
||||
"@",
|
||||
"configs/reverse_text/rl/train.toml",
|
||||
"--orchestrator",
|
||||
"@",
|
||||
"configs/reverse_text/rl/orch.toml",
|
||||
"--orchestrator.sampling.max-tokens",
|
||||
"128",
|
||||
"--trainer.model.experimental.lora.rank",
|
||||
"8",
|
||||
"--trainer.ckpt.weights.save-adapter-separately",
|
||||
"--trainer.weight_broadcast.adapter_only",
|
||||
"--orchestrator.lora-name",
|
||||
"r8-1e-4",
|
||||
"--trainer.optim.lr",
|
||||
"1e-4",
|
||||
"--max-steps",
|
||||
"25",
|
||||
"--ckpt.resume-step",
|
||||
"20",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_project(username: str) -> str:
|
||||
project = "ci-reverse-text-rl"
|
||||
if username != "CI_RUNNER":
|
||||
project += "-local"
|
||||
return project
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def lora_rl_process(
|
||||
vllm_server_dynamic_lora_loading, # Can only run with vLLM server
|
||||
run_process: Callable[[Command, Environment, int], ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
branch_name: str,
|
||||
commit_hash: str,
|
||||
) -> ProcessResult:
|
||||
wandb_name = f"{branch_name}-{commit_hash}"
|
||||
|
||||
return run_process(
|
||||
RL_CMD + ["--wandb.project", wandb_project, "--wandb.name", wandb_name, "--output-dir", output_dir.as_posix()],
|
||||
{},
|
||||
TIMEOUT,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def lora_rl_resume_process(
|
||||
vllm_server_dynamic_lora_loading, # Can only run with vLLM server
|
||||
lora_rl_process, # Resume training can only start when regular RL process is finished
|
||||
run_process: Callable[[Command, Environment, int], ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
branch_name: str,
|
||||
commit_hash: str,
|
||||
) -> ProcessResult:
|
||||
if lora_rl_process.returncode != 0:
|
||||
pytest.skip("RL process failed")
|
||||
wandb_name = f"{branch_name}-{commit_hash}-resume"
|
||||
|
||||
return run_process(
|
||||
RL_RESUME_CMD
|
||||
+ ["--wandb.project", wandb_project, "--wandb.name", wandb_name, "--output-dir", output_dir.as_posix()],
|
||||
{},
|
||||
TIMEOUT,
|
||||
)
|
||||
|
||||
|
||||
def test_no_error(lora_rl_process: ProcessResult, output_dir: Path):
|
||||
if lora_rl_process.returncode != 0:
|
||||
print("=== VLLM STDOUT ===")
|
||||
with open(output_dir / "vllm.stdout", "r") as f:
|
||||
print(*f.readlines()[-40:], sep="\n")
|
||||
print("=== VLLM STDERR ===")
|
||||
with open(output_dir / "vllm.stderr", "r") as f:
|
||||
print(*f.readlines()[-40:], sep="\n")
|
||||
print("=== ORCHESTRATOR STDOUT ===")
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
print(*f.readlines()[-100:], sep="\n")
|
||||
assert lora_rl_process.returncode == 0, f"RL process failed with return code {lora_rl_process.returncode}"
|
||||
|
||||
|
||||
def test_no_error_resume(lora_rl_resume_process: ProcessResult, output_dir: Path):
|
||||
if lora_rl_resume_process.returncode != 0:
|
||||
print("=== RESUME VLLM STDOUT ===")
|
||||
with open(output_dir / "vllm.stdout", "r") as f:
|
||||
print(*f.readlines()[-40:], sep="\n")
|
||||
print("=== RESUME VLLM STDERR ===")
|
||||
with open(output_dir / "vllm.stderr", "r") as f:
|
||||
print(*f.readlines()[-40:], sep="\n")
|
||||
print("=== RESUME ORCHESTRATOR STDOUT ===")
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
print(*f.readlines()[-100:], sep="\n")
|
||||
assert lora_rl_resume_process.returncode == 0, (
|
||||
f"RL resume process failed with return code {lora_rl_resume_process.returncode}"
|
||||
)
|
||||
|
||||
|
||||
def test_check_reward(output_dir: Path, lora_rl_resume_process: ProcessResult):
|
||||
if lora_rl_resume_process.returncode != 0:
|
||||
pytest.skip("RL resume process failed")
|
||||
wandb_paths = [i for i in output_dir.glob("run-*")]
|
||||
wandb_summaries = [json.load(open(i / "final_summary.json")) for i in wandb_paths]
|
||||
assert len(wandb_paths) == 2
|
||||
for wandb_summary in wandb_summaries:
|
||||
assert "reward/mean" in wandb_summary
|
||||
assert wandb_summary["reward/mean"] > 0.65
|
||||
|
||||
|
||||
# would need the setup a vllm server with the nccl broadcast enabled to make this work
|
||||
@pytest.mark.skip(reason="Skipping NCCL broadcast as it fail only in ci")
|
||||
def test_rl_nccl(run_process):
|
||||
process = run_process(
|
||||
RL_CMD + ["--weight-broadcast.type", "nccl"],
|
||||
{},
|
||||
TIMEOUT,
|
||||
)
|
||||
assert process.returncode == 0, f"RL process failed with return code {process.returncode}"
|
||||
@@ -1,55 +0,0 @@
|
||||
import pytest
|
||||
from openai import OpenAI
|
||||
from openai.types.chat.chat_completion import ChatCompletion
|
||||
|
||||
from prime_rl.orchestrator.config import SamplingConfig
|
||||
from prime_rl.orchestrator.utils import get_sampling_args
|
||||
|
||||
# Needs GPU flag because requires vLLM server for testing
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client():
|
||||
return OpenAI(base_url="http://localhost:8000/v1", api_key="")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def model_name() -> str:
|
||||
return "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def prompt() -> list[dict]:
|
||||
return [{"role": "user", "content": "Hello, how are you?"}]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def response(vllm_server, client: OpenAI, model_name: str, prompt) -> ChatCompletion:
|
||||
sampling_config = SamplingConfig(max_tokens=10)
|
||||
sampling_args = get_sampling_args(sampling_config)
|
||||
|
||||
return client.chat.completions.create(
|
||||
model=model_name,
|
||||
messages=prompt,
|
||||
**sampling_args,
|
||||
)
|
||||
|
||||
|
||||
def test_token_ids_in_response(response: ChatCompletion):
|
||||
response_dict = response.model_dump()
|
||||
assert "prompt_token_ids" in response_dict, "prompt_token_ids should be present in the response"
|
||||
assert len(response_dict["choices"]) == 1, "response should have one choice"
|
||||
assert "token_ids" in response_dict["choices"][0], "token_ids should be present in the response"
|
||||
|
||||
|
||||
def test_logprobs_in_response(response: ChatCompletion):
|
||||
response_dict = response.model_dump()
|
||||
assert "logprobs" in response_dict["choices"][0], "logprobs should be present in the response"
|
||||
|
||||
|
||||
def test_token_ids_and_logprobs_match(response: ChatCompletion):
|
||||
response_dict = response.model_dump()
|
||||
token_ids = response_dict["choices"][0]["token_ids"]
|
||||
logprobs = response_dict["choices"][0]["logprobs"]["content"]
|
||||
assert len(token_ids) == len(logprobs), "token_ids and logprobs should have the same length"
|
||||
@@ -1,25 +1,52 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests import Command, Environment, ProcessResult
|
||||
from tests.conftest import Command, Environment, ProcessResult
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
|
||||
|
||||
CMD = [
|
||||
"uv",
|
||||
"run",
|
||||
"eval",
|
||||
"@",
|
||||
"configs/debug/eval.toml",
|
||||
]
|
||||
ENV = {"CUDA_VISIBLE_DEVICES": "1"}
|
||||
pytestmark = [pytest.mark.slow]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def eval_process(vllm_server, run_process: Callable[[Command, Environment], ProcessResult]) -> ProcessResult:
|
||||
return run_process(CMD, ENV)
|
||||
def single_env_eval_process(
|
||||
run_process: Callable[[Command, Environment], ProcessResult], output_dir: Path
|
||||
) -> ProcessResult:
|
||||
"""Fixture for running single-env eval CI integration test"""
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"eval",
|
||||
"@",
|
||||
"configs/ci/integration/eval/single_env.toml",
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, {})
|
||||
|
||||
|
||||
def test_no_error(eval_process: ProcessResult):
|
||||
assert eval_process.returncode == 0, f"Eval process failed with return code {eval_process.returncode}"
|
||||
@pytest.fixture(scope="module")
|
||||
def multi_env_eval_process(
|
||||
run_process: Callable[[Command, Environment], ProcessResult], output_dir: Path
|
||||
) -> ProcessResult:
|
||||
"""Fixture for running multi-env eval CI integration test"""
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"eval",
|
||||
"@",
|
||||
"configs/ci/integration/eval/multi_env.toml",
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, {})
|
||||
|
||||
|
||||
def test_no_error_single_env(single_env_eval_process: ProcessResult):
|
||||
"""Tests that the single environment eval process does not fail."""
|
||||
assert single_env_eval_process.returncode == 0, f"Process has non-zero return code ({single_env_eval_process})"
|
||||
|
||||
|
||||
def test_no_error_multi_env(multi_env_eval_process: ProcessResult):
|
||||
"""Tests that the multi environment eval process does not fail."""
|
||||
assert multi_env_eval_process.returncode == 0, f"Process has non-zero return code ({multi_env_eval_process})"
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests import Command, Environment, ProcessResult
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
|
||||
|
||||
CMD = [
|
||||
"uv",
|
||||
"run",
|
||||
"orchestrator",
|
||||
"@",
|
||||
"configs/debug/orch.toml",
|
||||
"--model.name",
|
||||
"PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def orchestrator_process(
|
||||
vllm_server, run_process: Callable[[Command, Environment], ProcessResult], output_dir: Path
|
||||
) -> ProcessResult:
|
||||
return run_process(CMD + ["--output-dir", output_dir.as_posix()], {})
|
||||
|
||||
|
||||
def test_no_error(orchestrator_process: ProcessResult):
|
||||
assert orchestrator_process.returncode == 0, (
|
||||
f"Orchestrator process failed with return code {orchestrator_process.returncode}"
|
||||
)
|
||||
+81
-112
@@ -1,145 +1,114 @@
|
||||
import json
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests import Command, Environment, ProcessResult
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_number_goes_up_or_down, check_number_in_range, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
|
||||
TIMEOUT = 600 # 10 minutes
|
||||
RL_CMD = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"--trainer",
|
||||
"@",
|
||||
"configs/reverse_text/rl/train.toml",
|
||||
"--orchestrator",
|
||||
"@",
|
||||
"configs/reverse_text/rl/orch.toml",
|
||||
"--orchestrator.sampling.max-tokens",
|
||||
"128",
|
||||
"--ckpt",
|
||||
]
|
||||
RL_RESUME_CMD = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"--trainer",
|
||||
"@",
|
||||
"configs/reverse_text/rl/train.toml",
|
||||
"--orchestrator",
|
||||
"@",
|
||||
"configs/reverse_text/rl/orch.toml",
|
||||
"--orchestrator.sampling.max-tokens",
|
||||
"128",
|
||||
"--max-steps",
|
||||
"25",
|
||||
"--ckpt.resume-step",
|
||||
"20",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_project(username: str) -> str:
|
||||
project = "ci-reverse-text-rl"
|
||||
if username != "CI_RUNNER":
|
||||
project += "-local"
|
||||
return project
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"test-rl-{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def full_weight_rl_process(
|
||||
vllm_server, # Can only run with vLLM server
|
||||
run_process: Callable[[Command, Environment, int], ProcessResult],
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
branch_name: str,
|
||||
commit_hash: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
wandb_name = f"{branch_name}-{commit_hash}"
|
||||
|
||||
return run_process(
|
||||
RL_CMD + ["--wandb.project", wandb_project, "--wandb.name", wandb_name, "--output-dir", output_dir.as_posix()],
|
||||
{},
|
||||
TIMEOUT,
|
||||
)
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl/start.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def full_weight_rl_resume_process(
|
||||
vllm_server, # Can only run with vLLM server
|
||||
full_weight_rl_process, # Resume training can only start when regular RL process is finished
|
||||
run_process: Callable[[Command, Environment, int], ProcessResult],
|
||||
def rl_resume_process(
|
||||
rl_process, # Resume training can only start when regular RL process is finished
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
branch_name: str,
|
||||
commit_hash: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
if full_weight_rl_process.returncode != 0:
|
||||
if rl_process.returncode != 0:
|
||||
pytest.skip("Full weight RL process failed")
|
||||
wandb_name = f"{branch_name}-{commit_hash}-resume"
|
||||
wandb_name = f"{wandb_name}-resume"
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl/resume.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
|
||||
return run_process(
|
||||
RL_RESUME_CMD
|
||||
+ ["--wandb.project", wandb_project, "--wandb.name", wandb_name, "--output-dir", output_dir.as_posix()],
|
||||
{},
|
||||
TIMEOUT,
|
||||
)
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
def test_no_error(full_weight_rl_process: ProcessResult, output_dir: Path):
|
||||
if full_weight_rl_process.returncode != 0:
|
||||
print("=== VLLM STDOUT ===")
|
||||
with open(output_dir / "vllm.stdout", "r") as f:
|
||||
print(*f.readlines()[-40:], sep="\n")
|
||||
print("=== VLLM STDERR ===")
|
||||
with open(output_dir / "vllm.stderr", "r") as f:
|
||||
print(*f.readlines()[-40:], sep="\n")
|
||||
print("=== ORCHESTRATOR STDOUT ===")
|
||||
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
check_reward_in_range = partial(check_number_in_range, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
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(output_dir / "logs" / "orchestrator.stdout", "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, output_dir: Path):
|
||||
"""Tests that the reward is in range in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
|
||||
|
||||
|
||||
@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."""
|
||||
if rl_resume_process.returncode != 0:
|
||||
print("=== Inference Outputs ===")
|
||||
with open(output_dir / "logs" / "inference.stdout", "r") as f:
|
||||
print(*f.readlines()[-100:], sep="\n")
|
||||
print("=== Orchestrator Outputs ===")
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
print(*f.readlines()[-100:], sep="\n")
|
||||
assert full_weight_rl_process.returncode == 0, (
|
||||
f"RL process failed with return code {full_weight_rl_process.returncode}"
|
||||
)
|
||||
assert rl_resume_process.returncode == 0, f"Process has non-zero return code ({rl_resume_process})"
|
||||
|
||||
|
||||
def test_no_error_resume(full_weight_rl_resume_process: ProcessResult, output_dir: Path):
|
||||
if full_weight_rl_resume_process.returncode != 0:
|
||||
print("=== RESUME VLLM STDOUT ===")
|
||||
with open(output_dir / "vllm.stdout", "r") as f:
|
||||
print(*f.readlines()[-40:], sep="\n")
|
||||
print("=== RESUME VLLM STDERR ===")
|
||||
with open(output_dir / "vllm.stderr", "r") as f:
|
||||
print(*f.readlines()[-40:], sep="\n")
|
||||
print("=== RESUME ORCHESTRATOR STDOUT ===")
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
print(*f.readlines()[-100:], sep="\n")
|
||||
assert full_weight_rl_resume_process.returncode == 0, (
|
||||
f"RL resume process failed with return code {full_weight_rl_resume_process.returncode}"
|
||||
)
|
||||
|
||||
|
||||
def test_check_reward(output_dir: Path, full_weight_rl_resume_process: ProcessResult):
|
||||
if full_weight_rl_resume_process.returncode != 0:
|
||||
pytest.skip("Full weight RL resume process failed")
|
||||
wandb_paths = [i for i in output_dir.glob("run-*")]
|
||||
wandb_summaries = [json.load(open(i / "final_summary.json")) for i in wandb_paths]
|
||||
assert len(wandb_paths) == 2
|
||||
for wandb_summary in wandb_summaries:
|
||||
assert "reward/mean" in wandb_summary
|
||||
assert wandb_summary["reward/mean"] > 0.65
|
||||
|
||||
|
||||
# would need the setup a vllm server with the nccl broadcast enabled to make this work
|
||||
@pytest.mark.skip(reason="Skipping NCCL broadcast as it fail only in ci")
|
||||
def test_rl_nccl(run_process):
|
||||
process = run_process(
|
||||
RL_CMD + ["--weight-broadcast.type", "nccl"],
|
||||
{},
|
||||
TIMEOUT,
|
||||
)
|
||||
assert process.returncode == 0, f"RL process failed with return code {process.returncode}"
|
||||
def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_resume, output_dir: Path):
|
||||
"""Tests that the reward is in range in the RL resume process"""
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_number_goes_up_or_down, check_number_in_range, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
|
||||
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}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_lora/start.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, env={"VLLM_ALLOW_RUNTIME_LORA_UPDATING": "True"}, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_resume_process(
|
||||
rl_process, # Resume training can only start when regular RL process is finished
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
if rl_process.returncode != 0:
|
||||
pytest.skip("Full weight RL process failed")
|
||||
wandb_name += "-resume"
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_lora/resume.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
|
||||
return run_process(cmd, env={"VLLM_ALLOW_RUNTIME_LORA_UPDATING": "True"}, timeout=TIMEOUT)
|
||||
|
||||
|
||||
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
check_reward_in_range = partial(check_number_in_range, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
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(output_dir / "logs" / "orchestrator.stdout", "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, output_dir: Path):
|
||||
"""Tests that the reward is in range in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
|
||||
|
||||
|
||||
@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."""
|
||||
check_no_error(rl_resume_process, output_dir)
|
||||
|
||||
|
||||
def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_resume, output_dir: Path):
|
||||
"""Tests that the reward is in range in the RL resume process"""
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
|
||||
@@ -1,115 +1,111 @@
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests import Command, Environment, ProcessResult
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_number_goes_up_or_down, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
|
||||
|
||||
TIMEOUT = 300 # 5 minutes
|
||||
ENV = {"CUDA_VISIBLE_DEVICES": "1"}
|
||||
SFT_CMD = ["uv", "run", "sft", "@", "configs/reverse_text/sft/train.toml", "--max-steps", "10", "--ckpt"]
|
||||
SFT_RESUME_CMD = [
|
||||
"uv",
|
||||
"run",
|
||||
"sft",
|
||||
"@",
|
||||
"configs/reverse_text/sft/train.toml",
|
||||
"--max-steps",
|
||||
"20",
|
||||
"--ckpt.resume-step",
|
||||
"10",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_project(username: str) -> str:
|
||||
project = "ci-reverse-text-sft"
|
||||
if username != "CI_RUNNER":
|
||||
project += "-local"
|
||||
return project
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for SFT CI integration tests."""
|
||||
return f"test-sft-{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def sft_process(
|
||||
run_process: Callable[[Command, Environment, int], ProcessResult],
|
||||
output_dir: Path,
|
||||
run_process: Callable[..., ProcessResult],
|
||||
wandb_project: str,
|
||||
branch_name: str,
|
||||
commit_hash: str,
|
||||
wandb_name: str,
|
||||
output_dir: Path,
|
||||
) -> ProcessResult:
|
||||
wandb_name = f"{branch_name}-{commit_hash}"
|
||||
"""Fixture for running SFT CI integration test"""
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"torchrun",
|
||||
"--local-ranks-filter",
|
||||
"0",
|
||||
"--nproc-per-node",
|
||||
"2",
|
||||
"src/prime_rl/trainer/sft/train.py",
|
||||
"@",
|
||||
"configs/ci/integration/sft/start.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
|
||||
return run_process(
|
||||
SFT_CMD
|
||||
+ [
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
],
|
||||
ENV,
|
||||
TIMEOUT,
|
||||
)
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@pytest.fixture(scope="module")
|
||||
def sft_resume_process(
|
||||
sft_process, # Resume training can only start when regular SFT process is finished
|
||||
run_process: Callable[[Command, Environment, int], ProcessResult],
|
||||
output_dir: Path,
|
||||
run_process: Callable[..., ProcessResult],
|
||||
wandb_project: str,
|
||||
branch_name: str,
|
||||
commit_hash: str,
|
||||
) -> ProcessResult:
|
||||
wandb_name = f"{branch_name}-{commit_hash}-resume"
|
||||
|
||||
return run_process(
|
||||
SFT_RESUME_CMD
|
||||
+ [
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
],
|
||||
ENV,
|
||||
TIMEOUT,
|
||||
)
|
||||
|
||||
|
||||
SFT_CMD_MOE = ["uv", "run", "sft", "@", "configs/debug/moe/sft/train.toml"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sft_moe_process(
|
||||
run_process: Callable[[Command, Environment, int], ProcessResult],
|
||||
wandb_name: str,
|
||||
output_dir: Path,
|
||||
) -> ProcessResult:
|
||||
return run_process(
|
||||
SFT_CMD_MOE
|
||||
+ [
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
],
|
||||
ENV,
|
||||
TIMEOUT,
|
||||
)
|
||||
"""Fixture for resuming SFT CI integration test"""
|
||||
wandb_name += "-resume"
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"torchrun",
|
||||
"--local-ranks-filter",
|
||||
"0",
|
||||
"--nproc-per-node",
|
||||
"2",
|
||||
"src/prime_rl/trainer/sft/train.py",
|
||||
"@",
|
||||
"configs/ci/integration/sft/resume.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
check_loss_goes_down = partial(check_number_goes_up_or_down, go_up=False, pattern=r"Loss:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
def test_no_error(sft_process: ProcessResult):
|
||||
assert sft_process.returncode == 0, f"SFT process failed with return code {sft_process.returncode}"
|
||||
"""Tests that the SFT process does not fail."""
|
||||
assert sft_process.returncode == 0, f"Process has non-zero return code ({sft_process})"
|
||||
|
||||
|
||||
def test_loss_goes_down(sft_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the loss goes down in the SFT process"""
|
||||
trainer_log_path = output_dir / "logs" / "trainer" / "rank_0.log"
|
||||
print(f"Checking trainer path in {trainer_log_path}")
|
||||
with open(trainer_log_path, "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_loss_goes_down(trainer_stdout)
|
||||
|
||||
|
||||
def test_no_error_resume(sft_resume_process: ProcessResult):
|
||||
assert sft_resume_process.returncode == 0, (
|
||||
f"SFT resume process failed with return code {sft_resume_process.returncode}"
|
||||
)
|
||||
"""Tests that the SFT resume process does not fail."""
|
||||
assert sft_resume_process.returncode == 0, f"Process has non-zero return code ({sft_resume_process})"
|
||||
|
||||
|
||||
def test_no_error_moe(sft_moe_process: ProcessResult):
|
||||
assert sft_moe_process.returncode == 0, f"SFT MOE process failed with return code {sft_moe_process.returncode}"
|
||||
def test_loss_goes_down_resume(sft_resume_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the loss goes down in the SFT resume process"""
|
||||
trainer_log_path = output_dir / "logs" / "trainer" / "rank_0.log"
|
||||
print(f"Checking trainer path in {trainer_log_path}")
|
||||
with open(trainer_log_path, "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_loss_goes_down(trainer_stdout)
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import Command, Environment, ProcessResult
|
||||
|
||||
pytestmark = [pytest.mark.slow]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def single_env_synthesize_process(
|
||||
run_process: Callable[[Command, Environment], ProcessResult], output_dir: Path
|
||||
) -> ProcessResult:
|
||||
"""Fixture for running single-env synthesize CI integration test"""
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"synthesize",
|
||||
"@",
|
||||
"configs/ci/integration/synthesize/single_env.toml",
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, {})
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def multi_env_synthesize_process(
|
||||
run_process: Callable[[Command, Environment], ProcessResult], output_dir: Path
|
||||
) -> ProcessResult:
|
||||
"""Fixture for running multi-env synthesize CI integration test"""
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"synthesize",
|
||||
"@",
|
||||
"configs/ci/integration/synthesize/multi_env.toml",
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, {})
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def multi_turn_tool_call_synthesize_process(
|
||||
run_process: Callable[[Command, Environment], ProcessResult],
|
||||
output_dir: Path,
|
||||
) -> ProcessResult:
|
||||
"""Fixture for running multi-turn tool call synthesize CI integration test"""
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"synthesize",
|
||||
"@",
|
||||
"configs/ci/integration/synthesize/multi_turn_tool_call.toml",
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, {})
|
||||
|
||||
|
||||
def test_no_error_single_env(single_env_synthesize_process: ProcessResult):
|
||||
"""Tests that the single environment synthesize process does not fail."""
|
||||
assert single_env_synthesize_process.returncode == 0, (
|
||||
f"Process has non-zero return code ({single_env_synthesize_process})"
|
||||
)
|
||||
|
||||
|
||||
def test_no_error_multi_env(multi_env_synthesize_process: ProcessResult):
|
||||
"""Tests that the multi-env synthesize process does not fail."""
|
||||
assert multi_env_synthesize_process.returncode == 0, (
|
||||
f"Process has non-zero return code ({multi_env_synthesize_process})"
|
||||
)
|
||||
|
||||
|
||||
def test_no_error_multi_turn_tool_call(multi_turn_tool_call_synthesize_process: ProcessResult):
|
||||
"""Tests that the multi-turn tool call synthesize process does not fail."""
|
||||
assert multi_turn_tool_call_synthesize_process.returncode == 0, (
|
||||
f"Process has non-zero return code ({multi_turn_tool_call_synthesize_process})"
|
||||
)
|
||||
@@ -1,19 +0,0 @@
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests import Command, Environment, ProcessResult
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
|
||||
|
||||
ENV = {"CUDA_VISIBLE_DEVICES": "1"}
|
||||
CMD = ["uv", "run", "trainer", "@", "configs/debug/rl/train.toml"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def train_process(run_process: Callable[[Command, Environment], ProcessResult]) -> ProcessResult:
|
||||
return run_process(CMD, ENV)
|
||||
|
||||
|
||||
def test_no_error(train_process: ProcessResult):
|
||||
assert train_process.returncode == 0, f"Train process failed with return code {train_process.returncode}"
|
||||
@@ -0,0 +1,9 @@
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_project(get_wandb_project: Callable[[str], str]) -> str:
|
||||
"""Fixture for W&B project name for integration tests. This means all integration tests will use the same W&B project."""
|
||||
return get_wandb_project("nightly-tests")
|
||||
@@ -0,0 +1,55 @@
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_number_goes_up_or_down, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"acereason-math-{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/nightly/acereason_math.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
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(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
@@ -0,0 +1,55 @@
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_number_goes_up_or_down, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"alphabet-sort-{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/nightly/alphabet_sort.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
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(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
@@ -0,0 +1,55 @@
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_number_goes_up_or_down, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"hendrycks-math-{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/nightly/hendrycks_math.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
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(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
@@ -0,0 +1,55 @@
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_number_goes_up_or_down, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"reverse-text-{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/nightly/reverse_text.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
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(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
@@ -0,0 +1,55 @@
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_number_goes_up_or_down, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"wiki-search-{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/nightly/wiki_search.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
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(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
@@ -1,23 +0,0 @@
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from prime_rl.trainer import envs
|
||||
|
||||
|
||||
def test_training_env_defaults():
|
||||
"""Test default values for training environment variables"""
|
||||
assert envs.RANK == 0
|
||||
|
||||
|
||||
def test_training_env_custom_values():
|
||||
"""Test custom values for training environment variables"""
|
||||
os.environ.update({"RANK": "1"})
|
||||
|
||||
assert envs.RANK == 1
|
||||
|
||||
|
||||
def test_invalid_env_vars():
|
||||
"""Test that accessing invalid environment variables raises AttributeError"""
|
||||
with pytest.raises(AttributeError):
|
||||
envs.INVALID_VAR
|
||||
@@ -1,8 +0,0 @@
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.utils.logger import reset_logger, setup_logger
|
||||
|
||||
|
||||
def test_setup_default():
|
||||
reset_logger()
|
||||
setup_logger("info", log_file=Path("test") / "logs" / "test.log")
|
||||
@@ -1,5 +1,4 @@
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -36,22 +35,6 @@ def test_init_with_valid_env_vars(local_world_size: int, world_size: int):
|
||||
assert world == get_world()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("local_world_size", [1, 2])
|
||||
def test_init_with_torchrun(local_world_size: int):
|
||||
path = "src/prime_rl/trainer/world.py"
|
||||
assert os.path.exists(path)
|
||||
cmd = ["torchrun", f"--nproc_per_node={local_world_size}", path]
|
||||
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
stdout, stderr = process.communicate()
|
||||
if process.returncode != 0:
|
||||
error_msg = (
|
||||
stderr.decode("utf-8").strip()
|
||||
or stdout.decode("utf-8").strip()
|
||||
or f"Process failed with code {process.returncode}"
|
||||
)
|
||||
pytest.fail(f"Process failed: {error_msg}")
|
||||
|
||||
|
||||
def test_init_with_invalid_local_world_size():
|
||||
os.environ["WORLD_SIZE"] = "1"
|
||||
os.environ["LOCAL_WORLD_SIZE"] = "2"
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
|
||||
|
||||
def strip_escape_codes(text: str) -> str:
|
||||
"""Helper to strip escape codes from text"""
|
||||
return re.sub(r"\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", "", text)
|
||||
|
||||
|
||||
def check_no_error(process: ProcessResult, output_dir: Path) -> None:
|
||||
"""Helper to assert that a process did not error"""
|
||||
if process.returncode != 0:
|
||||
print("=== Inference Outputs ===")
|
||||
with open(output_dir / "logs" / "inference.stdout", "r") as f:
|
||||
print(*f.readlines()[-100:], sep="\n")
|
||||
print("=== Orchestrator Outputs ===")
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
print(*f.readlines()[-100:], sep="\n")
|
||||
assert process.returncode == 0, f"Process has non-zero return code ({process})"
|
||||
|
||||
|
||||
def check_number_goes_up_or_down(
|
||||
lines: list[str],
|
||||
start_step: int = 0,
|
||||
end_step: int = -1,
|
||||
pattern: str = r"Reward:\s*(\d+\.\d{4})",
|
||||
go_up: bool = True,
|
||||
):
|
||||
"""Helper to assert that a number in lines goes up from a specified start to end step"""
|
||||
step_lines = [line for line in lines if "Step" in line]
|
||||
assert len(step_lines) > 0, f"No step lines found in output ({lines})"
|
||||
try:
|
||||
start_step_line = step_lines[start_step]
|
||||
except IndexError:
|
||||
start_step_line = ""
|
||||
try:
|
||||
end_step_line = step_lines[end_step]
|
||||
except IndexError:
|
||||
end_step_line = ""
|
||||
assert start_step_line, f"Could not find start step {start_step} in output ({lines})"
|
||||
assert end_step_line, f"Could not find end step {end_step} in output ({lines})"
|
||||
start_step_match = re.search(pattern, start_step_line)
|
||||
end_step_match = re.search(pattern, end_step_line)
|
||||
assert start_step_match is not None, (
|
||||
f"Could not find number for start step {start_step} in line {start_step_line} ({lines})"
|
||||
)
|
||||
assert end_step_match is not None, (
|
||||
f"Could not find number for end step {end_step} in line {end_step_line} ({lines})"
|
||||
)
|
||||
start_step_number = float(start_step_match.group(1))
|
||||
end_step_number = float(end_step_match.group(1))
|
||||
if go_up:
|
||||
assert start_step_number < end_step_number, (
|
||||
f"Number did not go up. Found start_number={start_step_number} <= end_number={end_step_number} "
|
||||
f"(start line: {start_step_line}, end line: {end_step_line}) ({lines})"
|
||||
)
|
||||
else:
|
||||
assert start_step_number > end_step_number, (
|
||||
f"Number did not go down. Found start_number={start_step_number} >= end_number={end_step_number} "
|
||||
f"(start line: {start_step_line}, end line: {end_step_line}) ({lines})"
|
||||
)
|
||||
|
||||
|
||||
def check_number_in_range(
|
||||
lines: list[str],
|
||||
step: int = -1,
|
||||
min_threshold: float | None = 0.0,
|
||||
max_threshold: float | None = None,
|
||||
pattern: str = r"Reward:\s*(\d+\.\d{4})",
|
||||
):
|
||||
"""Helper to assert that a number in step logs is within a threshold"""
|
||||
step_lines = [line for line in lines if "Step" in line]
|
||||
assert len(step_lines) > 0, f"No step lines found in output ({lines})"
|
||||
try:
|
||||
step_line = step_lines[step]
|
||||
except IndexError:
|
||||
step_line = ""
|
||||
assert step_line, f"Could not find step {step} in output ({lines})"
|
||||
step_reward = re.search(pattern, step_line)
|
||||
assert step_reward is not None, f"Could not find reward for step {step}. Line: {step_line} ({lines})"
|
||||
step_reward = float(step_reward.group(1))
|
||||
if min_threshold is not None:
|
||||
assert step_reward >= min_threshold, (
|
||||
f"Reward did not reach minimum threshold. Found reward={step_reward} < {min_threshold} "
|
||||
f"(line: {step_line}) ({lines})"
|
||||
)
|
||||
if max_threshold is not None:
|
||||
assert step_reward <= max_threshold, (
|
||||
f"Reward did not reach maximum threshold. Found reward={step_reward} > {max_threshold} "
|
||||
f"(line: {step_line}) ({lines})"
|
||||
)
|
||||
Reference in New Issue
Block a user