env worker integration (#1714)
* start env servers for env group * bump * working reverse-text * correctly set log levels * use client configs everywhere + make val work * cycle through clients via inference pool * update model name * deprecate env worker * implement evals * deprecate evals+synthesize * deprecate serialization * use all clients for evals * simplify config * fix types and use inference pool for opd * bring back logging intercept * setup env client/server in prime-rl * externalize running env server * style * bring back rate limiter on scheduler * revert vf branch * back to custom branch * do not double asyncio * bring back eval * fix cpu tests * bump vf * add math group config * remove stop server call * add logs * remove last mentions of vf.State * deprecate some configs * more * remove eval + cpu integration tests * remove evals + synthesize configs * bump vf * fix branch with vlm cache * do not reference rollout status * use correct model name * stop teacher infer pool if setup * update changelog * deprecate server discovery (unused) * fix env id stripping * use updated model name for evals * strip env version on env server * remove server discovery tests * bump vf * do not fail if env server not yet up * add elastic sanity check * update docs * use extra env kwargs consistently across orch and env server * update math group config * update cfg * use dynamic model name in final evals * add extra_env_kwargs to changelog * resolve vf merge conflicts * assert lora name not None * fix unit tests * fix types * add hendrycks math sanity check * bump vf * do not double repeat eval inputs * do not duplicate eval inputs * lower avg@ * Initialize logger in env-server before install_env (#1743) install_env() calls get_logger() which requires the logger to be set up first. This was missing in env-server but present in orchestrator. * disable vf logging on orch * Fix elastic autoscaling: use base model for health checks (#1745) The health check was using `model_name` which gets updated to the LoRA adapter name after training starts. New inference servers only have the base model, so they would fail health checks and never get added to the pool. Store the original model name as `base_model_name` and use it for health checks, allowing new servers to be discovered and have the LoRA adapter loaded on them. --------- Co-authored-by: JannikSt <JannikSt@users.noreply.github.com> Co-authored-by: William Brown <williambrown97@gmail.com>
This commit is contained in:
co-authored by
JannikSt
William Brown
parent
125012f8d7
commit
31b48b8b10
@@ -38,35 +38,3 @@ jobs:
|
||||
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 --all-extras --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
|
||||
|
||||
@@ -50,3 +50,8 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`model.cp`**: When `cp>1` with `attn="flash_attention_3"`, require `model.impl="custom"` (FA3 ring-attention kernel only in custom path) (2026-02-06)
|
||||
- **`model.attn`**: Added `fa4` as an attention implementation option. Flash attention 4 is only supported with the custom implementation (#1726, 2026-02-06)
|
||||
- **`inference.model.enable_prefix_caching`**: Added flag to enable prefix caching in vLLM. Passed to vLLM as `--enable-prefix-caching` (default: None) (2026-02-08)
|
||||
- **`orchestrator.env.address`**: Added address field on `EnvConfig`. If set, connect to an environment server at this address; if None, spawn a server in a subprocess (2026-02-06)
|
||||
- **`orchestrator.env.extra_env_kwargs`**: Added on `EnvConfig`. Extra kwargs passed to the env (e.g. seq_len, interleaved_rollouts, score_rollouts). Auto-populated by the orchestrator for training envs; generally not recommended for user override. Main use case is to match these kwargs when running an env in an isolated environment server (default: {}) (2026-02-06)
|
||||
- **`OrchestratorConfig`**: Removed `workers_per_env`, `max_env_worker_restarts`, and `mask_env_responses` (2026-02-06)
|
||||
- **`EvalSaveDiskConfig`**, **`EvalSaveConfig`**, **`RetryConfig`**, **`OnlineEvalConfig`**: Removed (2026-02-06)
|
||||
- **`TemperatureScheduleConfig`**: Renamed to `TemperatureSchedulerConfig` (2026-02-06)
|
||||
@@ -1,15 +0,0 @@
|
||||
num_examples = 5
|
||||
rollouts_per_example = 3
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
name = "hendrycks"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
@@ -1,9 +0,0 @@
|
||||
num_examples = 5
|
||||
rollouts_per_example = 3
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
@@ -1,15 +0,0 @@
|
||||
num_examples = 5
|
||||
rollouts_per_example = 3
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
name = "hendrycks"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
@@ -1,8 +0,0 @@
|
||||
num_examples = 5
|
||||
rollouts_per_example = 3
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
@@ -1,9 +0,0 @@
|
||||
num_examples = 5
|
||||
rollouts_per_example = 3
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
@@ -1,4 +0,0 @@
|
||||
use_tqdm = true
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
@@ -1,13 +0,0 @@
|
||||
# Example of generating data in two single-turn environments (gsm8k and hendrycks)
|
||||
num_examples = 16
|
||||
rollouts_per_example = 4
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
name = "hendrycks"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
@@ -1,7 +0,0 @@
|
||||
# Example of generating data in a single single-turn environment (gsm8k)
|
||||
num_examples = 16
|
||||
rollouts_per_example = 4
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
@@ -1,13 +0,0 @@
|
||||
# Example of generating data in two single-turn environments (gsm8k and hendrycks)
|
||||
num_examples = 16
|
||||
rollouts_per_example = 4
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
name = "hendrycks"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
@@ -1,7 +0,0 @@
|
||||
# Example of generating data in a multi-turn environment (alphabet-sort)
|
||||
num_examples = 16
|
||||
rollouts_per_example = 4
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2 }
|
||||
@@ -1,6 +0,0 @@
|
||||
# Example of generating data in a multi-turn environment with tool calls
|
||||
num_examples = 16
|
||||
rollouts_per_example = 4
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
@@ -1,7 +0,0 @@
|
||||
# Example of generating data in a single single-turn environment (gsm8k)
|
||||
num_examples = 16
|
||||
rollouts_per_example = 4
|
||||
|
||||
[[env]]
|
||||
id = "primeintellect/math-env"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
@@ -1,12 +0,0 @@
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[[env]]
|
||||
id = "math500"
|
||||
args = { use_think = true }
|
||||
rollouts_per_example = 1
|
||||
|
||||
[[env]]
|
||||
id = "aime2024"
|
||||
args = { use_think = true }
|
||||
rollouts_per_example = 16
|
||||
@@ -0,0 +1,17 @@
|
||||
# Testing Elastic Inference
|
||||
|
||||
To test the elastic inference pool without having the `rl` entrypoint start the inference server:
|
||||
|
||||
1. **Run RL with the elastic config** (orchestrator discovers servers via DNS; it will find `localhost:8000` once the server is started):
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/alphabet_sort/rl_elastic.toml
|
||||
```
|
||||
|
||||
The config uses `[orchestrator.client.elastic]` with `hostname = "localhost"` and `port = 8000`. The orchestrator will wait for at least one ready server before starting rollouts.
|
||||
|
||||
2. **Start the inference server manually** (in a separate terminal or on another machine):
|
||||
|
||||
```bash
|
||||
uv run inference --model.name Qwen/Qwen3-4B-Instruct-2507 --enable-lora --max-lora-rank 32
|
||||
```
|
||||
@@ -0,0 +1,46 @@
|
||||
# Alphabet sort RL with elastic inference pool (no inference process started by rl).
|
||||
# Start the inference server manually first, then run: uv run rl @ examples/alphabet_sort/rl_elastic.toml
|
||||
# The orchestrator discovers servers via DNS (hostname) and only uses ready ones.
|
||||
# Omitting [inference] means inference = None, so the rl entrypoint will not start an inference process.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[wandb]
|
||||
project = "alphabet-sort"
|
||||
name = "alphabet-sort-elastic"
|
||||
|
||||
[trainer.model]
|
||||
impl = "auto"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 32
|
||||
alpha = 64
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 768
|
||||
|
||||
[orchestrator.client.elastic]
|
||||
hostname = "localhost"
|
||||
port = 8000
|
||||
sync_interval = 5.0
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
@@ -1,5 +0,0 @@
|
||||
[sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[env]]
|
||||
id = "math500"
|
||||
@@ -0,0 +1,42 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 3000
|
||||
seq_len = 8192
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-math-debug"
|
||||
name = "hendrycks-math-sanity"
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/math-env"
|
||||
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
name = "hendrycks-math"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/aime2024"
|
||||
name = "aime2024"
|
||||
rollouts_per_example = 16
|
||||
|
||||
[trainer.model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 8192
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
@@ -1,5 +0,0 @@
|
||||
max_concurrent = 128
|
||||
|
||||
[client]
|
||||
base_url = ["https://api.deepseek.com"]
|
||||
api_key_var = "DEEPSEEK_API_KEY"
|
||||
@@ -1,6 +0,0 @@
|
||||
max_concurrent = 128
|
||||
|
||||
[client]
|
||||
base_url = ["https://api.fireworks.ai/inference/v1"]
|
||||
|
||||
api_key_var = "FIREWORKS_API_KEY"
|
||||
@@ -1,4 +0,0 @@
|
||||
max_concurrent = 1024
|
||||
|
||||
[client]
|
||||
base_url = [ "http://localhost:8000/v1" ]
|
||||
@@ -1,8 +0,0 @@
|
||||
max_concurrent = 256
|
||||
|
||||
[client]
|
||||
base_url = ["https://openrouter.ai/api/v1"]
|
||||
api_key_var = "OPENROUTER_API_KEY"
|
||||
|
||||
[client.extra_body]
|
||||
provider = { order = ["deepseek", "novita/fp8", "atlas-cloud/fp8", "siliconflow/fp8"] }
|
||||
@@ -1,8 +0,0 @@
|
||||
max_concurrent = 128
|
||||
|
||||
[client]
|
||||
base_url = ["https://openrouter.ai/api/v1"]
|
||||
api_key_var = "OPENROUTER_API_KEY"
|
||||
|
||||
[client.extra_body]
|
||||
provider = { order = ["z-ai"], allow_fallbacks = false}
|
||||
@@ -1,8 +0,0 @@
|
||||
max_concurrent = 16
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/INTELLECT-3"
|
||||
|
||||
[client]
|
||||
base_url = ["https://dev-inference.pinference.ai/api/v1"]
|
||||
api_key_var = "PRIME_API_KEY_DEV"
|
||||
@@ -1,5 +0,0 @@
|
||||
max_concurrent = 128
|
||||
|
||||
[client]
|
||||
base_url = ["https://api.together.ai/v1"]
|
||||
api_key_var = "TOGETHER_API_KEY"
|
||||
@@ -1,3 +0,0 @@
|
||||
[[env]]
|
||||
id = "aime2024"
|
||||
rollouts_per_example = 32 # 30 examples * 32 rollouts = 960 rollouts
|
||||
@@ -1,3 +0,0 @@
|
||||
[[env]]
|
||||
id = "aime2025"
|
||||
rollouts_per_example = 32 # 30 examples * 32 rollouts = 960 rollouts
|
||||
@@ -1,4 +0,0 @@
|
||||
[[env]]
|
||||
id = "gpqa"
|
||||
rollouts_per_example = 8
|
||||
args = { verifier = "regex" }
|
||||
@@ -1,3 +0,0 @@
|
||||
[[env]]
|
||||
id = "hle"
|
||||
rollouts_per_example = 1 # 2158 examples * 1 rollouts = 2158 rollouts
|
||||
@@ -1,4 +0,0 @@
|
||||
[[env]]
|
||||
id = "livecodebench"
|
||||
args = { pool_size = 128 }
|
||||
rollouts_per_example = 2 # 454 examples * 2 rollouts = 908 rollouts
|
||||
@@ -1,3 +0,0 @@
|
||||
[[env]]
|
||||
id = "mmlu-pro"
|
||||
rollouts_per_example = 1 # 12K examples * 1 rollouts = 12000 rollouts
|
||||
@@ -1 +0,0 @@
|
||||
The model names in this directory match the names on OpenRouter. If you try hitting the model on a different provider, you might have to change the model name.
|
||||
@@ -1,2 +0,0 @@
|
||||
[model]
|
||||
name = "deepseek/deepseek-r1-0528"
|
||||
@@ -1,2 +0,0 @@
|
||||
[model]
|
||||
name = "deepseek/deepseek-v3.2-exp"
|
||||
@@ -1,2 +0,0 @@
|
||||
[model]
|
||||
name = "z-ai/glm-4.5-air"
|
||||
@@ -1,2 +0,0 @@
|
||||
[model]
|
||||
name = "z-ai/glm-4.6"
|
||||
@@ -1,20 +0,0 @@
|
||||
max_concurrent = 64
|
||||
reasoning_field = "reasoning"
|
||||
|
||||
[model]
|
||||
name = "openai/gpt-oss-120b"
|
||||
|
||||
|
||||
[client]
|
||||
base_url = ["https://openrouter.ai/api/v1"]
|
||||
api_key_var = "OPENROUTER_API_KEY"
|
||||
|
||||
[sampling]
|
||||
reasoning_effort = "high"
|
||||
temperature = 1.0
|
||||
max_tokens = 122880
|
||||
|
||||
[sampling.extra_body.provider]
|
||||
only = ["google-vertex"]
|
||||
allow_fallbacks = false
|
||||
require_parameters = true
|
||||
@@ -1,2 +0,0 @@
|
||||
[model]
|
||||
name = "PrimeIntellect/INTELLECT-3"
|
||||
@@ -0,0 +1,51 @@
|
||||
trainer_gpu_ids = [0]
|
||||
inference_gpu_ids = [1]
|
||||
|
||||
max_steps = 500
|
||||
|
||||
[wandb]
|
||||
project = "math-group-debug"
|
||||
name = "math-group"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
oversampling_factor = 1.5
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/math-env"
|
||||
name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[orchestrator.val]
|
||||
interval = 5
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/aime2024"
|
||||
name = "aime2024"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 4096
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 2048
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ max_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "reverse-text"
|
||||
address = "tcp://127.0.0.1:5000" # requires: uv run env-server --env.id reverse-text --env.address tcp://127.0.0.1:5000
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "reverse-text"
|
||||
@@ -22,6 +23,17 @@ name = "reverse-text-2"
|
||||
interval = 1
|
||||
num_examples = 16
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 512
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
num_examples = 32
|
||||
rollouts_per_example = 4
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
|
||||
+1
-112
@@ -8,7 +8,7 @@ The main usecase of PRIME-RL is RL training. Three main abstractions facilitate
|
||||
|
||||
### Orchestrator
|
||||
|
||||
The orchestrator is a lightweight CPU process that handles the core data and scheduling logic, serving as an intermediary between the trainer and inference service with bidirectional relays. In one direction, it collects rollouts from the inference server, assembles them into packed batches, and dispatches them to the trainer; in the other direction, it relays updated model weights from the trainer to the inference service. The orchestrator utilizes `verifiers` environments to abstract multi-turn rollout generation and scoring, leveraging async OpenAI-compatible inference clients.
|
||||
The orchestrator is a lightweight CPU process that handles the core data and scheduling logic, serving as an intermediary between the trainer and inference service with bidirectional relays. In one direction, it collects rollouts from the inference server, assembles them into packed batches, and dispatches them to the trainer; in the other direction, it relays updated model weights from the trainer to the inference service. The orchestrator utilizes `verifiers` environments to abstract multi-turn rollout generation and scoring. Each training and evaluation environment is exposed as a `vf.EnvServer` as a sidecar to the orchestrator process (default) or as a standalone process (e.g. used in hosted training to run environments in containers).
|
||||
|
||||
### Trainer
|
||||
|
||||
@@ -65,114 +65,3 @@ uv run torchrun --nproc-per-node 8 src/prime_rl/trainer/sft/train.py ...
|
||||
```
|
||||
|
||||
For more details on multi-node deployment options, see the [deployment](deployment.md) documentation and see the [examples](examples) for concrete training configurations. To see all available configuration options, run `uv run sft --help`.
|
||||
|
||||
## Evals
|
||||
|
||||
You can eval any [verifiers](https://github.com/willccbb/verifiers) environment against API models, local models and checkpoints from an SFT or RL training using the `eval` entrypoint.
|
||||
|
||||
> We recommned using the `vf-eval` entrypoint for debugging and developing an environment and the PRIME-RL eval entrypoint for production-grade workloads, as it has more advanced features such as multi-environment evaluation, saving results to the Environments Hub, and scales better to custom multi-node inference deployments.
|
||||
|
||||
By default, the entrypoint uses the OpenAI API with `gpt-4.1-mini` to provide a smooth out-of-the-box experience without requiring a vLLM server.
|
||||
|
||||
To check all available configuration options, run `uv run eval --help`.
|
||||
|
||||
### API Models
|
||||
|
||||
By default, the entrypoint uses the OpenAI API. First, set the API key as an environment variable:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=...
|
||||
```
|
||||
|
||||
### Single Environment
|
||||
|
||||
```bash
|
||||
uv run eval @ configs/debug/eval/single_env.toml
|
||||
```
|
||||
|
||||
### Multiple Environments
|
||||
|
||||
```bash
|
||||
uv run eval @ configs/debug/eval/multi_env.toml
|
||||
```
|
||||
|
||||
### Local Models
|
||||
|
||||
To use a different API, or custom inference deployment, override the client and model configuration. For example, for a bare vLLM server, run:
|
||||
|
||||
```bash
|
||||
uv run eval \
|
||||
@ configs/debug/eval/local_model.toml \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
--model.name <model-name>
|
||||
```
|
||||
|
||||
### Checkpoints
|
||||
|
||||
To evaluate a training checkpoints, start an inference server with the model being the base model that you started training from and specify the directory containing the weight checkpoints with `--weights-dir`.
|
||||
|
||||
```bash
|
||||
uv run inference --model.name <model-name>
|
||||
```
|
||||
|
||||
```bash
|
||||
uv run eval \
|
||||
@ configs/debug/eval/single_env.toml \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
--model.name <model-name> \
|
||||
--weights-dir outputs/weights
|
||||
```
|
||||
|
||||
By default, this will evaluate the base model and all step checkpoints found in the weights directory. To skip evaling the base model, set `--no-eval-base` and to evaluate only specific steps, set `--steps` as a comma-separated list of integers representing the steps to evaluate. For example,
|
||||
|
||||
## Synthetic Data
|
||||
|
||||
You can generate synthetic data in any [verifiers](https://github.com/willccbb/verifiers) environment using the `synthesize` entrypoint. The entrypoint shares configuration with evals (`ModelConfig`, `ClientConfig`, `SamplingConfig`, and `EnvConfig`), making it easy to generate data using the same models and sampling settings as your evaluations.
|
||||
|
||||
The synthesize entrypoint supports single-turn, multi-turn, and tool-calling environments, and can generate data across multiple environments in parallel. It automatically parses reasoning content from model responses (configurable via `--reasoning-field`, defaults to `reasoning_content`), and saves data in append mode using the same schema as verifiers, making it straightforward to convert to SFT datasets. The entrypoint is robust to errors during generation, scoring, or saving—failed groups are simply dropped. Environments specified in the format `{env_org}/{env_id}` are automatically installed, similar to the RL entrypoint.
|
||||
|
||||
By default, the entrypoint uses the OpenAI API with `gpt-4.1-mini` (also the default for evals) to provide a smooth out-of-the-box experience without requiring a vLLM server. Make sure to set your API key as an environment variable
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=...
|
||||
```
|
||||
|
||||
To check all available configuration options, run `uv run synthesize --help`.
|
||||
|
||||
### Single-Turn Environments
|
||||
|
||||
Generate synthetic data in a single-turn environment (e.g., `gsm8k`):
|
||||
|
||||
```bash
|
||||
uv run synthesize @ configs/debug/synthesize/single_turn.toml
|
||||
```
|
||||
|
||||
By default, the entrypoint parses and saves the `reasoning_content` field from raw responses, as returned by vLLM when a reasoning parser is set. This behavior can be configured to handle different APIs:
|
||||
|
||||
```bash
|
||||
uv run synthesize @ configs/debug/synthesize/single_turn.toml --reasoning-field reasoning
|
||||
```
|
||||
|
||||
### Multiple Environments
|
||||
|
||||
Generate synthetic data across multiple environments (e.g., `gsm8k` and `hendrycks-math`):
|
||||
|
||||
```bash
|
||||
uv run synthesize @ configs/debug/synthesize/multi_env.toml
|
||||
```
|
||||
|
||||
### Multi-Turn Environments
|
||||
|
||||
Generate synthetic data in a multi-turn environment (e.g., `alphabet-sort`):
|
||||
|
||||
```bash
|
||||
uv run synthesize @ configs/debug/synthesize/multi_turn.toml
|
||||
```
|
||||
|
||||
### Multi-Turn Environments with Tool Calls
|
||||
|
||||
Generate synthetic data in a multi-turn environment with tool calls (e.g., `wiki-search`):
|
||||
|
||||
```bash
|
||||
uv run synthesize @ configs/debug/synthesize/multi_turn_tool_call.toml
|
||||
```
|
||||
|
||||
+8
-10
@@ -55,31 +55,29 @@ For RL training, logs are organized by component:
|
||||
| **Trainer** | `logs/trainer/rank_{N}.log` | Training process (one file per GPU rank) |
|
||||
| **Env Workers** | `logs/env_workers/{env_name}/worker_{N}.log` | Per-environment worker logs (optional) |
|
||||
|
||||
## Per-Environment Worker Logging
|
||||
## Per-Environment Logging
|
||||
|
||||
Environment workers run in **separate subprocesses** to isolate event loop lag. Worker logging is controlled at the orchestrator level via `orchestrator.log`:
|
||||
Environment are run via `vf.EnvServer` in separate processes. By default, each environment logs to a file in its run directory under `{output_dir}/run_default/train/{env_name}.log` and `{output_dir}/run_default/eval/{env_name}.log`. The log verbosity can be controlled with `orchestrator.log.vf_level`.
|
||||
|
||||
```toml
|
||||
[orchestrator.log]
|
||||
level = "debug" # Log level for prime-rl logger
|
||||
vf_level = "info" # Log level for verifiers library
|
||||
env_worker_logs = true # Enable file logging for env workers
|
||||
```
|
||||
|
||||
When `env_worker_logs = true`, logs are written to:
|
||||
```
|
||||
output_dir/
|
||||
└── logs/
|
||||
└── env_workers/
|
||||
└── run_default/
|
||||
└── train/
|
||||
├── {env_name_1}.log
|
||||
├── {env_name_2}.log
|
||||
└── ...
|
||||
└── eval/
|
||||
├── {env_name_1}.log
|
||||
├── {env_name_2}.log
|
||||
└── ...
|
||||
```
|
||||
|
||||
All workers for an environment share the same log file.
|
||||
|
||||
Set `env_worker_logs = false` to disable worker file logging (workers inherit parent process logging).
|
||||
|
||||
## Torchrun
|
||||
|
||||
For multi-node training with `torchrun`, all ranks log simultaneously. To filter to master rank only:
|
||||
|
||||
+2
-3
@@ -49,9 +49,8 @@ rl = "prime_rl.rl:main"
|
||||
trainer = "prime_rl.trainer.rl.train:main"
|
||||
orchestrator = "prime_rl.orchestrator.orchestrator:main"
|
||||
inference = "prime_rl.inference.server:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
sft = "prime_rl.trainer.sft.train:main"
|
||||
eval = "prime_rl.eval.eval:main"
|
||||
synthesize = "prime_rl.synthesize.synthesize:main"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
@@ -84,7 +83,7 @@ override-dependencies = ["nvidia-cudnn-cu12>=9.15"]
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cu128" }
|
||||
reverse-text = { index = "primeintellect" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "e85c598" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "3409cb5" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eebbd950a6ff11d9b5f806282e33df83df9d" }
|
||||
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "main" }
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.orchestrator.config import EvalConfig
|
||||
from prime_rl.utils.config import ClientConfig, LogConfig, ModelConfig, WandbConfig
|
||||
from prime_rl.utils.pydantic_config import BaseSettings
|
||||
|
||||
|
||||
class OfflineEvalConfig(EvalConfig, BaseSettings):
|
||||
"""Configures evaluation."""
|
||||
|
||||
# The client configuration
|
||||
client: ClientConfig = ClientConfig(timeout=36000, base_url=["https://api.openai.com/v1"])
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig(name="gpt-4.1-mini")
|
||||
|
||||
# The wandb configuration
|
||||
wandb: WandbConfig | None = None
|
||||
|
||||
# The logging configuration
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
reasoning_field: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="The field in the raw model response that contains the reasoning content. Defaults to 'reasoning_content', which is the default for vLLM when serving a model with a reasoning parser. Other APIs (e.g. DeepSeek, GLM, etc.) may use different field names.",
|
||||
),
|
||||
] = "reasoning_content"
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
Field(
|
||||
description="Directory to write outputs to. Will be populated with artifacts such as reports and HF datasets as subdirectories. Should be set to a persistent directory with enough disk space."
|
||||
),
|
||||
] = Path("outputs")
|
||||
|
||||
weights_dir: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="Directory to load weight checkpoints (searches for `{weights_dir}/step_{x}`) generated during a training run (RL/ SFT). If set, will automatically eval all checkpoints found, including the base model. If None, will only eval the base model.",
|
||||
),
|
||||
] = None
|
||||
|
||||
steps: Annotated[
|
||||
list[int] | None,
|
||||
Field(
|
||||
description="Steps to evaluate. If None, will evaluate all steps found in the weights directory. If set, will only evaluate the specified steps. If any of the specified steps are not found in the weights directory, will raise an error.",
|
||||
),
|
||||
] = None
|
||||
|
||||
eval_base: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to evaluate the base model. If True, will evaluate the base model before evaluating the checkpoints.",
|
||||
),
|
||||
] = True
|
||||
|
||||
use_tqdm: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use tqdm to display progress bars during model generation.",
|
||||
),
|
||||
] = False
|
||||
|
||||
max_concurrent: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Maximum number of concurrent rollouts to generate and score. Will create a global semaphore and pass to verifiers Environment. If None, will not limit concurrency.",
|
||||
),
|
||||
] = None
|
||||
|
||||
resume_path: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="Path to the directory containing results.jsonl to resume from. When set, will read existing example_ids from the results.jsonl file, filter the dataset to exclude already-evaluated examples, and append new results to the existing file. Can be an absolute path or relative to the current working directory.",
|
||||
),
|
||||
] = None
|
||||
|
||||
watcher: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"If True, watch `weights_dir` for newly-created stable checkpoints (folders named `step_{x}` that contain a `STABLE` file) "
|
||||
"and evaluate them as they appear, instead of immediately iterating over all existing checkpoints."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_eval_base(self):
|
||||
if self.weights_dir is None and not self.eval_base:
|
||||
raise ValueError(
|
||||
"You should either evaluate the base model and/or checkpoints. Set `--eval-base` or specify a weight checkpoint directory with `--weights-dir`."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_resume_stream(self):
|
||||
"""Enforce per_rollout when resume_path or save.stream is enabled, as both require per-rollout scheduling."""
|
||||
if self.resume_path is not None:
|
||||
if not self.save.stream:
|
||||
raise ValueError(
|
||||
"resume_path requires save.stream. Streaming saves are required for resume functionality."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_resume_multiple_environments(self):
|
||||
"""Prevent resume_path when multiple environments are configured, as they would share the same results.jsonl file."""
|
||||
if self.resume_path is not None and len(self.env) > 1:
|
||||
raise ValueError(
|
||||
f"resume_path cannot be used when evaluating multiple environments ({len(self.env)} environments configured). "
|
||||
f"All environments will read from and write to the same file ({self.resume_path / 'results.jsonl'}), "
|
||||
f"which may cause environments to incorrectly skip rollouts based on other environments' data. "
|
||||
f"Consider evaluating environments separately."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_resume_multiple_checkpoints(self):
|
||||
"""Prevent resume_path when multiple checkpoints will be evaluated, as they would share the same results.jsonl file."""
|
||||
if self.resume_path is not None and self.weights_dir is not None:
|
||||
# When weights_dir is set, multiple checkpoint evaluations will occur (at least 1 checkpoint,
|
||||
# and possibly the base model if eval_base=True). All would write to the same results.jsonl file.
|
||||
raise ValueError(
|
||||
f"resume_path cannot be used when evaluating multiple checkpoints (weights_dir is set). "
|
||||
f"When resume_path is set, all checkpoint evaluations (including base model if eval_base=True) "
|
||||
f"would write to the same results.jsonl file ({self.resume_path / 'results.jsonl'}), "
|
||||
f"causing later checkpoints to incorrectly skip examples that were already evaluated for earlier checkpoints. "
|
||||
f"Consider evaluating checkpoints separately, each with its own resume_path, or remove resume_path to use checkpoint-specific output directories."
|
||||
)
|
||||
return self
|
||||
@@ -1,46 +0,0 @@
|
||||
from typing import TYPE_CHECKING, Any, List
|
||||
|
||||
from prime_rl.utils.envs import (
|
||||
_ENV_PARSERS as _BASE_ENV_PARSERS,
|
||||
get_env_value,
|
||||
get_dir,
|
||||
set_defaults,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# Enable type checking for shared envs
|
||||
# ruff: noqa
|
||||
from prime_rl.utils.envs import *
|
||||
|
||||
# HF
|
||||
HF_HUB_CACHE: str
|
||||
HF_HUB_DISABLE_PROGRESS_BARS: str
|
||||
HF_HUB_ETAG_TIMEOUT: int
|
||||
|
||||
# vLLM
|
||||
VLLM_CONFIGURE_LOGGING: int
|
||||
|
||||
|
||||
_EVAL_ENV_PARSERS = {
|
||||
"HF_HUB_CACHE": str,
|
||||
"HF_HUB_DISABLE_PROGRESS_BARS": str,
|
||||
"HF_HUB_ETAG_TIMEOUT": int,
|
||||
"VLLM_CONFIGURE_LOGGING": int,
|
||||
**_BASE_ENV_PARSERS,
|
||||
}
|
||||
|
||||
_EVAL_ENV_DEFAULTS = {
|
||||
"HF_HUB_DISABLE_PROGRESS_BARS": "1", # Disable HF progress bars
|
||||
"HF_HUB_ETAG_TIMEOUT": "500", # Set request timeout to 500s to avoid model download issues
|
||||
"VLLM_CONFIGURE_LOGGING": "0", # Disable vLLM logging
|
||||
}
|
||||
|
||||
set_defaults(_EVAL_ENV_DEFAULTS)
|
||||
|
||||
|
||||
def __getattr__(name: str) -> Any:
|
||||
return get_env_value(_EVAL_ENV_PARSERS, name)
|
||||
|
||||
|
||||
def __dir__() -> List[str]:
|
||||
return get_dir(_EVAL_ENV_PARSERS)
|
||||
@@ -1,160 +0,0 @@
|
||||
import asyncio
|
||||
|
||||
from prime_rl.eval.config import OfflineEvalConfig
|
||||
from prime_rl.eval.utils import run_evals
|
||||
from prime_rl.utils.client import (
|
||||
check_health,
|
||||
maybe_check_has_model,
|
||||
reload_weights,
|
||||
setup_admin_clients,
|
||||
setup_clients,
|
||||
setup_evals_client,
|
||||
update_weights,
|
||||
)
|
||||
from prime_rl.utils.logger import intercept_verifiers_logging, setup_logger
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
from prime_rl.utils.utils import clean_exit, get_env_ids_to_install, get_step_path, install_env
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def eval(config: OfflineEvalConfig):
|
||||
# Initialize the logger
|
||||
logger = setup_logger(
|
||||
config.log.level,
|
||||
log_file=config.output_dir / "logs" / "eval.log" if config.log.file else None,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
intercept_verifiers_logging(level=config.log.vf_level)
|
||||
|
||||
env_names = [env.name or env.id for env in config.env]
|
||||
logger.info(f"Starting evals for {config.model.name} in environments {', '.join(env_names)}")
|
||||
logger.info(f"Using sampling config {config.sampling}")
|
||||
|
||||
# Install environments
|
||||
env_ids_to_install = get_env_ids_to_install(config.env)
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id)
|
||||
|
||||
# Initialize the monitor
|
||||
logger.info(f"Initializing monitor ({config.wandb})")
|
||||
setup_monitor(
|
||||
config=config.wandb,
|
||||
output_dir=None,
|
||||
run_config=config,
|
||||
)
|
||||
|
||||
# Setup clients
|
||||
logger.info(
|
||||
f"Initializing OpenAI client (base_url={', '.join(config.client.base_url)}, api_key_var={config.client.api_key_var}, headers={config.client.headers})"
|
||||
)
|
||||
clients = setup_clients(config.client)
|
||||
admin_clients = setup_admin_clients(config.client)
|
||||
evals_client = setup_evals_client()
|
||||
|
||||
# Check health of the client
|
||||
logger.info("Waiting for inference pool to be ready")
|
||||
await check_health(admin_clients)
|
||||
await maybe_check_has_model(clients, config.model.name, skip_model_check=config.client.skip_model_check)
|
||||
logger.success(f"Inference pool is healthy and serves {config.model.name}")
|
||||
|
||||
# Reset weights to base model to allow reusing inference server across runs
|
||||
logger.info("Resetting weights to base model")
|
||||
await reload_weights(admin_clients)
|
||||
|
||||
# Run benchmarks on base model
|
||||
if config.eval_base:
|
||||
logger.info(f"Evaluating model {config.model.name}")
|
||||
await run_evals(
|
||||
clients=clients,
|
||||
eval_config=config,
|
||||
model_name=config.model.name,
|
||||
sampling_config=config.sampling,
|
||||
evals_client=evals_client,
|
||||
reasoning_field=config.reasoning_field,
|
||||
output_dir=config.output_dir,
|
||||
ckpt_step=0,
|
||||
resume_path=config.resume_path,
|
||||
)
|
||||
|
||||
# If specified, evaluate all checkpoints found in the weights directory
|
||||
if config.weights_dir is not None:
|
||||
logger.info(f"Evaluating weight checkpoints in {config.weights_dir}")
|
||||
# Only include checkpoints that have a STABLE file (indicating save completed)
|
||||
ckpt_steps = sorted(
|
||||
[
|
||||
int(step_path.name.split("_")[-1])
|
||||
for step_path in config.weights_dir.glob("step_*")
|
||||
if (step_path / "STABLE").exists()
|
||||
]
|
||||
)
|
||||
logger.info(f"Found {len(ckpt_steps)} stable weight checkpoints (steps: {', '.join(map(str, ckpt_steps))})")
|
||||
|
||||
if config.steps is not None:
|
||||
missing_steps = [step for step in config.steps if step not in ckpt_steps]
|
||||
if missing_steps:
|
||||
raise ValueError(
|
||||
f"Step {missing_steps[0]} not found (or not stable) in weights directory {config.weights_dir}"
|
||||
)
|
||||
|
||||
# Filter the steps to evaluate
|
||||
if config.steps is not None:
|
||||
ckpt_steps = [step for step in ckpt_steps if step in config.steps]
|
||||
|
||||
async def _eval_ckpt(ckpt_step: int) -> bool:
|
||||
try:
|
||||
logger.info(f"Evaluating model {config.model.name} at checkpoint {ckpt_step}")
|
||||
await update_weights(admin_clients, get_step_path(config.weights_dir, ckpt_step))
|
||||
|
||||
await run_evals(
|
||||
clients=clients,
|
||||
eval_config=config,
|
||||
model_name=config.model.name,
|
||||
sampling_config=config.sampling,
|
||||
evals_client=evals_client,
|
||||
reasoning_field=config.reasoning_field,
|
||||
output_dir=config.output_dir,
|
||||
ckpt_step=ckpt_step,
|
||||
resume_path=config.resume_path,
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception(f"Checkpoint eval failed (ckpt_step={ckpt_step})")
|
||||
return False
|
||||
|
||||
logger.info(f"Evaluating {len(ckpt_steps)} weight checkpoints (steps: {', '.join(map(str, ckpt_steps))})")
|
||||
for ckpt_step in ckpt_steps:
|
||||
await _eval_ckpt(ckpt_step)
|
||||
|
||||
if config.watcher:
|
||||
# After evaluating all currently-stable checkpoints, watch for new ones and evaluate them as they appear.
|
||||
# Only checkpoints with step > max_evaluated_step will be picked up (strictly increasing order).
|
||||
max_evaluated_step = max(ckpt_steps) if ckpt_steps else -1
|
||||
while True:
|
||||
# Only include checkpoints that have a STABLE file (indicating save completed)
|
||||
all_ckpt_steps = sorted(
|
||||
[
|
||||
int(step_path.name.split("_")[-1])
|
||||
for step_path in config.weights_dir.glob("step_*")
|
||||
if (step_path / "STABLE").exists()
|
||||
]
|
||||
)
|
||||
new_ckpt_steps = [step for step in all_ckpt_steps if step > max_evaluated_step]
|
||||
if len(new_ckpt_steps) > 0:
|
||||
logger.info(f"New checkpoints to evaluate: {', '.join(map(str, new_ckpt_steps))}")
|
||||
for ckpt_step in new_ckpt_steps:
|
||||
await _eval_ckpt(ckpt_step)
|
||||
max_evaluated_step = max(max_evaluated_step, ckpt_step)
|
||||
else:
|
||||
logger.info("No new checkpoints to evaluate, waiting for 10 seconds")
|
||||
await asyncio.sleep(10)
|
||||
|
||||
logger.success("Eval finished!")
|
||||
|
||||
|
||||
def main():
|
||||
asyncio.run(eval(parse_argv(OfflineEvalConfig)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,29 +0,0 @@
|
||||
from typing import Literal
|
||||
|
||||
from datasets import Dataset, load_dataset
|
||||
|
||||
Benchmark = Literal["math500", "aime24", "aime25", "livecodebench-v5"]
|
||||
|
||||
_BENCHMARKS_DATASET_NAMES: dict[Benchmark, str] = {
|
||||
"math500": "PrimeIntellect/MATH-500",
|
||||
"aime24": "PrimeIntellect/AIME-24",
|
||||
"aime25": "PrimeIntellect/AIME-25",
|
||||
"livecodebench-v5": "PrimeIntellect/LiveCodeBench-v5",
|
||||
}
|
||||
|
||||
_BENCHMARK_DISPLAY_NAMES: dict[Benchmark, str] = {
|
||||
"math500": "MATH-500",
|
||||
"aime24": "AIME-24",
|
||||
"aime25": "AIME-25",
|
||||
"livecodebench-v5": "LiveCodeBench-V5",
|
||||
}
|
||||
|
||||
|
||||
def get_benchmark_dataset(name: Benchmark) -> Dataset:
|
||||
dataset = load_dataset(_BENCHMARKS_DATASET_NAMES[name], split="train")
|
||||
assert isinstance(dataset, Dataset)
|
||||
return dataset
|
||||
|
||||
|
||||
def get_benchmark_display_name(name: Benchmark) -> str:
|
||||
return _BENCHMARK_DISPLAY_NAMES[name]
|
||||
@@ -1,717 +0,0 @@
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from itertools import cycle
|
||||
from multiprocessing import Process
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
from huggingface_hub import whoami
|
||||
from openai import AsyncOpenAI
|
||||
from prime_evals import AsyncEvalsClient
|
||||
from verifiers import load_environment
|
||||
from verifiers.utils.path_utils import get_results_path
|
||||
from verifiers.utils.save_utils import (
|
||||
get_hf_hub_dataset_name,
|
||||
make_dataset,
|
||||
sanitize_metadata,
|
||||
save_metadata,
|
||||
save_outputs,
|
||||
)
|
||||
|
||||
from prime_rl.eval.config import OfflineEvalConfig
|
||||
from prime_rl.orchestrator.config import EvalConfig, EvalSamplingConfig, EvalSaveConfig, ModelConfig, RetryConfig
|
||||
from prime_rl.orchestrator.utils import set_semaphore
|
||||
from prime_rl.synthesize.utils import merge_reasoning_content, save_result
|
||||
from prime_rl.utils.client import setup_clients, setup_evals_client
|
||||
from prime_rl.utils.config import ClientConfig
|
||||
from prime_rl.utils.elastic import ServerDiscovery
|
||||
from prime_rl.utils.logger import ProgressTracker, get_logger, intercept_verifiers_logging, reset_logger, setup_logger
|
||||
from prime_rl.utils.monitor import get_monitor
|
||||
from prime_rl.utils.utils import capitalize, get_eval_dir, get_step_path, strip_env_version
|
||||
from prime_rl.utils.vf import (
|
||||
generate_group,
|
||||
generate_rollout,
|
||||
get_completion_len,
|
||||
get_is_truncated,
|
||||
to_serializable_state,
|
||||
)
|
||||
|
||||
WRITE_LOCK = asyncio.Lock()
|
||||
|
||||
|
||||
def read_existing_rollout_ids(results_file: Path) -> set[tuple[int, int]]:
|
||||
"""Read existing (example_id, rollout_idx) pairs from results file for resume."""
|
||||
rollout_ids: set[tuple[int, int]] = set()
|
||||
with open(results_file, "r") as f:
|
||||
for line in f:
|
||||
result = json.loads(line)
|
||||
rollout_ids.add((result["example_id"], result["rollout_idx"]))
|
||||
return rollout_ids
|
||||
|
||||
|
||||
def read_existing_results(results_file: Path) -> pd.DataFrame:
|
||||
results = []
|
||||
with open(results_file, "r") as f:
|
||||
for line in f:
|
||||
result = json.loads(line)
|
||||
info = result.get("info", {})
|
||||
prime_info = info.get("prime_rl", {})
|
||||
rollout_status = prime_info.get("rollout_status", "ok")
|
||||
results.append(
|
||||
{
|
||||
"example_id": result["example_id"],
|
||||
"reward": result["reward"],
|
||||
"completion_len": result["completion_len"],
|
||||
"is_truncated": result["is_truncated"],
|
||||
"rollout_status": rollout_status,
|
||||
}
|
||||
)
|
||||
|
||||
return pd.DataFrame(results)
|
||||
|
||||
|
||||
def read_completed_example_ids(results_file: Path, rollouts_per_example: int) -> set[int]:
|
||||
"""Read example_ids that have complete groups (all rollouts_per_example completed) for group-based resume."""
|
||||
example_id_counts: dict[int, int] = {}
|
||||
with open(results_file, "r") as f:
|
||||
for line in f:
|
||||
result = json.loads(line)
|
||||
example_id = result["example_id"]
|
||||
example_id_counts[example_id] = example_id_counts.get(example_id, 0) + 1
|
||||
|
||||
# Return example_ids that have exactly rollouts_per_example results
|
||||
completed_example_ids = {
|
||||
example_id for example_id, count in example_id_counts.items() if count == rollouts_per_example
|
||||
}
|
||||
return completed_example_ids
|
||||
|
||||
|
||||
def compute_pass_at_k(rewards: list[int]) -> dict[str, float]:
|
||||
total_attempts = len(rewards)
|
||||
k = total_attempts // 2
|
||||
|
||||
if k == 0:
|
||||
return {"pass@1": float(any(reward == 1.0 for reward in rewards))}
|
||||
|
||||
num_trials = 100
|
||||
pass_rates = []
|
||||
|
||||
for _ in range(num_trials):
|
||||
sampled_rewards = np.random.choice(rewards, size=k, replace=False)
|
||||
pass_rate = float(any(reward == 1.0 for reward in sampled_rewards))
|
||||
pass_rates.append(pass_rate)
|
||||
|
||||
return {f"pass@{k}": float(np.mean(pass_rates))}
|
||||
|
||||
|
||||
def prepare_sampling_args(sampling_config: EvalSamplingConfig) -> dict[str, Any]:
|
||||
"""Prepare sampling args for the client."""
|
||||
# Initialize sampling args
|
||||
sampling_args: dict[str, Any] = {}
|
||||
|
||||
# Apply sampling arguments, if specified
|
||||
if sampling_config.temperature is not None:
|
||||
sampling_args["temperature"] = sampling_config.temperature
|
||||
if sampling_config.max_tokens is not None:
|
||||
sampling_args["max_tokens"] = sampling_config.max_tokens
|
||||
if sampling_config.top_p is not None:
|
||||
sampling_args["top_p"] = sampling_config.top_p
|
||||
if sampling_config.reasoning_effort is not None:
|
||||
sampling_args["reasoning_effort"] = sampling_config.reasoning_effort
|
||||
|
||||
extra_body: dict[str, Any] = sampling_config.extra_body.copy()
|
||||
|
||||
# Apply vLLM-specific sampling arguments, if specified
|
||||
if sampling_config.top_k is not None:
|
||||
extra_body["top_k"] = sampling_config.top_k
|
||||
if sampling_config.min_p is not None:
|
||||
extra_body["min_p"] = sampling_config.min_p
|
||||
if sampling_config.min_tokens is not None:
|
||||
extra_body["min_tokens"] = sampling_config.min_tokens
|
||||
if sampling_config.repetition_penalty is not None:
|
||||
extra_body["repetition_penalty"] = sampling_config.repetition_penalty
|
||||
|
||||
sampling_args["extra_body"] = extra_body
|
||||
|
||||
return sampling_args
|
||||
|
||||
|
||||
# TODO: Move to verifiers to avoid code drift
|
||||
def make_result(output: vf.RolloutOutput, reasoning_field: str, rollout_idx: int) -> dict:
|
||||
"""Translates a finished rollout state to a synthetic dataset row."""
|
||||
completion = merge_reasoning_content(output["completion"], output["trajectory"], reasoning_field)
|
||||
result_dict = {
|
||||
"example_id": output["example_id"],
|
||||
"rollout_idx": rollout_idx,
|
||||
"prompt": output["prompt"],
|
||||
"completion": completion,
|
||||
"task": output["task"],
|
||||
"reward": output["reward"],
|
||||
"generation_ms": output["timing"]["generation_ms"],
|
||||
"scoring_ms": output["timing"]["scoring_ms"],
|
||||
"total_ms": output["timing"]["total_ms"],
|
||||
"info": output.get("info", {}),
|
||||
"answer": output.get("answer", ""),
|
||||
"completion_len": get_completion_len(output),
|
||||
"is_truncated": get_is_truncated(output),
|
||||
}
|
||||
for metric_name, metric_value in output["metrics"].items():
|
||||
result_dict[metric_name] = metric_value
|
||||
|
||||
result_dict["oai_tools"] = json.dumps(output.get("oai_tools", []))
|
||||
|
||||
return result_dict
|
||||
|
||||
|
||||
async def make_and_save_result(output: vf.RolloutOutput, save_file: Path, reasoning_field: str, rollout_idx: int):
|
||||
"""Translates and saves a finished rollout state to a synthetic dataset row."""
|
||||
result_dict = await asyncio.to_thread(make_result, output, reasoning_field, rollout_idx)
|
||||
await save_result(result_dict, save_file)
|
||||
|
||||
|
||||
def _is_valid_reward(reward: Any) -> bool:
|
||||
if reward is None:
|
||||
return False
|
||||
if isinstance(reward, float) and np.isnan(reward):
|
||||
return False
|
||||
return isinstance(reward, (int, float))
|
||||
|
||||
|
||||
def _format_avg_reward(rewards: list) -> str:
|
||||
valid = [r for r in rewards if _is_valid_reward(r)]
|
||||
if not valid:
|
||||
return "N/A"
|
||||
return f"{(sum(valid) / len(valid)):.4f}"
|
||||
|
||||
|
||||
async def generate_and_save_rollout(
|
||||
client: AsyncOpenAI,
|
||||
env: vf.Environment,
|
||||
model_name: str,
|
||||
example: dict,
|
||||
rollout_idx: int,
|
||||
env_name_or_id: str,
|
||||
sampling_args: dict,
|
||||
save_file: Path | None,
|
||||
reasoning_field: str,
|
||||
retry_config: RetryConfig,
|
||||
pbar: ProgressTracker,
|
||||
rewards_accumulator: list,
|
||||
rewards_lock: asyncio.Lock,
|
||||
) -> vf.RolloutOutput:
|
||||
"""Generate and optionally save a single rollout, updating progress bar per-rollout."""
|
||||
logger = get_logger()
|
||||
|
||||
# max_retries = max_attempts - 1 (verifiers counts retries, not attempts)
|
||||
max_retries = max(0, retry_config.max_attempts - 1)
|
||||
state = await generate_rollout(client, env, model_name, example, sampling_args, max_retries=max_retries)
|
||||
|
||||
# Check if the rollout failed with an error (after retries exhausted)
|
||||
if state.get("error") is not None:
|
||||
logger.error(
|
||||
f"Rollout generation failed after retries; recording no_response "
|
||||
f"(env={env_name_or_id}, example_id={example.get('example_id')}, rollout_idx={rollout_idx}): {state.get('error')}"
|
||||
)
|
||||
|
||||
# Save with rollout_idx if streaming saves enabled.
|
||||
if save_file is not None:
|
||||
result_dict = await asyncio.to_thread(make_result, state, reasoning_field, rollout_idx)
|
||||
await save_result(result_dict, save_file)
|
||||
|
||||
# Update running average immediately.
|
||||
async with rewards_lock:
|
||||
rewards_accumulator.append(state.get("reward"))
|
||||
pbar.set_postfix({"Avg Reward": _format_avg_reward(rewards_accumulator)})
|
||||
pbar.update(1)
|
||||
|
||||
return state
|
||||
|
||||
|
||||
async def generate_and_save_group(
|
||||
client: AsyncOpenAI,
|
||||
env: vf.Environment,
|
||||
model_name: str,
|
||||
example: dict,
|
||||
rollouts_per_example: int,
|
||||
env_name_or_id: str,
|
||||
sampling_args: dict,
|
||||
save_file: Path | None,
|
||||
reasoning_field: str,
|
||||
retry_config: RetryConfig,
|
||||
pbar: ProgressTracker,
|
||||
rewards_accumulator: list,
|
||||
rewards_lock: asyncio.Lock,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""Generate a group of rollouts, save results, and update progress (group-level)."""
|
||||
logger = get_logger()
|
||||
|
||||
# max_retries = max_attempts - 1 (verifiers counts retries, not attempts)
|
||||
max_retries = max(0, retry_config.max_attempts - 1)
|
||||
states = await generate_group(
|
||||
client, env, model_name, example, rollouts_per_example, sampling_args, max_retries=max_retries
|
||||
)
|
||||
|
||||
# Log errors for any states that failed (after retries exhausted)
|
||||
for state in states:
|
||||
if state.get("error") is not None:
|
||||
logger.error(
|
||||
f"Rollout in group failed after retries "
|
||||
f"(env={env_name_or_id}, example_id={example.get('example_id')}): {state.get('error')}"
|
||||
)
|
||||
|
||||
# Save results for the generated group.
|
||||
if save_file is not None:
|
||||
await asyncio.gather(
|
||||
*[
|
||||
make_and_save_result(state, save_file, reasoning_field, rollout_idx)
|
||||
for rollout_idx, state in enumerate(states)
|
||||
]
|
||||
)
|
||||
|
||||
# Update running average after group completes.
|
||||
async with rewards_lock:
|
||||
for state in states:
|
||||
rewards_accumulator.append(state.get("reward"))
|
||||
pbar.set_postfix({"Avg Reward": _format_avg_reward(rewards_accumulator)})
|
||||
pbar.update(rollouts_per_example)
|
||||
|
||||
return states
|
||||
|
||||
|
||||
async def run_eval(
|
||||
clients: list[AsyncOpenAI],
|
||||
env_id: str,
|
||||
env_name: str | None,
|
||||
env_args: dict,
|
||||
num_examples: int,
|
||||
rollouts_per_example: int,
|
||||
reasoning_field: str,
|
||||
output_dir: Path,
|
||||
ckpt_step: int,
|
||||
model_name: str,
|
||||
sampling_config: EvalSamplingConfig,
|
||||
save_config: EvalSaveConfig,
|
||||
retry_config: RetryConfig,
|
||||
evals_client: AsyncEvalsClient,
|
||||
per_rollout: bool = False,
|
||||
step: int | None = None,
|
||||
resume_path: Path | None = None,
|
||||
) -> None:
|
||||
# Get the logger
|
||||
logger = get_logger()
|
||||
monitor = get_monitor()
|
||||
eval_start_time = time.perf_counter()
|
||||
|
||||
# Load the eval environment
|
||||
env_name_or_id = env_name or env_id
|
||||
env = load_environment(strip_env_version(env_id), **env_args)
|
||||
dataset = env.get_eval_dataset(n=num_examples)
|
||||
sampling_args = prepare_sampling_args(sampling_config)
|
||||
|
||||
# Determine streaming save path
|
||||
if save_config.stream:
|
||||
if resume_path is not None:
|
||||
# resume_path points to a directory containing results.jsonl
|
||||
path_to_save = resume_path / "results.jsonl"
|
||||
else:
|
||||
base_path = get_results_path(env_name_or_id, model_name, base_path=output_dir)
|
||||
path_to_save = base_path / "results.jsonl"
|
||||
path_to_save.parent.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
path_to_save = None
|
||||
|
||||
# Create shared structure for tracking rewards
|
||||
rewards_accumulator: list = []
|
||||
rewards_lock = asyncio.Lock()
|
||||
examples = dataset.to_list()
|
||||
|
||||
if per_rollout:
|
||||
# Per-rollout scheduling: enables live progress updates and per-rollout resume
|
||||
all_rollouts: list[tuple[dict, int]] = [
|
||||
(example, rollout_idx) for example in examples for rollout_idx in range(rollouts_per_example)
|
||||
]
|
||||
|
||||
# Filter out already-completed rollouts on resume
|
||||
if resume_path is not None:
|
||||
assert path_to_save is not None
|
||||
existing_rollout_ids = read_existing_rollout_ids(path_to_save)
|
||||
original_count = len(all_rollouts)
|
||||
all_rollouts = [
|
||||
(ex, ridx) for ex, ridx in all_rollouts if (ex["example_id"], ridx) not in existing_rollout_ids
|
||||
]
|
||||
skipped_count = original_count - len(all_rollouts)
|
||||
logger.info(
|
||||
f"Resuming from {path_to_save}: skipping {skipped_count} already-completed rollouts, "
|
||||
f"{len(all_rollouts)} remaining"
|
||||
)
|
||||
# Populate rewards_accumulator with existing rewards
|
||||
existing_results_df = read_existing_results(path_to_save)
|
||||
rewards_accumulator.extend(existing_results_df.reward.tolist())
|
||||
|
||||
total_rollouts = len(all_rollouts)
|
||||
logger.info(
|
||||
f"Evaluating {model_name} on {env_name_or_id} ({num_examples=}, {rollouts_per_example=}) "
|
||||
f"{'with default args' if env_args == {} else f'with args {env_args}'} and extra_body {sampling_args['extra_body']}\n"
|
||||
f"{'Saving results to ' + str(path_to_save) if save_config.stream else 'Results will be saved at end of evaluation'}"
|
||||
)
|
||||
|
||||
pbar = ProgressTracker(total=total_rollouts, desc="Evaluating")
|
||||
if rewards_accumulator:
|
||||
pbar.set_postfix({"Avg Reward": _format_avg_reward(rewards_accumulator)})
|
||||
|
||||
all_states = await asyncio.gather(
|
||||
*[
|
||||
generate_and_save_rollout(
|
||||
client,
|
||||
env,
|
||||
model_name,
|
||||
example,
|
||||
rollout_idx,
|
||||
env_name_or_id,
|
||||
sampling_args,
|
||||
path_to_save,
|
||||
reasoning_field,
|
||||
retry_config,
|
||||
pbar,
|
||||
rewards_accumulator,
|
||||
rewards_lock,
|
||||
)
|
||||
for client, (example, rollout_idx) in zip(cycle(clients), all_rollouts)
|
||||
]
|
||||
)
|
||||
else:
|
||||
# Group-based scheduling: preserves group-based rubric scoring
|
||||
# Filter out completed example_ids on resume
|
||||
if resume_path is not None and path_to_save is not None and path_to_save.exists():
|
||||
completed_example_ids = read_completed_example_ids(path_to_save, rollouts_per_example)
|
||||
original_count = len(examples)
|
||||
examples = [ex for ex in examples if ex["example_id"] not in completed_example_ids]
|
||||
skipped_count = original_count - len(examples)
|
||||
logger.info(
|
||||
f"Resuming from {path_to_save}: skipping {skipped_count} already-completed example_ids "
|
||||
f"({len(completed_example_ids)} complete groups), {len(examples)} remaining"
|
||||
)
|
||||
# Populate rewards_accumulator with existing rewards for metrics
|
||||
existing_results_df = read_existing_results(path_to_save)
|
||||
rewards_accumulator.extend(existing_results_df.reward.tolist())
|
||||
|
||||
total_rollouts = len(examples) * rollouts_per_example
|
||||
logger.info(
|
||||
f"Evaluating {env_name_or_id} ({num_examples=}, {rollouts_per_example=}) "
|
||||
f"{'with default args' if env_args == {} else f'with args {env_args}'} and extra_body {sampling_args['extra_body']}\n"
|
||||
f"{'Saving results to ' + str(path_to_save) if save_config.stream else 'Results will be saved at end of evaluation'}"
|
||||
)
|
||||
|
||||
pbar = ProgressTracker(total=total_rollouts, desc="Evaluating")
|
||||
if rewards_accumulator:
|
||||
pbar.set_postfix({"Avg Reward": _format_avg_reward(rewards_accumulator)})
|
||||
|
||||
group_states_list = await asyncio.gather(
|
||||
*[
|
||||
generate_and_save_group(
|
||||
client,
|
||||
env,
|
||||
model_name,
|
||||
example,
|
||||
rollouts_per_example,
|
||||
env_name_or_id,
|
||||
sampling_args,
|
||||
path_to_save if save_config.stream else None,
|
||||
reasoning_field,
|
||||
retry_config,
|
||||
pbar,
|
||||
rewards_accumulator,
|
||||
rewards_lock,
|
||||
)
|
||||
for client, example in zip(cycle(clients), examples)
|
||||
]
|
||||
)
|
||||
all_states = [state for group in group_states_list for state in group]
|
||||
|
||||
k = rollouts_per_example
|
||||
new_results_df = pd.DataFrame(
|
||||
{
|
||||
"example_id": [state["example_id"] for state in all_states],
|
||||
"reward": [state["reward"] for state in all_states],
|
||||
"completion_len": [get_completion_len(state) for state in all_states],
|
||||
"is_truncated": [get_is_truncated(state) for state in all_states],
|
||||
"rollout_status": [
|
||||
(state.get("info", {}) or {}).get("prime_rl", {}).get("rollout_status", "ok") for state in all_states
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
# If resuming, combine with existing results for accurate metrics
|
||||
if resume_path is not None:
|
||||
assert path_to_save is not None
|
||||
existing_results_df = read_existing_results(path_to_save)
|
||||
results_df = pd.concat([existing_results_df, new_results_df], ignore_index=True)
|
||||
logger.info(
|
||||
f"Combined existing ({len(existing_results_df)}) and new ({len(new_results_df)}) results for metrics"
|
||||
)
|
||||
else:
|
||||
results_df = new_results_df
|
||||
|
||||
unique_rewards = results_df.reward.dropna().unique()
|
||||
could_be_binary = set(unique_rewards).issubset({0.0, 1.0})
|
||||
if could_be_binary:
|
||||
pass_at_k = (
|
||||
results_df.groupby("example_id")
|
||||
.apply(lambda x: compute_pass_at_k(x.reward.dropna()), include_groups=False)
|
||||
.apply(pd.Series)
|
||||
)
|
||||
else:
|
||||
pass_at_k = None
|
||||
logger.warning("Skipping computing pass@k rates because the task rewards appear to be non-binary")
|
||||
|
||||
# Log statistics to console
|
||||
eval_time = time.perf_counter() - eval_start_time
|
||||
no_response_rate = (
|
||||
float((results_df.rollout_status == "no_response").mean()) if "rollout_status" in results_df else 0.0
|
||||
)
|
||||
message = f"Evaluated {model_name} on {env_name_or_id} in {eval_time:.2f}s (Avg@{k}={results_df.reward.mean():.4f}"
|
||||
if could_be_binary:
|
||||
assert pass_at_k is not None
|
||||
for pass_rate, pass_rate_score in pd.Series(pass_at_k.mean()).items():
|
||||
message += f", {capitalize(str(pass_rate))}: {pass_rate_score:.4f}"
|
||||
message += (
|
||||
f", No-response: {no_response_rate * 100:.1f}%"
|
||||
f", Completion Length: {results_df.completion_len.mean():.2f} (±{results_df.completion_len.std():.2f}, ∈[{results_df.completion_len.min():.2f}, {results_df.completion_len.max():.2f}])"
|
||||
f", Truncated: {results_df.is_truncated.mean() * 100:.1f}%)"
|
||||
)
|
||||
logger.success(message)
|
||||
|
||||
# Log statistics to monitor
|
||||
eval_metrics = {
|
||||
f"avg@{k}": results_df.reward.mean(),
|
||||
"no_response/pct": no_response_rate * 100.0,
|
||||
"no_response/count": int((results_df.rollout_status == "no_response").sum())
|
||||
if "rollout_status" in results_df
|
||||
else 0,
|
||||
"completion_len/avg": results_df.completion_len.mean().item(),
|
||||
"completion_len/max": results_df.completion_len.max().item(),
|
||||
"completion_len/min": results_df.completion_len.min().item(),
|
||||
"is_truncated/mean": results_df.is_truncated.mean().item(),
|
||||
"time": eval_time,
|
||||
}
|
||||
if could_be_binary:
|
||||
assert pass_at_k is not None
|
||||
eval_metrics.update(pd.Series(pass_at_k.mean()).to_dict())
|
||||
eval_metrics = {**{f"eval/{env_name_or_id}/{k}": v for k, v in eval_metrics.items()}}
|
||||
eval_metrics.update({"progress/ckpt_step": ckpt_step, "step": step or ckpt_step})
|
||||
monitor.log(eval_metrics, step=None)
|
||||
|
||||
# Save results
|
||||
if save_config.disk is not None or save_config.hf is not None or save_config.env_hub:
|
||||
outputs = env._prepare_rollout_results(
|
||||
all_states=[to_serializable_state(state) for state in all_states], # type: ignore
|
||||
model=model_name,
|
||||
client=clients[0], # We use the first client
|
||||
state_columns=None,
|
||||
results_path=None,
|
||||
gen_sampling_args=sampling_args,
|
||||
start_time=eval_start_time,
|
||||
)
|
||||
dataset = make_dataset(outputs)
|
||||
metadata_dict = sanitize_metadata(outputs["metadata"])
|
||||
|
||||
if save_config.disk is not None:
|
||||
is_online = step is not None
|
||||
default_save_path = (
|
||||
get_step_path(get_eval_dir(output_dir), ckpt_step) / env_name_or_id
|
||||
if is_online
|
||||
else outputs["metadata"]["path_to_save"]
|
||||
)
|
||||
save_path = save_config.disk.path or default_save_path
|
||||
save_outputs(outputs["outputs"], save_path)
|
||||
save_metadata(metadata_dict, save_path)
|
||||
logger.info(f"Saved eval results for {env_name_or_id} to disk ({save_path})")
|
||||
|
||||
if save_config.hf is not None:
|
||||
dataset_name = save_config.hf.dataset_name or get_hf_hub_dataset_name(outputs)
|
||||
dataset_subset = save_config.hf.dataset_subset or env.env_id
|
||||
dataset_split = save_config.hf.dataset_split or "evals"
|
||||
dataset.push_to_hub(dataset_name, dataset_subset, split=dataset_split, private=save_config.hf.private)
|
||||
default_org = whoami().get("name", "")
|
||||
repo_name = dataset_name if "/" in dataset_name else f"{default_org}/{dataset_name}"
|
||||
logger.info(
|
||||
f"Pushed {'private' if save_config.hf.private else 'public'} eval results for {env_name_or_id} to HF Hub (https://huggingface.co/datasets/{repo_name})"
|
||||
)
|
||||
|
||||
if save_config.env_hub:
|
||||
eval_name = f"{env_id}--{model_name.replace('/', '--')}"
|
||||
|
||||
# Create evaluation for environment
|
||||
create_response = await evals_client.create_evaluation(
|
||||
name=eval_name,
|
||||
environments=[{"id": env_id}],
|
||||
model_name=model_name,
|
||||
framework="verifiers",
|
||||
metadata=metadata_dict,
|
||||
metrics=eval_metrics,
|
||||
)
|
||||
|
||||
eval_id = create_response.get("evaluation_id")
|
||||
assert eval_id is not None
|
||||
|
||||
# Push samples
|
||||
await evals_client.push_samples(eval_id, dataset.to_list())
|
||||
|
||||
# Finalize evaluation
|
||||
await evals_client.finalize_evaluation(eval_id, metrics=eval_metrics)
|
||||
|
||||
logger.info(
|
||||
f"Pushed eval results for {env_id} to Environments Hub (https://app.primeintellect.ai/dashboard/evaluations/{eval_id})"
|
||||
)
|
||||
|
||||
|
||||
async def run_evals(
|
||||
clients: list[AsyncOpenAI],
|
||||
eval_config: EvalConfig | OfflineEvalConfig,
|
||||
model_name: str,
|
||||
sampling_config: EvalSamplingConfig,
|
||||
evals_client: AsyncEvalsClient,
|
||||
reasoning_field: str,
|
||||
output_dir: Path,
|
||||
ckpt_step: int,
|
||||
step: int | None = None,
|
||||
resume_path: Path | None = None,
|
||||
):
|
||||
logger = get_logger()
|
||||
|
||||
async def run_eval_safe(env):
|
||||
"""Wrapper to catch RetryError and skip env."""
|
||||
await run_eval(
|
||||
clients=clients,
|
||||
env_id=env.id,
|
||||
env_name=env.name,
|
||||
env_args=env.args,
|
||||
num_examples=env.num_examples or eval_config.num_examples,
|
||||
reasoning_field=reasoning_field,
|
||||
rollouts_per_example=env.rollouts_per_example or eval_config.rollouts_per_example,
|
||||
output_dir=output_dir,
|
||||
model_name=model_name,
|
||||
sampling_config=sampling_config,
|
||||
save_config=eval_config.save,
|
||||
retry_config=eval_config.retry,
|
||||
evals_client=evals_client,
|
||||
per_rollout=eval_config.per_rollout,
|
||||
ckpt_step=ckpt_step,
|
||||
step=step,
|
||||
resume_path=resume_path,
|
||||
)
|
||||
return True
|
||||
|
||||
results = await asyncio.gather(*[run_eval_safe(env) for env in eval_config.env])
|
||||
|
||||
skipped = sum(1 for r in results if r is None)
|
||||
if skipped > 0:
|
||||
logger.warning(f"Skipped {skipped}/{len(eval_config.env)} environments due to retry exhaustion")
|
||||
|
||||
|
||||
async def _get_clients(client_config: ClientConfig, model_name: str) -> list[AsyncOpenAI]:
|
||||
"""Discover inference clients via elastic discovery or static config."""
|
||||
if not client_config.is_elastic:
|
||||
return setup_clients(client_config)
|
||||
|
||||
discovery = ServerDiscovery.from_config(client_config, model_name)
|
||||
return await discovery.wait_for_clients()
|
||||
|
||||
|
||||
def _run_evals_in_subprocess(
|
||||
client_config: ClientConfig,
|
||||
eval_config: EvalConfig,
|
||||
model_config: ModelConfig,
|
||||
sampling_config: EvalSamplingConfig,
|
||||
reasoning_field: str,
|
||||
output_dir: str,
|
||||
ckpt_step: int,
|
||||
step: int | None,
|
||||
max_concurrent: int,
|
||||
json_logging: bool = False,
|
||||
):
|
||||
"""Entry point for eval subprocess. Creates its own event loop and clients."""
|
||||
# Setup logger for subprocess (reset first since we inherit parent's global state when forked)
|
||||
reset_logger()
|
||||
logger = setup_logger("info", json_logging=json_logging)
|
||||
intercept_verifiers_logging(level="info")
|
||||
logger.info(f"Eval subprocess started for checkpoint step {ckpt_step}")
|
||||
|
||||
evals_client = setup_evals_client()
|
||||
|
||||
async def _run():
|
||||
await set_semaphore(max_concurrent)
|
||||
|
||||
model_name = model_config.name
|
||||
if model_config.lora and ckpt_step > 0:
|
||||
model_name = model_config.lora.name
|
||||
clients = await _get_clients(client_config, model_name)
|
||||
logger.info(f"Using {len(clients)} inference client(s) for model {model_name}")
|
||||
|
||||
await run_evals(
|
||||
clients=clients,
|
||||
eval_config=eval_config,
|
||||
model_name=model_name,
|
||||
sampling_config=sampling_config,
|
||||
evals_client=evals_client,
|
||||
reasoning_field=reasoning_field,
|
||||
output_dir=Path(output_dir),
|
||||
ckpt_step=ckpt_step,
|
||||
step=step,
|
||||
)
|
||||
|
||||
asyncio.run(_run())
|
||||
get_monitor().close()
|
||||
logger.info(f"Eval subprocess finished for checkpoint step {ckpt_step}")
|
||||
|
||||
|
||||
async def run_evals_subprocess(
|
||||
client_config: ClientConfig,
|
||||
eval_config: EvalConfig | OfflineEvalConfig,
|
||||
model_config: ModelConfig,
|
||||
sampling_config: EvalSamplingConfig,
|
||||
reasoning_field: str,
|
||||
output_dir: Path,
|
||||
ckpt_step: int,
|
||||
step: int | None = None,
|
||||
max_concurrent: int = -1,
|
||||
json_logging: bool = False,
|
||||
):
|
||||
"""Run evals in a separate subprocess to isolate the event loop.
|
||||
|
||||
This prevents eval's async work from causing event loop lag in the
|
||||
orchestrator's main loop. The orchestrator blocks until eval completes.
|
||||
"""
|
||||
logger = get_logger()
|
||||
logger.info(f"Spawning eval subprocess for checkpoint step {ckpt_step}")
|
||||
|
||||
process = Process(
|
||||
target=_run_evals_in_subprocess,
|
||||
args=(
|
||||
client_config,
|
||||
eval_config,
|
||||
model_config,
|
||||
sampling_config,
|
||||
reasoning_field,
|
||||
str(output_dir),
|
||||
ckpt_step,
|
||||
step,
|
||||
max_concurrent,
|
||||
json_logging,
|
||||
),
|
||||
daemon=True,
|
||||
)
|
||||
process.start()
|
||||
|
||||
# Wait for process to complete without blocking the event loop
|
||||
while process.is_alive():
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
if process.exitcode != 0:
|
||||
logger.error(f"Eval subprocess failed with exit code {process.exitcode}")
|
||||
else:
|
||||
logger.success(f"Eval subprocess completed for checkpoint step {ckpt_step}")
|
||||
@@ -8,11 +8,11 @@ from typing import cast
|
||||
|
||||
import verifiers as vf
|
||||
from datasets import Dataset
|
||||
from verifiers.utils.save_utils import make_serializable
|
||||
|
||||
from prime_rl.orchestrator.config import BufferConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import format_num, mean, mean_normalize
|
||||
from prime_rl.utils.vf import from_serializable_state, to_serializable_state
|
||||
|
||||
|
||||
class Buffer:
|
||||
@@ -73,7 +73,7 @@ class Buffer:
|
||||
self.hard_examples: list[dict] = []
|
||||
|
||||
# Initialize rollout buffer (flat list of rollouts)
|
||||
self.rollout_buffer: list[vf.State] = []
|
||||
self.rollout_buffer: list[vf.RolloutOutput] = []
|
||||
|
||||
self.reset_step_metrics()
|
||||
|
||||
@@ -87,16 +87,14 @@ class Buffer:
|
||||
"""Saves pool assignments and rollout buffer."""
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def write_jsonl(lst: list[dict], path: Path) -> None:
|
||||
def write_jsonl(lst: list, path: Path) -> None:
|
||||
with open(path, "w") as f:
|
||||
for item in lst:
|
||||
f.write(json.dumps(item) + "\n")
|
||||
f.write(json.dumps(item, default=make_serializable) + "\n")
|
||||
|
||||
write_jsonl(self.easy_examples, path / "easy_examples.jsonl")
|
||||
write_jsonl(self.hard_examples, path / "hard_examples.jsonl")
|
||||
|
||||
serializable_rollouts = [to_serializable_state(rollout) for rollout in self.rollout_buffer]
|
||||
write_jsonl(serializable_rollouts, path / "rollout_buffer.jsonl")
|
||||
write_jsonl(self.rollout_buffer, path / "rollout_buffer.jsonl")
|
||||
|
||||
def load(self, path: Path) -> None:
|
||||
"""Loads pool assignments and rollouts."""
|
||||
@@ -107,9 +105,7 @@ class Buffer:
|
||||
|
||||
saved_easy_examples = read_jsonl(path / "easy_examples.jsonl")
|
||||
saved_hard_examples = read_jsonl(path / "hard_examples.jsonl")
|
||||
saved_rollout_buffer = [
|
||||
from_serializable_state(rollout) for rollout in read_jsonl(path / "rollout_buffer.jsonl")
|
||||
]
|
||||
saved_rollout_buffer = cast(list[vf.RolloutOutput], read_jsonl(path / "rollout_buffer.jsonl"))
|
||||
|
||||
if any(saved_easy_examples) or any(saved_hard_examples) or any(saved_rollout_buffer):
|
||||
# Build hash lookup for example buffer (env -> (example_hash -> example_id))
|
||||
@@ -211,7 +207,7 @@ class Buffer:
|
||||
|
||||
return sampled_examples
|
||||
|
||||
def update(self, rollouts: list[vf.State]):
|
||||
def update(self, rollouts: list[vf.RolloutOutput]):
|
||||
"""Updates the buffer state with completed rollouts."""
|
||||
|
||||
rollouts_by_example = defaultdict(list)
|
||||
@@ -246,7 +242,7 @@ class Buffer:
|
||||
self.num_rollouts_per_step[env_name]["normal"] += len(example_rollouts)
|
||||
self.rollout_buffer.extend(example_rollouts)
|
||||
|
||||
def sample_rollouts(self, n: int) -> list[vf.State]:
|
||||
def sample_rollouts(self, n: int) -> list[vf.RolloutOutput]:
|
||||
"""Samples the latest n rollouts from the buffer."""
|
||||
n = min(n, len(self.rollout_buffer))
|
||||
sampled_rollouts = self.rollout_buffer[-n:]
|
||||
|
||||
@@ -67,7 +67,7 @@ class ModelConfig(BaseModelConfig):
|
||||
] = None
|
||||
|
||||
|
||||
class TemperatureScheduleConfig(BaseConfig):
|
||||
class TemperatureSchedulerConfig(BaseConfig):
|
||||
"""Configures temperature scheduling over training steps. Use this OR sampling.temperature, not both."""
|
||||
|
||||
type: Annotated[
|
||||
@@ -114,7 +114,7 @@ class SamplingConfig(BaseConfig):
|
||||
] = None
|
||||
|
||||
temp_scheduler: Annotated[
|
||||
TemperatureScheduleConfig | None,
|
||||
TemperatureSchedulerConfig | None,
|
||||
Field(
|
||||
description="Temperature schedule over training steps. Set this OR temperature, not both.",
|
||||
),
|
||||
@@ -238,17 +238,6 @@ class EvalSamplingConfig(BaseConfig):
|
||||
] = {}
|
||||
|
||||
|
||||
class EvalSaveDiskConfig(BaseConfig):
|
||||
"""Configures how to save the eval results to disk."""
|
||||
|
||||
path: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="The path to save the eval results to. If None, will default to <output_dir>/evals/<step_path>/<env_id> for online evals and the verifiers default for offline evals."
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class EvalSaveHFConfig(BaseConfig):
|
||||
"""Configures how to save the eval results to HF."""
|
||||
|
||||
@@ -279,72 +268,26 @@ class EvalSaveHFConfig(BaseConfig):
|
||||
] = False
|
||||
|
||||
|
||||
class EvalSaveConfig(BaseConfig):
|
||||
disk: EvalSaveDiskConfig | None = None
|
||||
hf: EvalSaveHFConfig | None = None
|
||||
env_hub: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to push eval results to Prime Environment Hub. Automatically pushes all evaluated environments. Requires PRIME_API_KEY and authorization for the environments."
|
||||
),
|
||||
] = False
|
||||
stream: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to save results incrementally as rollouts complete.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class RetryConfig(BaseConfig):
|
||||
"""Configures retry behavior for rollout generation."""
|
||||
|
||||
max_attempts: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Maximum number of retry attempts.",
|
||||
),
|
||||
] = 10
|
||||
|
||||
wait_multiplier: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
description="Multiplier for exponential backoff wait time.",
|
||||
),
|
||||
] = 1.0
|
||||
|
||||
wait_min: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
description="Minimum wait time in seconds between retries.",
|
||||
),
|
||||
] = 1.0
|
||||
|
||||
wait_max: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
description="Maximum wait time in seconds between retries.",
|
||||
),
|
||||
] = 60.0
|
||||
|
||||
reraise: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to reraise the original exception after all retries are exhausted. If False, raises tenacity.RetryError instead.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class EnvConfig(BaseConfig):
|
||||
"""Configures an environment for training."""
|
||||
|
||||
id: Annotated[str, Field(description="ID of the environment to use.")] = "reverse-text"
|
||||
args: Annotated[dict, Field(description="Arguments to pass to the environment.")] = {}
|
||||
name: Annotated[str | None, Field(description="Name of the environment to use.")] = None
|
||||
address: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Address of the environment server. If None, will spawn an environment server in a subprocess automatically.If given, will try to connect an environment client to the environment server at this address."
|
||||
),
|
||||
] = None
|
||||
extra_env_kwargs: Annotated[
|
||||
dict[str, Any],
|
||||
Field(
|
||||
description=(
|
||||
"Extra kwargs passed to an env (e.g. seq_len, interleaved_rollouts, score_rollouts). This field is auto-populated with the seq_len, interleaved_rollouts, and score_rollouts for training envs on the orchestrator. It is generally NOT recommended for this field to be overriden by the user. It's main use case is to match the extra_env_kwargs when running an env in an isolated environment server."
|
||||
),
|
||||
),
|
||||
] = {}
|
||||
|
||||
|
||||
class EvalEnvConfig(EnvConfig):
|
||||
@@ -391,34 +334,10 @@ class EvalConfig(BaseConfig):
|
||||
default_factory=EvalSamplingConfig,
|
||||
description="Shared sampling configuration for evals; can differ from training sampling.",
|
||||
)
|
||||
save: EvalSaveConfig = Field(
|
||||
default_factory=EvalSaveConfig,
|
||||
description="Configures how to save the eval results.",
|
||||
)
|
||||
retry: RetryConfig = Field(
|
||||
default_factory=RetryConfig,
|
||||
description="Configures retry behavior for rollout generation.",
|
||||
)
|
||||
num_examples: Annotated[int, Field(description="Number of examples to evaluate per environment.")] = -1
|
||||
rollouts_per_example: Annotated[
|
||||
int, Field(ge=1, description="Number of samples to generate per example for each environment.")
|
||||
] = 1
|
||||
reasoning_field: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="The field in the raw model response that contains the reasoning content. Defaults to 'reasoning_content', which is the default for vLLM when serving a model with a reasoning parser. Other APIs (e.g. DeepSeek, GLM, etc.) may use different field names.",
|
||||
),
|
||||
] = "reasoning_content"
|
||||
per_rollout: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Schedule rollouts individually instead of as groups. Enables live progress updates and per-rollout resume, but incompatible with group-based rubrics.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class OnlineEvalConfig(EvalConfig):
|
||||
"""Configures online evaluation."""
|
||||
|
||||
interval: Annotated[
|
||||
int,
|
||||
@@ -704,7 +623,7 @@ class OrchestratorConfig(BaseSettings):
|
||||
env: list[EnvConfig] = [EnvConfig()]
|
||||
|
||||
# The evaluation configuration
|
||||
eval: OnlineEvalConfig | None = None
|
||||
eval: EvalConfig | None = None
|
||||
|
||||
# Data buffer configuration
|
||||
buffer: BufferConfig = BufferConfig()
|
||||
@@ -761,22 +680,6 @@ class OrchestratorConfig(BaseSettings):
|
||||
),
|
||||
] = None
|
||||
|
||||
workers_per_env: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Number of worker subprocesses to spawn per environment. Multiple workers enable isolation of event loop lag - if one worker slows down, others continue at full speed. Uses least-pending routing to distribute load.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
max_env_worker_restarts: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=-1,
|
||||
description="Maximum number of automatic restarts for an environment worker that dies unexpectedly. After this limit, the orchestrator will crash. Set to -1 for unlimited restarts.",
|
||||
),
|
||||
] = 5
|
||||
|
||||
batch_size: Annotated[int, Field(ge=1, description="Number of samples to train on per step.")] = 128
|
||||
|
||||
oversampling_factor: Annotated[
|
||||
@@ -802,13 +705,6 @@ class OrchestratorConfig(BaseSettings):
|
||||
),
|
||||
] = 2048
|
||||
|
||||
mask_env_responses: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to mask environment responses from the loss.",
|
||||
),
|
||||
] = True
|
||||
|
||||
# TODO(Mika): This should be automatic from the number of ZMQ connections
|
||||
num_train_workers: Annotated[
|
||||
int,
|
||||
@@ -860,11 +756,8 @@ class OrchestratorConfig(BaseSettings):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_max_concurrent(self):
|
||||
min_concurrent = self.rollouts_per_example * (self.workers_per_env or 1)
|
||||
if self.max_concurrent is not None and self.max_concurrent < min_concurrent:
|
||||
raise ValueError(
|
||||
f"max_concurrent must be at least rollouts_per_example * workers_per_env ({min_concurrent})"
|
||||
)
|
||||
if self.max_concurrent is not None and self.max_concurrent < self.rollouts_per_example:
|
||||
raise ValueError("max_concurrent must be at least the number of rollouts per example")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -901,6 +794,19 @@ class OrchestratorConfig(BaseSettings):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_extra_env_kwargs(self):
|
||||
train_extra_env_kwargs = dict(
|
||||
seq_len=self.seq_len,
|
||||
interleaved_rollouts=True,
|
||||
score_rollouts=not self.buffer.skip_verification,
|
||||
)
|
||||
for env in self.env:
|
||||
# extra_env_kwargs is not meant to be used by the user, we shamelessly override here
|
||||
env.extra_env_kwargs.update(train_extra_env_kwargs)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_temperature_config(self):
|
||||
has_temp = self.sampling.temperature is not None
|
||||
@@ -914,8 +820,8 @@ class OrchestratorConfig(BaseSettings):
|
||||
self.sampling.temperature = 1.0
|
||||
|
||||
if has_scheduler:
|
||||
schedule = self.sampling.temp_scheduler
|
||||
if schedule.total_steps is None and self.max_steps is None:
|
||||
scheduler = self.sampling.temp_scheduler
|
||||
if scheduler.total_steps is None and self.max_steps is None:
|
||||
raise ValueError("temp_scheduler.total_steps must be set when max_steps is None")
|
||||
|
||||
return self
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from prime_rl.orchestrator.config import EnvConfig
|
||||
from prime_rl.utils.config import LogConfig
|
||||
from prime_rl.utils.pydantic_config import BaseSettings
|
||||
|
||||
|
||||
class EnvServerConfig(BaseSettings):
|
||||
"""Configures an environment server."""
|
||||
|
||||
env: EnvConfig = EnvConfig()
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
Field(
|
||||
description="Directory to write outputs to. Will be populated with checkpoints, weights, rollouts and logs as subdirectories. Should be set to a persistent directory with enough disk space. This value should be distinct across experiments running on a single node. See the README for more details."
|
||||
),
|
||||
] = Path("outputs/run_default")
|
||||
@@ -0,0 +1,41 @@
|
||||
from loguru import logger
|
||||
from verifiers.workers import ZMQEnvServer
|
||||
|
||||
from prime_rl.orchestrator.env_server.config import EnvServerConfig
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import get_log_dir
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
from prime_rl.utils.utils import clean_exit, get_env_ids_to_install, install_env, strip_env_version
|
||||
|
||||
|
||||
@clean_exit
|
||||
@logger.catch(reraise=True)
|
||||
def run_server(config: EnvServerConfig):
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
# install environment if not already installed
|
||||
env_ids_to_install = set()
|
||||
env_ids_to_install.update(get_env_ids_to_install([config.env]))
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id)
|
||||
|
||||
env_name = config.env.name or config.env.id
|
||||
log_file = (get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix()
|
||||
ZMQEnvServer.run_server(
|
||||
env_id=strip_env_version(config.env.id),
|
||||
env_args=config.env.args,
|
||||
extra_env_kwargs=config.env.extra_env_kwargs,
|
||||
log_level=config.log.level,
|
||||
log_file_level=config.log.vf_level,
|
||||
log_file=log_file,
|
||||
**{"address": config.env.address} if config.env.address is not None else {},
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry-point for env-server. Run using `uv run env-server`"""
|
||||
run_server(parse_argv(EnvServerConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,487 +0,0 @@
|
||||
"""
|
||||
Environment worker subprocess.
|
||||
|
||||
Runs environment rollouts in a separate process to isolate event loop lag.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import queue
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from itertools import cycle
|
||||
from multiprocessing import Process, Queue
|
||||
from pathlib import Path
|
||||
|
||||
import verifiers as vf
|
||||
from aiolimiter import AsyncLimiter
|
||||
from openai import AsyncOpenAI
|
||||
from verifiers.utils.async_utils import maybe_semaphore
|
||||
|
||||
from prime_rl.utils.client import setup_clients
|
||||
from prime_rl.utils.config import ClientConfig
|
||||
from prime_rl.utils.elastic import ServerDiscovery
|
||||
from prime_rl.utils.logger import get_logger, intercept_verifiers_logging, reset_logger, setup_logger
|
||||
from prime_rl.utils.utils import strip_env_version
|
||||
|
||||
|
||||
class WorkerDiedError(Exception):
|
||||
"""Raised when a worker subprocess dies unexpectedly."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class RolloutRequest:
|
||||
"""Request to generate rollouts for an example."""
|
||||
|
||||
request_id: str
|
||||
example_id: int
|
||||
rollouts_per_example: int
|
||||
model_name: str # Model name to use for this request (may change for LoRA)
|
||||
sampling_args: dict
|
||||
|
||||
|
||||
@dataclass
|
||||
class RolloutResponse:
|
||||
"""Response containing rollout results."""
|
||||
|
||||
request_id: str
|
||||
results: list[dict] # Simplified state dicts
|
||||
lag_metrics: dict | None = None # Event loop lag metrics from worker
|
||||
|
||||
|
||||
def extract_result(output: vf.RolloutOutput, temperature: float) -> dict:
|
||||
"""
|
||||
Extract only the fields from vf.RolloutOutput needed to build training
|
||||
samples and logging.
|
||||
|
||||
The extracted dict must contain all fields needed by:
|
||||
- Buffer.update(): example_id, task, reward
|
||||
- orchestrator metrics: reward, is_truncated, error, timing, metrics, trajectory
|
||||
- interleave_rollout: trajectory[*]["tokens"] with all token fields
|
||||
|
||||
For multimodal (Qwen3-VL), tokens dict may also contain:
|
||||
- pixel_values: flattened image patches [num_patches, patch_dim]
|
||||
- image_grid_thw: grid dimensions [num_images, 3]
|
||||
|
||||
Args:
|
||||
state: The vf.State from the environment rollout
|
||||
temperature: The temperature used during generation (from sampling args)
|
||||
"""
|
||||
# Get trajectory with tokens (needed for training)
|
||||
trajectory = []
|
||||
for step in output.get("trajectory", []):
|
||||
traj_step = {
|
||||
"prompt": step.get("prompt"),
|
||||
"completion": step.get("completion"),
|
||||
# tokens dict contains: prompt_ids, prompt_mask, completion_ids,
|
||||
# completion_mask, completion_logprobs, is_truncated
|
||||
# For multimodal: also pixel_values, image_grid_thw
|
||||
"tokens": step.get("tokens"),
|
||||
"temperature": temperature, # Store temperature per-turn for per-token temp support
|
||||
}
|
||||
trajectory.append(traj_step)
|
||||
|
||||
return {
|
||||
# Required by buffer
|
||||
"example_id": output.get("example_id"),
|
||||
"task": output.get("task"),
|
||||
"reward": output.get("reward"),
|
||||
# Required by orchestrator metrics
|
||||
"is_truncated": output.get("is_truncated", False),
|
||||
"error": output.get("error"),
|
||||
"timing": output.get("timing", {}),
|
||||
"metrics": output.get("metrics", {}),
|
||||
# Required for training examples
|
||||
"prompt": output.get("prompt"),
|
||||
"completion": output.get("completion"),
|
||||
"trajectory": trajectory,
|
||||
}
|
||||
|
||||
|
||||
async def worker_loop(
|
||||
request_queue: Queue,
|
||||
response_queue: Queue,
|
||||
env: vf.Environment,
|
||||
clients: list[AsyncOpenAI],
|
||||
client_config: ClientConfig,
|
||||
max_concurrent_groups: int,
|
||||
tasks_per_minute: int,
|
||||
example_lookup: dict[int, dict],
|
||||
model_name: str,
|
||||
):
|
||||
"""Main async loop for processing rollout requests."""
|
||||
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
|
||||
|
||||
semaphore = await maybe_semaphore(max_concurrent_groups)
|
||||
rate_limiter = AsyncLimiter(tasks_per_minute, 60) if tasks_per_minute > 0 else None
|
||||
|
||||
# Start event loop lag monitor for this worker
|
||||
lag_monitor = EventLoopLagMonitor(interval=0.1) # More frequent sampling for workers
|
||||
lag_monitor_task = asyncio.create_task(lag_monitor.run())
|
||||
|
||||
# Setup client discovery (elastic mode) or static client cycle
|
||||
discovery: ServerDiscovery | None = None
|
||||
if client_config.is_elastic:
|
||||
discovery = ServerDiscovery.from_config(client_config, model_name)
|
||||
static_cycle = cycle(clients) if clients else None
|
||||
|
||||
# Track in-flight tasks
|
||||
pending_tasks: dict[asyncio.Task, str] = {}
|
||||
waiting_requests: list[RolloutRequest] = []
|
||||
|
||||
def get_next_client():
|
||||
"""Get next client from discovery or static cycle."""
|
||||
if discovery:
|
||||
return discovery.get_next_client()
|
||||
return next(static_cycle) if static_cycle else None
|
||||
|
||||
def has_clients() -> bool:
|
||||
"""Check if clients are available."""
|
||||
if discovery:
|
||||
return discovery.has_clients
|
||||
return bool(clients)
|
||||
|
||||
async def process_request(request: RolloutRequest, client: AsyncOpenAI) -> RolloutResponse:
|
||||
if rate_limiter:
|
||||
await rate_limiter.acquire()
|
||||
example = example_lookup[request.example_id]
|
||||
group_inputs = [vf.RolloutInput(**example) for _ in range(request.rollouts_per_example)]
|
||||
async with semaphore:
|
||||
outputs = await env.run_group(
|
||||
group_inputs=group_inputs,
|
||||
client=client,
|
||||
model=request.model_name,
|
||||
sampling_args=request.sampling_args, # Use per-request sampling args for temp scheduling
|
||||
state_columns=["trajectory"],
|
||||
)
|
||||
temperature = request.sampling_args["temperature"]
|
||||
return RolloutResponse(request_id=request.request_id, results=[extract_result(o, temperature) for o in outputs])
|
||||
|
||||
try:
|
||||
while True:
|
||||
if discovery:
|
||||
await discovery.refresh()
|
||||
|
||||
# Process waiting requests if we now have clients
|
||||
if has_clients() and waiting_requests:
|
||||
for req in waiting_requests:
|
||||
task = asyncio.create_task(process_request(req, get_next_client()))
|
||||
pending_tasks[task] = req.request_id
|
||||
waiting_requests.clear()
|
||||
|
||||
# Drain request queue
|
||||
while True:
|
||||
try:
|
||||
request = request_queue.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
if request is None: # Shutdown signal
|
||||
return
|
||||
|
||||
# Update discovery model name if it changed (e.g., switched to LoRA)
|
||||
if discovery and request.model_name != discovery.model_name:
|
||||
discovery.model_name = request.model_name
|
||||
discovery._urls = [] # Force refresh on next call
|
||||
|
||||
if has_clients():
|
||||
task = asyncio.create_task(process_request(request, get_next_client()))
|
||||
pending_tasks[task] = request.request_id
|
||||
else:
|
||||
waiting_requests.append(request)
|
||||
|
||||
if not pending_tasks:
|
||||
# No pending tasks, wait a bit for new requests
|
||||
await asyncio.sleep(0.01)
|
||||
continue
|
||||
|
||||
# Wait for at least one task to complete
|
||||
done, _ = await asyncio.wait(pending_tasks.keys(), timeout=0.1, return_when=asyncio.FIRST_COMPLETED)
|
||||
for task in done:
|
||||
pending_tasks.pop(task)
|
||||
response = task.result()
|
||||
# Attach lag metrics to response
|
||||
response.lag_metrics = lag_monitor.get_metrics()
|
||||
response_queue.put(response)
|
||||
finally:
|
||||
# Cleanup
|
||||
lag_monitor_task.cancel()
|
||||
if discovery:
|
||||
await discovery.stop()
|
||||
else:
|
||||
for c in clients:
|
||||
await c.close()
|
||||
for task in pending_tasks:
|
||||
task.cancel()
|
||||
|
||||
|
||||
def worker_main(
|
||||
request_queue: Queue,
|
||||
response_queue: Queue,
|
||||
env_id: str,
|
||||
env_args: dict,
|
||||
client_config_dict: dict,
|
||||
seq_len: int,
|
||||
interleaved_rollouts: bool,
|
||||
max_concurrent_groups: int,
|
||||
tasks_per_minute: int,
|
||||
example_lookup: dict[int, dict],
|
||||
log_level: str,
|
||||
vf_log_level: str,
|
||||
log_file: str | None,
|
||||
worker_name: str | None = None,
|
||||
model_name: str = "",
|
||||
json_logging: bool = False,
|
||||
):
|
||||
"""Main entry point for worker subprocess."""
|
||||
# Reset logger inherited from parent process, then setup fresh logger for this worker
|
||||
if log_file:
|
||||
reset_logger()
|
||||
setup_logger(log_level, log_file=Path(log_file), append=True, tag=worker_name, json_logging=json_logging)
|
||||
intercept_verifiers_logging(level=vf_log_level)
|
||||
|
||||
# Load environment
|
||||
env = vf.load_environment(strip_env_version(env_id), **env_args)
|
||||
env.set_max_seq_len(seq_len)
|
||||
env.set_interleaved_rollouts(True)
|
||||
|
||||
# Create clients (empty list in elastic mode - workers discover servers dynamically)
|
||||
client_config = ClientConfig(**client_config_dict)
|
||||
clients = [] if client_config.is_elastic else setup_clients(client_config)
|
||||
|
||||
# Run async loop
|
||||
asyncio.run(
|
||||
worker_loop(
|
||||
request_queue,
|
||||
response_queue,
|
||||
env,
|
||||
clients,
|
||||
client_config,
|
||||
max_concurrent_groups,
|
||||
tasks_per_minute,
|
||||
example_lookup,
|
||||
model_name,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class EnvWorker:
|
||||
"""Manages a worker subprocess for environment rollouts."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
env_id: str,
|
||||
env_args: dict,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
seq_len: int,
|
||||
interleaved_rollouts: bool,
|
||||
max_concurrent_groups: int,
|
||||
tasks_per_minute: int,
|
||||
example_lookup: dict[int, dict],
|
||||
worker_name: str | None = None,
|
||||
log_level: str = "warn",
|
||||
vf_log_level: str = "warn",
|
||||
log_file: str | None = None,
|
||||
max_restarts: int = 5,
|
||||
json_logging: bool = False,
|
||||
):
|
||||
self.env_id = env_id
|
||||
self.env_args = env_args
|
||||
self.client_config = client_config
|
||||
self.model_name = model_name
|
||||
self.seq_len = seq_len
|
||||
self.interleaved_rollouts = interleaved_rollouts
|
||||
self.max_concurrent_groups = max_concurrent_groups
|
||||
self.tasks_per_minute = tasks_per_minute
|
||||
self.example_lookup = example_lookup
|
||||
self.worker_name = worker_name or env_id
|
||||
|
||||
self.log_level = log_level
|
||||
self.vf_log_level = vf_log_level
|
||||
self.log_file = log_file
|
||||
self.max_restarts = max_restarts
|
||||
self.json_logging = json_logging
|
||||
|
||||
self.request_queue: Queue = Queue()
|
||||
self.response_queue: Queue = Queue()
|
||||
self.process: Process | None = None
|
||||
|
||||
# Track pending requests for response matching
|
||||
self.pending_futures: dict[str, asyncio.Future] = {}
|
||||
|
||||
# Track latest lag metrics from this worker
|
||||
self.latest_lag_metrics: dict = {}
|
||||
|
||||
# Track intentional shutdown to avoid false error on clean stop
|
||||
self._stopping = False
|
||||
# Track if worker died unexpectedly (prevents scheduler from routing to dead worker)
|
||||
self._dead = False
|
||||
# Track restart count to prevent infinite restart loops
|
||||
self._restart_count = 0
|
||||
# Track fatal error when max restarts exceeded (orchestrator should crash)
|
||||
self._fatal_error: Exception | None = None
|
||||
# Track successful responses since last restart (to reset restart count)
|
||||
self._responses_since_restart = 0
|
||||
|
||||
def start(self):
|
||||
"""Start the worker process."""
|
||||
self.process = Process(
|
||||
target=worker_main,
|
||||
args=(
|
||||
self.request_queue,
|
||||
self.response_queue,
|
||||
self.env_id,
|
||||
self.env_args,
|
||||
self.client_config.model_dump(),
|
||||
self.seq_len,
|
||||
self.interleaved_rollouts,
|
||||
self.max_concurrent_groups,
|
||||
self.tasks_per_minute,
|
||||
self.example_lookup,
|
||||
self.log_level,
|
||||
self.vf_log_level,
|
||||
self.log_file,
|
||||
self.worker_name,
|
||||
self.model_name,
|
||||
self.json_logging,
|
||||
),
|
||||
daemon=True,
|
||||
)
|
||||
self.process.start()
|
||||
self._stopping = False # Reset after process is alive to avoid race condition
|
||||
self._dead = False # Reset in case of restart
|
||||
|
||||
def stop(self):
|
||||
"""Stop the worker process."""
|
||||
self._stopping = True
|
||||
if self.process and self.process.is_alive():
|
||||
self.request_queue.put(None) # Shutdown signal
|
||||
self.process.join(timeout=5)
|
||||
if self.process.is_alive():
|
||||
self.process.terminate()
|
||||
|
||||
def _restart(self):
|
||||
"""Restart the worker process after unexpected death."""
|
||||
# Clean up old process if it exists
|
||||
if self.process is not None:
|
||||
if self.process.is_alive():
|
||||
self.process.terminate()
|
||||
# Always join to reap zombie process, even if already dead
|
||||
self.process.join(timeout=5)
|
||||
self.process.close()
|
||||
|
||||
# Clear queues to avoid stale data (drain without blocking)
|
||||
while True:
|
||||
try:
|
||||
self.request_queue.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
while True:
|
||||
try:
|
||||
self.response_queue.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
|
||||
# Start fresh process
|
||||
self.start()
|
||||
|
||||
async def submit_request(
|
||||
self,
|
||||
example_id: int,
|
||||
rollouts_per_example: int,
|
||||
sampling_args: dict,
|
||||
) -> tuple[asyncio.Future, str]:
|
||||
"""Submit a rollout request and return a (future, request_id) tuple."""
|
||||
request_id = uuid.uuid4().hex
|
||||
request = RolloutRequest(
|
||||
request_id=request_id,
|
||||
example_id=example_id,
|
||||
rollouts_per_example=rollouts_per_example,
|
||||
model_name=self.model_name,
|
||||
sampling_args=sampling_args,
|
||||
)
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
future = loop.create_future()
|
||||
self.pending_futures[request_id] = future
|
||||
|
||||
self.request_queue.put(request)
|
||||
return future, request_id
|
||||
|
||||
async def collect_responses(self):
|
||||
"""Background task to collect responses and resolve futures."""
|
||||
logger = get_logger()
|
||||
while True:
|
||||
# Drain queue first to salvage any responses before checking for dead worker
|
||||
while True:
|
||||
try:
|
||||
response: RolloutResponse = self.response_queue.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
# Store latest lag metrics from worker
|
||||
if response.lag_metrics:
|
||||
self.latest_lag_metrics = response.lag_metrics
|
||||
if response.request_id in self.pending_futures:
|
||||
future = self.pending_futures.pop(response.request_id)
|
||||
# Check if future was cancelled (e.g., by update_policy)
|
||||
if not future.done():
|
||||
future.set_result(response.results)
|
||||
# Track successful responses; reset restart count after stable operation
|
||||
self._responses_since_restart += 1
|
||||
if self._responses_since_restart >= 10 and self._restart_count > 0:
|
||||
logger.debug(
|
||||
f"Worker '{self.worker_name}' stable after {self._responses_since_restart} responses, resetting restart count"
|
||||
)
|
||||
self._restart_count = 0
|
||||
self._responses_since_restart = 0
|
||||
|
||||
# Check if worker process died unexpectedly (but not during intentional shutdown)
|
||||
if self.process and not self.process.is_alive() and not self._stopping:
|
||||
exit_code = self.process.exitcode
|
||||
error = WorkerDiedError(f"Worker '{self.worker_name}' died unexpectedly (exit code: {exit_code})")
|
||||
# Mark worker as dead so scheduler won't route new requests here
|
||||
self._dead = True
|
||||
# Fail remaining pending futures so callers don't hang indefinitely
|
||||
for future in self.pending_futures.values():
|
||||
if not future.done():
|
||||
future.set_exception(error)
|
||||
self.pending_futures.clear()
|
||||
|
||||
# Check if we've exceeded max restarts (-1 means unlimited)
|
||||
self._restart_count += 1
|
||||
if self.max_restarts >= 0 and self._restart_count > self.max_restarts:
|
||||
logger.error(
|
||||
f"Worker '{self.worker_name}' died {self._restart_count} times, exceeding max restarts ({self.max_restarts}). Giving up."
|
||||
)
|
||||
# Store fatal error so orchestrator can detect and crash
|
||||
self._fatal_error = error
|
||||
raise error
|
||||
|
||||
# Log warning and restart the worker automatically
|
||||
restart_info = (
|
||||
f"{self._restart_count}/{self.max_restarts}" if self.max_restarts >= 0 else f"{self._restart_count}"
|
||||
)
|
||||
logger.warning(
|
||||
f"Worker '{self.worker_name}' died unexpectedly (exit code: {exit_code}). "
|
||||
f"Restarting worker automatically ({restart_info}). In-flight requests will be rescheduled."
|
||||
)
|
||||
self._responses_since_restart = 0 # Reset on restart
|
||||
self._restart()
|
||||
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
def update_model_name(self, model_name: str):
|
||||
"""Update the model name for future requests."""
|
||||
get_logger().debug(f"Worker '{self.worker_name}' switching model: {self.model_name} -> {model_name}")
|
||||
self.model_name = model_name
|
||||
|
||||
@property
|
||||
def pending_count(self) -> int:
|
||||
"""Number of pending requests for this worker.
|
||||
|
||||
Returns a large number if the worker is dead to prevent scheduler from selecting it.
|
||||
"""
|
||||
if self._dead:
|
||||
return 999999 # Effectively infinite - scheduler will pick other workers
|
||||
return len(self.pending_futures)
|
||||
@@ -0,0 +1,138 @@
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
|
||||
from prime_rl.orchestrator.config import EvalSamplingConfig
|
||||
from prime_rl.orchestrator.vf_utils import evaluate, get_completion_len
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor import get_monitor
|
||||
from prime_rl.utils.utils import capitalize
|
||||
|
||||
|
||||
def get_eval_sampling_args(sampling_config: EvalSamplingConfig) -> dict[str, Any]:
|
||||
"""Get sampling args for evaluation."""
|
||||
# Initialize sampling args
|
||||
sampling_args: dict[str, Any] = {}
|
||||
|
||||
# Apply sampling arguments, if specified
|
||||
if sampling_config.temperature is not None:
|
||||
sampling_args["temperature"] = sampling_config.temperature
|
||||
if sampling_config.max_tokens is not None:
|
||||
sampling_args["max_tokens"] = sampling_config.max_tokens
|
||||
if sampling_config.top_p is not None:
|
||||
sampling_args["top_p"] = sampling_config.top_p
|
||||
if sampling_config.reasoning_effort is not None:
|
||||
sampling_args["reasoning_effort"] = sampling_config.reasoning_effort
|
||||
|
||||
extra_body: dict[str, Any] = sampling_config.extra_body.copy()
|
||||
|
||||
# Apply vLLM-specific sampling arguments, if specified
|
||||
if sampling_config.top_k is not None:
|
||||
extra_body["top_k"] = sampling_config.top_k
|
||||
if sampling_config.min_p is not None:
|
||||
extra_body["min_p"] = sampling_config.min_p
|
||||
if sampling_config.min_tokens is not None:
|
||||
extra_body["min_tokens"] = sampling_config.min_tokens
|
||||
if sampling_config.repetition_penalty is not None:
|
||||
extra_body["repetition_penalty"] = sampling_config.repetition_penalty
|
||||
|
||||
sampling_args["extra_body"] = extra_body
|
||||
|
||||
return sampling_args
|
||||
|
||||
|
||||
def compute_pass_at_k(rewards: list[int]) -> dict[str, float]:
|
||||
total_attempts = len(rewards)
|
||||
k = total_attempts // 2
|
||||
|
||||
if k == 0:
|
||||
return {"pass@1": float(any(reward == 1.0 for reward in rewards))}
|
||||
|
||||
num_trials = 100
|
||||
pass_rates = []
|
||||
|
||||
for _ in range(num_trials):
|
||||
sampled_rewards = np.random.choice(rewards, size=k, replace=False)
|
||||
pass_rate = float(any(reward == 1.0 for reward in sampled_rewards))
|
||||
pass_rates.append(pass_rate)
|
||||
|
||||
return {f"pass@{k}": float(np.mean(pass_rates))}
|
||||
|
||||
|
||||
async def evaluate_env(
|
||||
env: vf.Environment,
|
||||
env_name: str,
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
sampling_args: dict,
|
||||
num_examples: int,
|
||||
rollouts_per_example: int,
|
||||
ckpt_step: int,
|
||||
step: int | None,
|
||||
):
|
||||
logger = get_logger()
|
||||
logger.info(f"Evaluating {env_name} ({num_examples=}, {rollouts_per_example=})")
|
||||
eval_start_time = time.perf_counter()
|
||||
outputs = await evaluate(env, clients, model_name, sampling_args, num_examples, rollouts_per_example)
|
||||
eval_time = time.perf_counter() - eval_start_time
|
||||
|
||||
rows = []
|
||||
for output in outputs:
|
||||
rows.append(
|
||||
{
|
||||
"example_id": output["example_id"],
|
||||
"reward": output["reward"],
|
||||
"completion_len": get_completion_len(output),
|
||||
"is_truncated": output["is_truncated"],
|
||||
"has_error": output.get("error") is not None,
|
||||
"no_response": not output.get("completion"),
|
||||
}
|
||||
)
|
||||
results_df = pd.DataFrame(rows)
|
||||
|
||||
unique_rewards = results_df.reward.dropna().unique()
|
||||
could_be_binary = set(unique_rewards).issubset({0.0, 1.0})
|
||||
if could_be_binary:
|
||||
pass_at_k = (
|
||||
results_df.groupby("example_id")
|
||||
.apply(lambda x: compute_pass_at_k(x.reward.dropna()), include_groups=False)
|
||||
.apply(pd.Series)
|
||||
)
|
||||
else:
|
||||
pass_at_k = None
|
||||
logger.warning("Skipping computing pass@k rates because the task rewards appear to be non-binary")
|
||||
|
||||
# Log statistics to console
|
||||
message = f"Evaluated {env.env_id} in {eval_time:.2f}s (Avg@{rollouts_per_example}={results_df.reward.mean():.4f}"
|
||||
if could_be_binary:
|
||||
assert pass_at_k is not None
|
||||
for pass_rate, pass_rate_score in pd.Series(pass_at_k.mean()).items():
|
||||
message += f", {capitalize(str(pass_rate))}: {pass_rate_score:.4f}"
|
||||
message += (
|
||||
f", No-response: {results_df.no_response.mean() * 100:.1f}%"
|
||||
f", Completion Length: {results_df.completion_len.mean():.2f} (±{results_df.completion_len.std():.2f}, ∈[{results_df.completion_len.min():.2f}, {results_df.completion_len.max():.2f}])"
|
||||
f", Truncated: {results_df.is_truncated.mean() * 100:.1f}%)"
|
||||
)
|
||||
logger.success(message)
|
||||
|
||||
# Log statistics to monitor
|
||||
eval_metrics = {
|
||||
f"avg@{rollouts_per_example}": results_df.reward.mean(),
|
||||
"no_response/mean": results_df.no_response.mean(),
|
||||
"no_response/count": results_df.no_response.sum(),
|
||||
"completion_len/mean": results_df.completion_len.mean().item(),
|
||||
"completion_len/max": results_df.completion_len.max().item(),
|
||||
"completion_len/min": results_df.completion_len.min().item(),
|
||||
"is_truncated/mean": results_df.is_truncated.mean().item(),
|
||||
"time": eval_time,
|
||||
}
|
||||
if could_be_binary:
|
||||
assert pass_at_k is not None
|
||||
eval_metrics.update(pd.Series(pass_at_k.mean()).to_dict())
|
||||
eval_metrics = {**{f"eval/{env_name}/{k}": v for k, v in eval_metrics.items()}}
|
||||
eval_metrics.update({"progress/ckpt_step": ckpt_step, "step": step or ckpt_step})
|
||||
monitor = get_monitor()
|
||||
monitor.log(eval_metrics, step=None)
|
||||
@@ -6,10 +6,12 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.orchestrator.advantage import compute_advantages
|
||||
from prime_rl.orchestrator.eval_utils import get_eval_sampling_args
|
||||
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
|
||||
from prime_rl.orchestrator.patches import monkey_patch_chat_completion_logprobs, monkey_patch_oai_iterable_types
|
||||
from prime_rl.orchestrator.trajectories import build_vlm_image_cache, interleave_rollout
|
||||
from prime_rl.transport import TrainingBatch, TrainingSample, setup_training_batch_sender
|
||||
from prime_rl.utils.pathing import get_log_dir
|
||||
|
||||
# This monkey patch is necessary to avoid Pydantic validating fields using typing.Iterable (e.g. in multimodal or tool call messages) lazily which leads to tokenization errors, for more info see https://github.com/PrimeIntellect-ai/prime-rl/pull/1249
|
||||
monkey_patch_oai_iterable_types()
|
||||
@@ -25,10 +27,10 @@ import verifiers as vf
|
||||
from loguru import logger
|
||||
from transformers import AutoProcessor, AutoTokenizer
|
||||
|
||||
from prime_rl.eval.utils import run_evals_subprocess
|
||||
from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.orchestrator.config import BufferConfig, OrchestratorConfig
|
||||
from prime_rl.orchestrator.eval_utils import evaluate_env
|
||||
from prime_rl.orchestrator.scheduler import Scheduler
|
||||
from prime_rl.orchestrator.utils import (
|
||||
compute_teacher_logprobs,
|
||||
@@ -37,17 +39,22 @@ from prime_rl.orchestrator.utils import (
|
||||
print_benchmark,
|
||||
set_semaphore,
|
||||
)
|
||||
from prime_rl.orchestrator.vf_utils import (
|
||||
generate,
|
||||
get_completion_len,
|
||||
get_prompt_len,
|
||||
get_seq_len,
|
||||
setup_env_client,
|
||||
spawn_env_server,
|
||||
wait_for_env_servers,
|
||||
)
|
||||
from prime_rl.utils.client import (
|
||||
check_health,
|
||||
init_nccl_broadcast,
|
||||
maybe_check_has_model,
|
||||
reload_weights,
|
||||
setup_admin_clients,
|
||||
setup_clients,
|
||||
setup_inference_pool,
|
||||
)
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import intercept_verifiers_logging, setup_logger
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
from prime_rl.utils.temp_scheduling import compute_temperature
|
||||
@@ -60,7 +67,6 @@ from prime_rl.utils.utils import (
|
||||
strip_env_version,
|
||||
to_col_format,
|
||||
)
|
||||
from prime_rl.utils.vf import generate_batch, get_completion_len, get_prompt_len, get_seq_len
|
||||
from prime_rl.utils.vlm import is_vlm_model
|
||||
|
||||
|
||||
@@ -73,7 +79,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_file=config.output_dir / "logs" / "orchestrator.log" if config.log.file else None,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
intercept_verifiers_logging(level=config.log.vf_level)
|
||||
vf.setup_logging(level="CRITICAL")
|
||||
logger.info("Starting orchestrator")
|
||||
|
||||
event_loop_lag_monitor = EventLoopLagMonitor()
|
||||
@@ -99,22 +105,19 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
install_env(env_id)
|
||||
|
||||
# Setup inference pool (handles both static and elastic modes)
|
||||
inference_pool = await setup_inference_pool(config.client, base_model=config.model.name)
|
||||
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name)
|
||||
|
||||
admin_clients = inference_pool.admin_clients
|
||||
|
||||
# Setup teacher model client if configured
|
||||
teacher_clients = None
|
||||
teacher_admin_clients = None
|
||||
teacher_model_name = None
|
||||
# Setup teacher inference pool if configured
|
||||
if config.teacher_model:
|
||||
logger.info(
|
||||
f"Initializing teacher OpenAI client (base_url={', '.join(config.teacher_model.client.base_url)}, "
|
||||
f"Initializing teacher inference pool (base_url={', '.join(config.teacher_model.client.base_url)}, "
|
||||
f"model={config.teacher_model.model.name})"
|
||||
)
|
||||
teacher_clients = setup_clients(config.teacher_model.client)
|
||||
teacher_admin_clients = setup_admin_clients(config.teacher_model.client)
|
||||
teacher_model_name = config.teacher_model.model.name
|
||||
teacher_inference_pool = await setup_inference_pool(
|
||||
config.teacher_model.client, model_name=config.teacher_model.model.name
|
||||
)
|
||||
else:
|
||||
teacher_inference_pool = None
|
||||
|
||||
# Check if this is a vision-language model (used throughout for VLM-specific paths)
|
||||
is_vlm = is_vlm_model(config.model.name)
|
||||
@@ -150,26 +153,84 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info(
|
||||
f"Loading {len(config.env)} training environment(s) ({', '.join(env.name or env.id for env in config.env)})"
|
||||
)
|
||||
env = vf.EnvGroup(
|
||||
envs=[vf.load_environment(strip_env_version(env.id), **env.args) for env in config.env],
|
||||
env_names=[env.name or env.id for env in config.env],
|
||||
map_kwargs=dict(writer_batch_size=1), # Set defensively to not error on map operations on large datasets
|
||||
env_ids = [strip_env_version(env.id) for env in config.env]
|
||||
train_env_group = vf.EnvGroup(
|
||||
envs=[vf.load_environment(env_id, **env.args) for env_id, env in zip(env_ids, config.env)],
|
||||
env_names=[env.name or env_id for env_id, env in zip(env_ids, config.env)],
|
||||
map_kwargs=dict(writer_batch_size=1), # set defensively to not error on map operations on large datasets
|
||||
)
|
||||
env.set_max_seq_len(config.seq_len)
|
||||
logger.info("Using token prompts in environment to avoid retokenization discrepancies in multi-turn rollouts")
|
||||
env.set_interleaved_rollouts(True)
|
||||
if config.buffer.skip_verification:
|
||||
logger.info("Skipping verification (rewards will be set to 0)")
|
||||
env.set_score_rollouts(False)
|
||||
|
||||
train_env_addresses = []
|
||||
for env_id, env, env_name in zip(env_ids, config.env, train_env_group.env_names):
|
||||
if env.address is None:
|
||||
address = spawn_env_server(
|
||||
env_id=env_id,
|
||||
env_args=env.args,
|
||||
extra_env_kwargs=env.extra_env_kwargs,
|
||||
log_level="CRITICAL",
|
||||
log_file=(get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix(),
|
||||
log_file_level=config.log.vf_level,
|
||||
)
|
||||
else:
|
||||
address = env.address
|
||||
logger.info(f"Connecting train environment {env_name} to server at {address}")
|
||||
train_env_addresses.append(address)
|
||||
train_env_clients = [setup_env_client(address) for address in train_env_addresses]
|
||||
|
||||
logger.info("Waiting for train environment servers to be ready")
|
||||
await wait_for_env_servers(train_env_clients)
|
||||
logger.success("Train environment servers ready")
|
||||
|
||||
# this puts all train envs into server model
|
||||
# all calls to run_rollout and run_group will be routed to the server via the env client
|
||||
for env, env_client in zip(train_env_group.envs, train_env_clients):
|
||||
env.env_client = env_client
|
||||
|
||||
if config.eval:
|
||||
env_ids = [strip_env_version(env.id) for env in config.eval.env]
|
||||
eval_envs = [vf.load_environment(env_id, **env.args) for env_id, env in zip(env_ids, config.eval.env)]
|
||||
eval_env_names = [env.name or env_id for env_id, env in zip(env_ids, config.eval.env)]
|
||||
eval_sampling_args = get_eval_sampling_args(config.eval.sampling)
|
||||
eval_env_addresses = []
|
||||
|
||||
for env_id, env, eval_env_name in zip(env_ids, config.eval.env, eval_env_names):
|
||||
if env.address is None:
|
||||
address = spawn_env_server(
|
||||
env_id=env_id,
|
||||
env_args=env.args,
|
||||
extra_env_kwargs=env.extra_env_kwargs,
|
||||
log_level="CRITICAL",
|
||||
log_file=(get_log_dir(config.output_dir) / "eval" / f"{eval_env_name}.log").as_posix(),
|
||||
log_file_level=config.log.vf_level,
|
||||
)
|
||||
else:
|
||||
address = env.address
|
||||
logger.info(f"Connecting eval environment {eval_env_name} to server at {address}")
|
||||
eval_env_addresses.append(address)
|
||||
|
||||
eval_env_clients = [setup_env_client(address) for address in eval_env_addresses]
|
||||
|
||||
logger.info("Waiting for eval environment servers to be ready")
|
||||
await wait_for_env_servers(eval_env_clients)
|
||||
logger.success("Eval environment servers ready")
|
||||
|
||||
# this puts all eval envs into server mode
|
||||
# all calls to run_rollout and run_group will be routed to the server via the env client
|
||||
for eval_env, eval_env_client in zip(eval_envs, eval_env_clients):
|
||||
eval_env.env_client = eval_env_client
|
||||
else:
|
||||
eval_envs: list[vf.Environment] = []
|
||||
eval_env_names: list[str] = []
|
||||
eval_sampling_args = {}
|
||||
|
||||
# Setup buffer
|
||||
logger.info(f"Setting up buffer ({config.buffer})")
|
||||
train_dataset = env.get_dataset(seed=config.buffer.seed)
|
||||
buffer = Buffer(train_dataset, env.env_names, config.buffer)
|
||||
train_dataset = train_env_group.get_dataset(seed=config.buffer.seed)
|
||||
buffer = Buffer(train_dataset, train_env_group.env_names, config.buffer)
|
||||
if config.val is not None:
|
||||
val_buffer_config = BufferConfig(env_ratios=config.buffer.env_ratios)
|
||||
val_dataset = env.get_eval_dataset(seed=val_buffer_config.seed)
|
||||
val_buffer = Buffer(val_dataset, env.env_names, val_buffer_config)
|
||||
val_dataset = train_env_group.get_eval_dataset(seed=val_buffer_config.seed)
|
||||
val_buffer = Buffer(val_dataset, train_env_group.env_names, val_buffer_config)
|
||||
else:
|
||||
val_buffer = None
|
||||
|
||||
@@ -185,48 +246,42 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
checkpoint_step = config.ckpt.resume_step
|
||||
|
||||
scheduler = Scheduler(
|
||||
client_config=config.client,
|
||||
env_configs=config.env,
|
||||
env=train_env_group,
|
||||
buffer=buffer,
|
||||
config=config,
|
||||
inference_pool=inference_pool,
|
||||
oversampling_factor=config.oversampling_factor,
|
||||
max_async_level=config.max_async_level,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
strict_async_level=config.strict_async_level,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
lora_name=config.model.lora.name if config.model.lora else None,
|
||||
output_dir=config.output_dir,
|
||||
inference_pool=inference_pool,
|
||||
config=config,
|
||||
)
|
||||
|
||||
if checkpoint_step is not None and config.model.lora is not None:
|
||||
assert config.model.lora.name is not None
|
||||
scheduler.model_name = config.model.lora.name
|
||||
for workers in scheduler.workers.values():
|
||||
for worker in workers:
|
||||
worker.model_name = config.model.lora.name
|
||||
|
||||
await scheduler.start()
|
||||
|
||||
# Check health of the inference pool
|
||||
logger.info("Waiting for inference pool to be ready")
|
||||
await inference_pool.wait_for_ready(config.model.name)
|
||||
# Refresh clients after waiting (elastic mode may have discovered new servers)
|
||||
admin_clients = inference_pool.admin_clients
|
||||
logger.success("Inference pool ready")
|
||||
|
||||
# Check health of teacher inference server if configured
|
||||
if teacher_admin_clients is not None:
|
||||
if config.teacher_model and teacher_inference_pool:
|
||||
logger.info("Waiting for teacher inference pool to be ready")
|
||||
await check_health(teacher_admin_clients)
|
||||
await maybe_check_has_model(
|
||||
teacher_clients, teacher_model_name, skip_model_check=config.teacher_model.client.skip_model_check
|
||||
)
|
||||
await teacher_inference_pool.wait_for_ready(config.teacher_model.model.name)
|
||||
logger.success("Teacher inference pool ready")
|
||||
|
||||
# Set up weight broadcast backend
|
||||
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
if config.weight_broadcast.type == "nccl":
|
||||
await init_nccl_broadcast(
|
||||
admin_clients, config.weight_broadcast.host, config.weight_broadcast.port, config.weight_broadcast.timeout
|
||||
inference_pool.admin_clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
)
|
||||
|
||||
# Setup training batch sender for sending training examples to trainer
|
||||
@@ -259,7 +314,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
if config.reload_weights_on_start:
|
||||
if config.model.lora is None:
|
||||
logger.info("Training from scratch. Resetting weights to base model")
|
||||
await reload_weights(admin_clients)
|
||||
await reload_weights(inference_pool.admin_clients)
|
||||
else:
|
||||
logger.info("Training from scratch. Skipping base weight reload because LoRA is enabled")
|
||||
else:
|
||||
@@ -327,24 +382,28 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
and ((ckpt_step == 0 and config.eval.eval_base_model) or ckpt_step > 0)
|
||||
):
|
||||
last_eval_step = ckpt_step
|
||||
logger.info(f"Running evals for checkpoint step {ckpt_step} (blocking, subprocess)")
|
||||
logger.info(f"Running evals for checkpoint step {ckpt_step}")
|
||||
|
||||
# Pause weight updates during eval and cancel inflight rollouts
|
||||
# this avoid doing eval across different checkpoints and avoid congestion
|
||||
scheduler.checkpoint_ready.clear()
|
||||
scheduler.cancel_all_inflight_rollouts()
|
||||
|
||||
await run_evals_subprocess(
|
||||
client_config=config.client,
|
||||
eval_config=config.eval,
|
||||
model_config=config.model,
|
||||
sampling_config=config.eval.sampling,
|
||||
reasoning_field=config.eval.reasoning_field,
|
||||
output_dir=config.output_dir,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
max_concurrent=config.max_concurrent or -1,
|
||||
json_logging=config.log.json_logging,
|
||||
results = await asyncio.gather(
|
||||
*[
|
||||
evaluate_env(
|
||||
env=eval_env,
|
||||
env_name=eval_env_name,
|
||||
clients=inference_pool.clients,
|
||||
model_name=scheduler.model_name,
|
||||
sampling_args=eval_sampling_args,
|
||||
num_examples=eval_env_config.num_examples or config.eval.num_examples,
|
||||
rollouts_per_example=eval_env_config.rollouts_per_example or config.eval.rollouts_per_example,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
)
|
||||
for eval_env, eval_env_name, eval_env_config in zip(eval_envs, eval_env_names, config.eval.env)
|
||||
]
|
||||
)
|
||||
|
||||
# Resume weight updates
|
||||
@@ -352,7 +411,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Schedule generating the training batch
|
||||
temperature = compute_temperature(progress.step, config.sampling, config.max_steps)
|
||||
scheduler.set_sampling_args(get_sampling_args(config.sampling, temperature=temperature))
|
||||
sampling_args = get_sampling_args(config.sampling, temperature=temperature)
|
||||
scheduler.set_sampling_args(sampling_args)
|
||||
train_task = asyncio.create_task(scheduler.generate_batch(step=progress.step))
|
||||
|
||||
# Schedule running validation at the specified interval
|
||||
@@ -360,13 +420,13 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info(f"Running validation for step {progress.step}")
|
||||
val_examples = val_buffer.sample_examples(config.val.num_examples)
|
||||
val_task = asyncio.create_task(
|
||||
generate_batch(
|
||||
generate(
|
||||
env=train_env_group,
|
||||
clients=inference_pool.clients,
|
||||
env=env,
|
||||
model_name=config.model.name,
|
||||
model_name=scheduler.model_name,
|
||||
examples=val_examples,
|
||||
rollouts_per_example=config.val.rollouts_per_example,
|
||||
sampling_args=get_sampling_args(config.sampling, temperature=temperature),
|
||||
sampling_args=sampling_args,
|
||||
pbar_description="Generating rollouts (val)",
|
||||
)
|
||||
)
|
||||
@@ -379,8 +439,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
train_rollouts = train_task.result()
|
||||
|
||||
# Compute advantages
|
||||
rewards = [rollout["reward"] for rollout in train_rollouts]
|
||||
completion_lens = [get_completion_len(rollout) for rollout in train_rollouts]
|
||||
example_ids = [r["example_id"] for r in train_rollouts]
|
||||
rewards = [r["reward"] for r in train_rollouts]
|
||||
completion_lens = [get_completion_len(r) for r in train_rollouts]
|
||||
advantages = compute_advantages(
|
||||
rewards,
|
||||
completion_lens,
|
||||
@@ -390,8 +451,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Convert rollouts to training samples
|
||||
parallel_preprocess_start = time.perf_counter()
|
||||
|
||||
num_unique_examples = len({r["example_id"] for r in train_rollouts})
|
||||
num_unique_examples = len(set(example_ids))
|
||||
|
||||
# VLM: build image cache for efficient batched preprocessing
|
||||
if is_vlm:
|
||||
@@ -403,7 +463,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
vlm_cache = None
|
||||
|
||||
# Process rollouts in parallel
|
||||
def process_rollout(rollout: vf.State, rollout_idx: int) -> list[TrainingSample] | None:
|
||||
def process_rollout(rollout: vf.RolloutOutput, rollout_idx: int) -> list[TrainingSample] | None:
|
||||
return interleave_rollout(rollout, vlm_cache=vlm_cache, cache_key=rollout_idx)
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
@@ -430,12 +490,12 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Compute teacher logprobs if teacher model is configured
|
||||
teacher_logprobs_time = 0
|
||||
if config.teacher_model is not None:
|
||||
if config.teacher_model and teacher_inference_pool:
|
||||
logger.info(f"Computing teacher logprobs for {len(train_examples)} training examples")
|
||||
teacher_logprobs_start_time = time.perf_counter()
|
||||
teacher_logprobs_list = await compute_teacher_logprobs(
|
||||
clients=teacher_clients,
|
||||
model_name=teacher_model_name,
|
||||
clients=teacher_inference_pool.clients,
|
||||
model_name=config.teacher_model.model.name,
|
||||
samples=train_examples,
|
||||
)
|
||||
for train_example, teacher_logprobs in zip(train_examples, teacher_logprobs_list):
|
||||
@@ -663,18 +723,22 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
heart.beat()
|
||||
|
||||
if config.eval:
|
||||
logger.info("Running final evals (subprocess)")
|
||||
await run_evals_subprocess(
|
||||
client_config=config.client,
|
||||
eval_config=config.eval,
|
||||
model_config=config.model,
|
||||
sampling_config=config.eval.sampling,
|
||||
reasoning_field=config.eval.reasoning_field,
|
||||
output_dir=config.output_dir,
|
||||
ckpt_step=scheduler.ckpt_step,
|
||||
step=progress.step,
|
||||
max_concurrent=config.max_concurrent or -1,
|
||||
json_logging=config.log.json_logging,
|
||||
logger.info("Running final evals")
|
||||
results = await asyncio.gather(
|
||||
*[
|
||||
evaluate_env(
|
||||
env=eval_env,
|
||||
env_name=eval_env_name,
|
||||
clients=inference_pool.clients,
|
||||
model_name=scheduler.model_name,
|
||||
sampling_args=eval_sampling_args,
|
||||
num_examples=eval_env_config.num_examples or config.eval.num_examples,
|
||||
rollouts_per_example=eval_env_config.rollouts_per_example or config.eval.rollouts_per_example,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
)
|
||||
for eval_env, eval_env_name, eval_env_config in zip(eval_envs, eval_env_names, config.eval.env)
|
||||
]
|
||||
)
|
||||
|
||||
# Log final (immutable) samples and distributions to monitor(s)
|
||||
@@ -692,12 +756,16 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Shutdown rollout executor
|
||||
rollout_executor.shutdown(wait=False)
|
||||
|
||||
# Stop env workers
|
||||
await scheduler.stop()
|
||||
# Stop scheduler
|
||||
scheduler.cancel_all_inflight_rollouts()
|
||||
update_policy_task.cancel()
|
||||
|
||||
# Stop inference pool
|
||||
await inference_pool.stop()
|
||||
|
||||
if teacher_inference_pool is not None:
|
||||
await teacher_inference_pool.stop()
|
||||
|
||||
# Cancel event loop lag monitor task
|
||||
event_loop_lag_monitor_task.cancel()
|
||||
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
"""
|
||||
Scheduler that runs environments in subprocesses.
|
||||
|
||||
Isolates event loop lag from environment execution.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -11,14 +5,15 @@ import time
|
||||
from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
import verifiers as vf
|
||||
from aiolimiter import AsyncLimiter
|
||||
|
||||
from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.config import EnvConfig, OrchestratorConfig
|
||||
from prime_rl.orchestrator.env_worker import EnvWorker, WorkerDiedError
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.orchestrator.utils import get_sampling_args
|
||||
from prime_rl.orchestrator.vf_utils import run_group
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.config import ClientConfig
|
||||
from prime_rl.utils.logger import ProgressTracker, get_logger
|
||||
from prime_rl.utils.pathing import get_env_worker_log_file
|
||||
from prime_rl.utils.temp_scheduling import compute_temperature
|
||||
from prime_rl.utils.utils import (
|
||||
get_broadcast_dir,
|
||||
@@ -32,15 +27,14 @@ class InflightRolloutInfo(NamedTuple):
|
||||
"""Metadata for an in-flight group rollout request."""
|
||||
|
||||
off_policy_steps: int
|
||||
worker: EnvWorker
|
||||
request_id: str
|
||||
client_config: vf.ClientConfig
|
||||
|
||||
|
||||
class Scheduler:
|
||||
"""Asynchronously schedules group rollout requests using subprocess workers.
|
||||
|
||||
Runs environment execution in separate processes to isolate event loop lag
|
||||
from the main orchestrator process.
|
||||
"""
|
||||
Asynchronously manages scheduling of group rollout requests and policy
|
||||
updates. Keeps a constant number of groups in-flight (continuous batching)
|
||||
and updates the policy as soon as it becomes available.
|
||||
|
||||
References:
|
||||
- AReal: https://arxiv.org/abs/2505.24298v1
|
||||
@@ -49,20 +43,24 @@ class Scheduler:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
client_config: ClientConfig,
|
||||
env_configs: list[EnvConfig],
|
||||
env: vf.Environment,
|
||||
inference_pool: InferencePool,
|
||||
buffer: Buffer,
|
||||
config: OrchestratorConfig,
|
||||
oversampling_factor: float,
|
||||
max_async_level: int,
|
||||
max_off_policy_steps: int,
|
||||
strict_async_level: bool,
|
||||
inference_pool: InferencePool,
|
||||
tasks_per_minute: int | None,
|
||||
lora_name: str | None = None,
|
||||
output_dir: Path | None = None,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.client_config = client_config
|
||||
if tasks_per_minute is not None:
|
||||
self.rate_limiter = AsyncLimiter(max_rate=tasks_per_minute, time_period=60)
|
||||
else:
|
||||
self.rate_limiter = None
|
||||
self.env = env
|
||||
self.buffer = buffer
|
||||
self.config = config
|
||||
self.batch_size = config.batch_size
|
||||
@@ -81,82 +79,17 @@ class Scheduler:
|
||||
# Inference pool - used for admin operations (adapter sync) and metrics
|
||||
self.inference_pool = inference_pool
|
||||
|
||||
# Build example lookup dicts per env (example_id -> example)
|
||||
self.example_lookups: dict[str, dict[int, dict]] = {}
|
||||
for env_config in env_configs:
|
||||
env_name = env_config.name or env_config.id
|
||||
self.example_lookups[env_name] = buffer.example_buffer[env_name].copy()
|
||||
|
||||
# Create workers - multiple per env
|
||||
self.workers_per_env = config.workers_per_env or 1
|
||||
self.workers: dict[str, list[EnvWorker]] = {}
|
||||
self.env_names: list[str] = []
|
||||
for env_config in env_configs:
|
||||
env_name = env_config.name or env_config.id
|
||||
self.env_names.append(env_name)
|
||||
self.workers[env_name] = []
|
||||
|
||||
# Setup log file if env worker file logging is enabled (all workers share one file)
|
||||
env_log_file = None
|
||||
if config.log.env_worker_logs and output_dir is not None:
|
||||
env_log_file = get_env_worker_log_file(output_dir, env_name)
|
||||
env_log_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for worker_idx in range(self.workers_per_env):
|
||||
# Start with base model name - workers will be updated after LoRA is loaded
|
||||
worker = EnvWorker(
|
||||
env_id=env_config.id,
|
||||
env_args=env_config.args,
|
||||
client_config=client_config,
|
||||
model_name=self.model_name,
|
||||
seq_len=config.seq_len,
|
||||
interleaved_rollouts=True,
|
||||
max_concurrent_groups=(config.max_concurrent // (self.rollouts_per_example * self.workers_per_env))
|
||||
if config.max_concurrent is not None
|
||||
else -1,
|
||||
tasks_per_minute=config.tasks_per_minute or -1,
|
||||
example_lookup=self.example_lookups[env_name],
|
||||
worker_name=f"{env_name}_{worker_idx}",
|
||||
log_level=config.log.level,
|
||||
vf_log_level=config.log.vf_level,
|
||||
log_file=str(env_log_file) if env_log_file else None,
|
||||
max_restarts=config.max_env_worker_restarts,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
self.workers[env_name].append(worker)
|
||||
|
||||
# Track in-flight requests: future -> info
|
||||
self.inflight_group_rollouts: dict[asyncio.Future, InflightRolloutInfo] = {}
|
||||
# Track in-flight requests: task -> info
|
||||
self.inflight_group_rollouts: dict[asyncio.Task, InflightRolloutInfo] = {}
|
||||
|
||||
self.step, self.ckpt_step = 0, 0
|
||||
self.checkpoint_ready = asyncio.Event()
|
||||
self.checkpoint_ready.set()
|
||||
self.update_weights_time, self.wait_for_ckpt_time = 0, 0
|
||||
self.update_policy_task = None
|
||||
self.cancelled_rollouts_count = 0
|
||||
self.last_batch_generation_time = 0.0
|
||||
|
||||
# Background tasks
|
||||
self._response_collectors: list[asyncio.Task] = []
|
||||
|
||||
async def start(self):
|
||||
"""Start all workers and response collectors."""
|
||||
total_workers = sum(len(workers) for workers in self.workers.values())
|
||||
self.logger.info(f"Starting {total_workers} env worker(s) ({self.workers_per_env} per env)")
|
||||
for workers in self.workers.values():
|
||||
for worker in workers:
|
||||
worker.start()
|
||||
# Start response collector for each worker
|
||||
task = asyncio.create_task(worker.collect_responses())
|
||||
self._response_collectors.append(task)
|
||||
|
||||
async def stop(self):
|
||||
"""Stop all workers and collectors."""
|
||||
for task in self._response_collectors:
|
||||
task.cancel()
|
||||
for workers in self.workers.values():
|
||||
for worker in workers:
|
||||
worker.stop()
|
||||
|
||||
def set_sampling_args(self, sampling_args: dict) -> None:
|
||||
"""Update sampling args for future rollout requests."""
|
||||
self.sampling_args = sampling_args
|
||||
@@ -175,24 +108,22 @@ class Scheduler:
|
||||
|
||||
async def schedule_group_rollout(self):
|
||||
"""Asynchronously schedules a group rollout request."""
|
||||
if self.rate_limiter:
|
||||
await self.rate_limiter.acquire()
|
||||
example = self.buffer.sample_examples(n=1)[0]
|
||||
|
||||
# Route to worker for this example's environment
|
||||
task = example["task"]
|
||||
workers = self.workers[task]
|
||||
worker = min(workers, key=lambda w: w.pending_count)
|
||||
|
||||
future, request_id = await worker.submit_request(
|
||||
example_id=example["example_id"],
|
||||
rollouts_per_example=self.config.rollouts_per_example,
|
||||
sampling_args=self.sampling_args,
|
||||
)
|
||||
|
||||
self.inflight_group_rollouts[future] = InflightRolloutInfo(
|
||||
off_policy_steps=0,
|
||||
worker=worker,
|
||||
request_id=request_id,
|
||||
client_config = await self.inference_pool.get_next_client()
|
||||
run_group_task = asyncio.create_task(
|
||||
run_group(
|
||||
env=self.env,
|
||||
client=client_config,
|
||||
example=example,
|
||||
model_name=self.model_name,
|
||||
rollouts_per_example=self.config.rollouts_per_example,
|
||||
sampling_args=self.sampling_args,
|
||||
max_retries=0, # TODO: make configurable
|
||||
)
|
||||
)
|
||||
self.inflight_group_rollouts[run_group_task] = InflightRolloutInfo(0, client_config)
|
||||
|
||||
async def update_policy_loop(self):
|
||||
"""Continuously checks for new policy checkpoints."""
|
||||
@@ -235,51 +166,43 @@ class Scheduler:
|
||||
|
||||
if self.lora_name is not None:
|
||||
self.model_name = self.lora_name
|
||||
# Update workers to use LoRA name for future requests
|
||||
for workers in self.workers.values():
|
||||
for worker in workers:
|
||||
worker.update_model_name(self.lora_name)
|
||||
self.inference_pool.update_model_name(self.model_name)
|
||||
|
||||
self.checkpoint_ready.set()
|
||||
|
||||
# Handle off-policy tracking - cancel old requests
|
||||
futures_to_remove = []
|
||||
futures_to_update = []
|
||||
tasks_to_remove = []
|
||||
tasks_to_update = []
|
||||
|
||||
for future, info in self.inflight_group_rollouts.items():
|
||||
for task, info in self.inflight_group_rollouts.items():
|
||||
if info.off_policy_steps > self.max_off_policy_steps:
|
||||
if not future.done():
|
||||
future.cancel()
|
||||
futures_to_remove.append((future, info.worker))
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
tasks_to_remove.append((task, info.client_config))
|
||||
else:
|
||||
futures_to_update.append((future, info.off_policy_steps + 1, info.worker, info.request_id))
|
||||
tasks_to_update.append((task, info.off_policy_steps + 1, info.client_config))
|
||||
|
||||
# Remove cancelled
|
||||
for future, worker in futures_to_remove:
|
||||
self.inflight_group_rollouts.pop(future, None)
|
||||
self.cancelled_rollouts_count += len(futures_to_remove)
|
||||
for task, _ in tasks_to_remove:
|
||||
self.inflight_group_rollouts.pop(task, None)
|
||||
self.cancelled_rollouts_count += len(tasks_to_remove)
|
||||
|
||||
# Update off-policy steps for remaining
|
||||
for future, off_policy_steps, worker, request_id in futures_to_update:
|
||||
if future in self.inflight_group_rollouts:
|
||||
self.inflight_group_rollouts[future] = InflightRolloutInfo(
|
||||
off_policy_steps=off_policy_steps,
|
||||
worker=worker,
|
||||
request_id=request_id,
|
||||
for task, off_policy_steps, client_config in tasks_to_update:
|
||||
if task in self.inflight_group_rollouts:
|
||||
self.inflight_group_rollouts[task] = InflightRolloutInfo(
|
||||
off_policy_steps=off_policy_steps + 1, client_config=client_config
|
||||
)
|
||||
|
||||
if len(futures_to_remove) > 0:
|
||||
if len(tasks_to_remove) > 0:
|
||||
self.logger.warning(
|
||||
f"Cancelled {len(futures_to_remove)} old rollout requests (will refill naturally). Consider increasing max_off_policy_steps to avoid this."
|
||||
f"Cancelled {len(tasks_to_remove)} old rollout requests (will refill naturally). Consider increasing max_off_policy_steps to avoid this."
|
||||
)
|
||||
|
||||
self.ckpt_step = next_ckpt_step
|
||||
|
||||
async def generate_batch(self, step: int) -> list[dict]:
|
||||
"""Generate a batch of rollouts using workers.
|
||||
|
||||
Returns list of result dicts (not vf.State, since those stay in workers).
|
||||
"""
|
||||
async def generate_batch(self, step: int) -> list[vf.RolloutOutput]:
|
||||
"""Continuously generates a batch of rollouts."""
|
||||
self.step = step
|
||||
batch_start_time = time.perf_counter()
|
||||
|
||||
@@ -288,34 +211,34 @@ class Scheduler:
|
||||
while len(self.inflight_group_rollouts) < self.problems_per_batch:
|
||||
await self.schedule_group_rollout()
|
||||
|
||||
batch_rollouts: list[dict] = []
|
||||
batch_rollouts: list[vf.RolloutOutput] = []
|
||||
pbar = ProgressTracker(
|
||||
total=self.config.batch_size, desc="Generating rollouts (train)", json_logging=self.json_logging, step=step
|
||||
)
|
||||
|
||||
while len(batch_rollouts) < self.config.batch_size:
|
||||
# Wait for at least one future to complete
|
||||
done, _ = await asyncio.wait(
|
||||
finished_tasks, _ = await asyncio.wait(
|
||||
self.inflight_group_rollouts.keys(),
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
|
||||
await self.checkpoint_ready.wait()
|
||||
|
||||
for finished_future in done:
|
||||
for finished_task in finished_tasks:
|
||||
if len(batch_rollouts) >= self.config.batch_size:
|
||||
batch_rollouts = batch_rollouts[: self.config.batch_size]
|
||||
break
|
||||
|
||||
# Safely pop the future from tracking
|
||||
if self.inflight_group_rollouts.pop(finished_future, None) is None:
|
||||
if self.inflight_group_rollouts.pop(finished_task, None) is None:
|
||||
continue
|
||||
|
||||
try:
|
||||
group_results: list[dict] = finished_future.result()
|
||||
finished_rollouts: list[vf.RolloutOutput] = finished_task.result()
|
||||
|
||||
# Update buffer with results
|
||||
self.buffer.update(group_results)
|
||||
self.buffer.update(finished_rollouts)
|
||||
accepted_rollouts = self.buffer.sample_rollouts(n=self.config.rollouts_per_example)
|
||||
|
||||
batch_rollouts.extend(accepted_rollouts)
|
||||
@@ -323,11 +246,6 @@ class Scheduler:
|
||||
|
||||
except asyncio.CancelledError:
|
||||
pass # Request was cancelled, will be rescheduled
|
||||
except WorkerDiedError as e:
|
||||
# Worker died - check if it will auto-restart or if orchestrator should crash
|
||||
self.logger.warning(f"Rollout lost due to worker death: {e}")
|
||||
# Check if any worker has permanently failed (exceeded max restarts)
|
||||
self._check_for_fatal_worker_errors()
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Rollout failed: {e}")
|
||||
|
||||
@@ -337,14 +255,6 @@ class Scheduler:
|
||||
self.last_batch_generation_time = time.perf_counter() - batch_start_time
|
||||
return batch_rollouts
|
||||
|
||||
def _check_for_fatal_worker_errors(self):
|
||||
"""Check if any worker has permanently failed and raise the error to crash orchestrator."""
|
||||
for workers in self.workers.values():
|
||||
for worker in workers:
|
||||
if worker._fatal_error is not None:
|
||||
self.logger.error(f"Worker '{worker.worker_name}' permanently failed, crashing orchestrator")
|
||||
raise worker._fatal_error
|
||||
|
||||
@property
|
||||
def max_off_policy_level(self) -> int:
|
||||
if not self.inflight_group_rollouts:
|
||||
@@ -382,17 +292,6 @@ class Scheduler:
|
||||
}
|
||||
self.cancelled_rollouts_count = 0
|
||||
|
||||
# Add per-worker lag metrics and pending counts
|
||||
for workers in self.workers.values():
|
||||
for worker in workers:
|
||||
worker_key = worker.worker_name
|
||||
# Track pending count per worker (useful for debugging load balancing)
|
||||
metrics[f"worker/{worker_key}/pending"] = worker.pending_count
|
||||
if worker.latest_lag_metrics:
|
||||
for metric_name, value in worker.latest_lag_metrics.items():
|
||||
# e.g. "worker_lag/env_0/max"
|
||||
metrics[f"worker_lag/{worker_key}/{metric_name.split('/')[-1]}"] = value
|
||||
|
||||
# Add inference pool metrics (e.g. elastic pool server counts)
|
||||
metrics.update(self.inference_pool.get_metrics())
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import base64
|
||||
import time
|
||||
from io import BytesIO
|
||||
from typing import TypedDict
|
||||
|
||||
import verifiers as vf
|
||||
from PIL import Image
|
||||
@@ -9,25 +8,17 @@ from PIL import Image
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class TrajectoryStepWithTemp(TypedDict):
|
||||
"""Trajectory step with temperature field added by prime-rl's extract_result."""
|
||||
|
||||
tokens: vf.TrajectoryStepTokens
|
||||
temperature: float
|
||||
|
||||
|
||||
# We use list() instead of deepcopy() for flat lists (token IDs, logprobs) - safe because
|
||||
# primitives are immutable. pixel_values/image_grid_thw are not mutated after creation.
|
||||
|
||||
|
||||
def interleave_rollout(
|
||||
state: vf.State,
|
||||
output: vf.RolloutOutput,
|
||||
vlm_cache: "VLMImageCache | None" = None,
|
||||
cache_key: int | None = None,
|
||||
) -> list[TrainingSample] | None:
|
||||
"""
|
||||
Convert vf.State to trainable rollouts by interleaving trajectory steps
|
||||
Convert vf.RolloutOutput to trainable rollouts by interleaving trajectory steps
|
||||
where the extension property holds.
|
||||
|
||||
When consecutive steps share token prefixes (extension property), they are
|
||||
@@ -45,29 +36,31 @@ def interleave_rollout(
|
||||
Each sample gets the images accumulated up to its last merged step.
|
||||
|
||||
Args:
|
||||
state: vf.State containing trajectory data
|
||||
output: vf.RolloutOutput containing trajectory data
|
||||
vlm_cache: Pre-computed VLM image cache for multimodal training
|
||||
cache_key: Cache key to use when retrieving images from the VLM cache
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
trajectory = state["trajectory"]
|
||||
trajectory = output["trajectory"]
|
||||
if len(trajectory) == 0:
|
||||
logger.warning(f"No trajectory steps for example {state['example_id']}. Skipping rollout.")
|
||||
logger.warning(f"No trajectory steps for example {output['example_id']}. Skipping rollout.")
|
||||
return None
|
||||
|
||||
has_error = state["error"] is not None
|
||||
has_error = output["error"] is not None
|
||||
# this field should be guaranteed because we set temperature in get_sampling_args
|
||||
temperature = output["sampling_args"]["temperature"]
|
||||
|
||||
def get_images(step_idx: int) -> tuple[list | None, list | None]:
|
||||
if vlm_cache is None:
|
||||
return None, None
|
||||
key = state["example_id"] if cache_key is None else cache_key
|
||||
key = output["example_id"] if cache_key is None else cache_key
|
||||
return vlm_cache.get_for_step(key, step_idx)
|
||||
|
||||
def make_sample(step: TrajectoryStepWithTemp, step_idx: int) -> TrainingSample:
|
||||
def make_sample(step: vf.TrajectoryStep, step_idx: int) -> TrainingSample:
|
||||
"""Create a new TrainingSample from a trajectory step."""
|
||||
tokens = step["tokens"]
|
||||
temperature = step["temperature"]
|
||||
assert tokens is not None
|
||||
if has_error:
|
||||
completion_mask = [False] * len(tokens["completion_mask"])
|
||||
else:
|
||||
@@ -87,10 +80,10 @@ def interleave_rollout(
|
||||
image_grid_thw=image_grid_thw,
|
||||
)
|
||||
|
||||
def extend_sample(sample: TrainingSample, step: TrajectoryStepWithTemp, prefix_len: int, step_idx: int) -> None:
|
||||
def extend_sample(sample: TrainingSample, step: vf.TrajectoryStep, prefix_len: int, step_idx: int) -> None:
|
||||
"""Extend an existing sample with a new trajectory step (extension property holds)."""
|
||||
tokens = step["tokens"]
|
||||
temperature = step["temperature"]
|
||||
assert tokens is not None
|
||||
|
||||
# Extend with new prompt tokens (mask=False, no gradient)
|
||||
new_prompt_ids = tokens["prompt_ids"][prefix_len:]
|
||||
@@ -142,7 +135,7 @@ def interleave_rollout(
|
||||
else:
|
||||
# No prefix matches - start a new sample
|
||||
logger.debug(
|
||||
f"Extension property broke at step {step_idx + 1} for example {state['example_id']}. "
|
||||
f"Extension property broke at step {step_idx + 1} for example {output['example_id']}. "
|
||||
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
|
||||
)
|
||||
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
@@ -177,7 +170,7 @@ def _extract_images_from_messages(messages: list) -> list[Image.Image]:
|
||||
|
||||
|
||||
def _extract_images_from_examples(
|
||||
examples: list[tuple[int, vf.State]],
|
||||
examples: list[tuple[int, vf.RolloutOutput]],
|
||||
) -> tuple[list[Image.Image], dict[int, list[int]]]:
|
||||
"""
|
||||
Extract images from all trajectory steps of each example.
|
||||
@@ -187,7 +180,7 @@ def _extract_images_from_examples(
|
||||
full conversation history), so we extract only the NEW images introduced in each step.
|
||||
|
||||
Args:
|
||||
examples: List of (cache_key, state) tuples where state contains a "trajectory"
|
||||
examples: List of (cache_key, output) tuples where output contains a "trajectory"
|
||||
list with steps that have "prompt" messages in OpenAI chat format.
|
||||
|
||||
Returns:
|
||||
@@ -199,8 +192,8 @@ def _extract_images_from_examples(
|
||||
all_images = []
|
||||
images_per_step_per_example = {}
|
||||
|
||||
for eid, state in examples:
|
||||
trajectory = state.get("trajectory", [])
|
||||
for eid, output in examples:
|
||||
trajectory = output.get("trajectory", [])
|
||||
if not trajectory:
|
||||
images_per_step_per_example[eid] = []
|
||||
continue
|
||||
@@ -319,7 +312,7 @@ class VLMImageCache:
|
||||
return steps[-1]
|
||||
|
||||
|
||||
def build_vlm_image_cache(rollouts: list[vf.State], processor) -> VLMImageCache:
|
||||
def build_vlm_image_cache(rollouts: list[vf.RolloutOutput], processor) -> VLMImageCache:
|
||||
"""
|
||||
Build image cache for VLM training by extracting and preprocessing images.
|
||||
|
||||
|
||||
@@ -5,12 +5,13 @@ from pathlib import Path
|
||||
from typing import Any, AsyncContextManager
|
||||
|
||||
import pandas as pd
|
||||
from openai import AsyncOpenAI
|
||||
import verifiers as vf
|
||||
from openai.types.chat.chat_completion import ChatCompletion, Choice
|
||||
from openai.types.completion_usage import CompletionUsage
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from verifiers.utils.async_utils import maybe_semaphore
|
||||
from verifiers.utils.client_utils import setup_client
|
||||
|
||||
from prime_rl.orchestrator.config import SamplingConfig
|
||||
from prime_rl.transport import TrainingSample
|
||||
@@ -143,13 +144,15 @@ def print_benchmark(history: dict[str, list[Any]]) -> None:
|
||||
|
||||
|
||||
async def compute_teacher_logprobs(
|
||||
clients: list[AsyncOpenAI],
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
samples: list[TrainingSample],
|
||||
) -> list[list[float]]:
|
||||
"""Compute teacher model logprobs for a batch of training samples via prefill."""
|
||||
|
||||
async def _compute_single(client: AsyncOpenAI, sample: TrainingSample) -> list[float]:
|
||||
async def _compute_single(client_config: vf.ClientConfig, sample: TrainingSample) -> list[float]:
|
||||
client = setup_client(client_config)
|
||||
|
||||
async with await get_semaphore():
|
||||
response = await client.post(
|
||||
"/chat/completions/tokens",
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from itertools import cycle
|
||||
from multiprocessing import Process
|
||||
from typing import Any
|
||||
|
||||
import verifiers as vf
|
||||
from verifiers.envs.environment import EnvClient
|
||||
from verifiers.utils.worker_utils import get_free_port
|
||||
from verifiers.workers import ZMQEnvClient, ZMQEnvServer
|
||||
|
||||
from prime_rl.utils.logger import InterceptHandler, ProgressTracker, get_logger
|
||||
|
||||
DEFAULT_RETRIES = 3
|
||||
REQUIRED_STATE_COLUMNS = ["trajectory", "sampling_args"]
|
||||
DEFAULT_STATE_COLUMNS = []
|
||||
|
||||
|
||||
def spawn_env_server(
|
||||
env_id: str,
|
||||
env_args: dict[str, Any],
|
||||
extra_env_kwargs: dict[str, Any],
|
||||
address: str | None = None,
|
||||
log_level: str | None = None,
|
||||
log_file: str | None = None,
|
||||
log_file_level: str | None = None,
|
||||
daemon: bool = True,
|
||||
) -> str:
|
||||
"""
|
||||
Starts a ZMQEnvServer process in a subprocess.
|
||||
|
||||
Mirrors vf.Environment.start_server().
|
||||
"""
|
||||
address = address or f"tcp://127.0.0.1:{get_free_port()}"
|
||||
Process(
|
||||
target=ZMQEnvServer.run_server,
|
||||
args=(
|
||||
env_id,
|
||||
env_args,
|
||||
extra_env_kwargs,
|
||||
log_level,
|
||||
log_file,
|
||||
log_file_level,
|
||||
),
|
||||
kwargs=dict(address=address),
|
||||
daemon=daemon,
|
||||
).start()
|
||||
|
||||
return address
|
||||
|
||||
|
||||
def setup_env_client(address: str) -> EnvClient:
|
||||
"""Sets up a ZMQEnvClient for a given address."""
|
||||
return ZMQEnvClient(address=address)
|
||||
|
||||
|
||||
async def wait_for_env_servers(
|
||||
env_clients: list[EnvClient], interval: int = 1, log_interval: int = 10, timeout: int = 1800
|
||||
) -> None:
|
||||
logger = get_logger()
|
||||
|
||||
async def wait_for_env_server(env_client: EnvClient) -> None:
|
||||
wait_time = 0
|
||||
logger.debug(f"Starting pinging environment server at {env_client.address}")
|
||||
while wait_time < timeout:
|
||||
try:
|
||||
await env_client.health(timeout=1) # quick timeout
|
||||
logger.debug(f"Environment server at {env_client.address} is ready after {wait_time} seconds")
|
||||
return
|
||||
except Exception as e:
|
||||
if wait_time % log_interval == 0 and wait_time > 0:
|
||||
logger.warning(
|
||||
f"Environment server at {env_client.address} was not reached after {wait_time} seconds (Error: {e})"
|
||||
)
|
||||
await asyncio.sleep(interval)
|
||||
wait_time += interval
|
||||
msg = f"Environment server at {env_client.address} is not ready after {wait_time} (>{timeout}) seconds. Aborting..."
|
||||
logger.error(msg)
|
||||
raise TimeoutError(msg)
|
||||
|
||||
await asyncio.gather(*[wait_for_env_server(env_client) for env_client in env_clients])
|
||||
|
||||
|
||||
async def run_rollout(
|
||||
env: vf.Environment,
|
||||
client: vf.ClientConfig,
|
||||
model_name: str,
|
||||
example: dict,
|
||||
sampling_args: dict,
|
||||
max_retries: int = DEFAULT_RETRIES,
|
||||
state_columns: list[str] = DEFAULT_STATE_COLUMNS,
|
||||
) -> vf.RolloutOutput:
|
||||
"""
|
||||
Wrapper for vf.Environment.run_rollout().
|
||||
|
||||
Asynchronously generates and scores a rollout.
|
||||
"""
|
||||
state_columns = state_columns + REQUIRED_STATE_COLUMNS
|
||||
rollout_input = vf.RolloutInput(**example)
|
||||
return await env.run_rollout(
|
||||
rollout_input,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=sampling_args,
|
||||
max_retries=max_retries,
|
||||
state_columns=state_columns,
|
||||
)
|
||||
|
||||
|
||||
async def run_group(
|
||||
env: vf.Environment,
|
||||
client: vf.ClientConfig,
|
||||
model_name: str,
|
||||
example: dict,
|
||||
rollouts_per_example: int,
|
||||
sampling_args: dict,
|
||||
max_retries: int = DEFAULT_RETRIES,
|
||||
state_columns: list[str] = DEFAULT_STATE_COLUMNS,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""
|
||||
Wrapper for vf.Environment.run_group().
|
||||
|
||||
Asynchronously generates and scores a group.
|
||||
"""
|
||||
state_columns = state_columns + REQUIRED_STATE_COLUMNS
|
||||
group_inputs = [vf.RolloutInput(**example) for _ in range(rollouts_per_example)]
|
||||
return await env.run_group(
|
||||
group_inputs,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=sampling_args,
|
||||
max_retries=max_retries,
|
||||
state_columns=state_columns,
|
||||
)
|
||||
|
||||
|
||||
# TODO: migrate this to vf.Environment.generate() once it supports multiple clients
|
||||
async def generate(
|
||||
env: vf.Environment,
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
examples: list,
|
||||
rollouts_per_example: int,
|
||||
sampling_args: dict,
|
||||
max_retries: int = DEFAULT_RETRIES,
|
||||
state_columns: list[str] = DEFAULT_STATE_COLUMNS,
|
||||
pbar_description: str = "Generating rollouts",
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""
|
||||
Wrapper for vf.Environment.generate().
|
||||
|
||||
NOTE: Currently we cannot use vf.Environment.generate() directly because it does not support multiple clients.
|
||||
|
||||
Asynchronously generates and scores a list of groups.
|
||||
"""
|
||||
|
||||
total_rollouts = len(examples) * rollouts_per_example
|
||||
pbar = ProgressTracker(total=total_rollouts, desc=pbar_description)
|
||||
|
||||
async def run_group_with_progress(client, example):
|
||||
result = await run_group(
|
||||
env=env,
|
||||
client=client,
|
||||
model_name=model_name,
|
||||
example=example,
|
||||
rollouts_per_example=rollouts_per_example,
|
||||
max_retries=max_retries,
|
||||
state_columns=state_columns,
|
||||
sampling_args=sampling_args,
|
||||
)
|
||||
pbar.update(rollouts_per_example)
|
||||
return result
|
||||
|
||||
try:
|
||||
group_outputs_list: list[list[vf.RolloutOutput]] = await asyncio.gather(
|
||||
*[run_group_with_progress(client, example) for client, example in zip(cycle(clients), examples)]
|
||||
)
|
||||
finally:
|
||||
pbar.close()
|
||||
|
||||
return [output for group_outputs in group_outputs_list for output in group_outputs]
|
||||
|
||||
|
||||
async def evaluate(
|
||||
env: vf.Environment,
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
sampling_args: dict,
|
||||
num_examples: int,
|
||||
rollouts_per_example: int,
|
||||
max_retries: int = DEFAULT_RETRIES,
|
||||
state_columns: list[str] = DEFAULT_STATE_COLUMNS,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""
|
||||
Wrapper for vf.Environment.evaluate().
|
||||
|
||||
NOTE: Currently we cannot use vf.Environment.evaluate() directly because it does not support multiple clients.
|
||||
Instead, we use our generate() wrapper which round-robins clients.
|
||||
|
||||
"""
|
||||
inputs = env._get_eval_inputs(num_examples, rollouts_per_example)
|
||||
outputs = await generate(
|
||||
env=env,
|
||||
clients=clients,
|
||||
model_name=model_name,
|
||||
examples=inputs,
|
||||
# _get_eval_inputs() already repeats the examples, this currently means
|
||||
# we do not support eval envs with group scoring well -- this should be
|
||||
# resolved once we can use vf.Environment.generate() and
|
||||
# vf.Environment.evaluate() directly though
|
||||
rollouts_per_example=1,
|
||||
sampling_args=sampling_args,
|
||||
max_retries=max_retries,
|
||||
state_columns=state_columns,
|
||||
)
|
||||
return outputs
|
||||
|
||||
|
||||
# TODO: remove once usage is tracked by verifiers
|
||||
def get_prompt_len(output: vf.RolloutOutput) -> int:
|
||||
"""
|
||||
Computes the number of prompt tokens from vf.RolloutOutput. Defined as the
|
||||
number of prompt ids from the first trajectory step. If raw tokens are not
|
||||
available, falls back to checking the usage of the first response.
|
||||
"""
|
||||
if not output["trajectory"]:
|
||||
return 0
|
||||
first_step = output["trajectory"][0]
|
||||
if first_step["tokens"] is not None:
|
||||
return len(first_step["tokens"]["prompt_ids"])
|
||||
first_step_response = first_step["response"]
|
||||
return (first_step_response.get("usage") or {}).get("prompt_tokens", 0)
|
||||
|
||||
|
||||
# TODO: remove once usage is tracked by verifiers
|
||||
def get_seq_len(output: vf.RolloutOutput) -> int:
|
||||
"""
|
||||
Computes the number of tokens from vf.RolloutOutput. Defined as the sum of prompt
|
||||
and completion tokens from the last trajectory step. If raw tokens are not
|
||||
available, falls back to checking the usage of the last response.
|
||||
"""
|
||||
if not output["trajectory"]:
|
||||
return 0
|
||||
last_step = output["trajectory"][-1]
|
||||
if last_step["tokens"] is not None:
|
||||
return len(last_step["tokens"]["prompt_ids"]) + len(last_step["tokens"]["completion_ids"])
|
||||
last_step_response = last_step["response"]
|
||||
return (last_step_response.get("usage") or {}).get("total_tokens", 0)
|
||||
|
||||
|
||||
# TODO: remove once usage is tracked by verifiers
|
||||
def get_completion_len(output: vf.RolloutOutput) -> int:
|
||||
"""
|
||||
Computes the number of completion tokens from vf.RolloutOutput. Defined as
|
||||
the difference between the total number of tokens and the number of prompt
|
||||
tokens.
|
||||
"""
|
||||
return get_seq_len(output) - get_prompt_len(output)
|
||||
|
||||
|
||||
def intercept_vf_logging(level: str = "DEBUG", prefix: str = "verifiers"):
|
||||
"""Intercepts verifiers logging and routes through prime-rl logger with [verifiers] prefix."""
|
||||
vf_logger = logging.getLogger("verifiers")
|
||||
vf_logger.handlers.clear()
|
||||
vf_logger.addHandler(InterceptHandler(prefix=prefix))
|
||||
vf_logger.setLevel(level.upper())
|
||||
vf_logger.propagate = False
|
||||
@@ -1,44 +0,0 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from prime_rl.orchestrator.config import EvalConfig
|
||||
from prime_rl.utils.config import ClientConfig, LogConfig, ModelConfig
|
||||
from prime_rl.utils.pydantic_config import BaseSettings
|
||||
|
||||
|
||||
class SynthesizeConfig(EvalConfig, BaseSettings):
|
||||
"""Configures synthetic data generation."""
|
||||
|
||||
# The client configuration
|
||||
client: ClientConfig = ClientConfig(
|
||||
timeout=36000, base_url=["https://api.openai.com/v1"], api_key_var="OPENAI_API_KEY"
|
||||
)
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig(name="gpt-4.1-mini")
|
||||
|
||||
# The logging configuration
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
reasoning_field: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="The field in the raw model response that contains the reasoning content. Defaults to 'reasoning_content', which is the default for vLLM when serving a model with a reasoning parser. Other APIs (e.g. DeepSeek, GLM, etc.) may use different field names.",
|
||||
),
|
||||
] = "reasoning_content"
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
Field(
|
||||
description="Directory to write outputs to. Will be populated with artifacts such as reports and HF datasets as subdirectories. Should be set to a persistent directory with enough disk space."
|
||||
),
|
||||
] = Path("outputs")
|
||||
|
||||
max_concurrent: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Maximum number of concurrent rollouts to generate and score. Will create a global semaphore and pass to verifiers Environment. If None, will not limit concurrency.",
|
||||
),
|
||||
] = None
|
||||
@@ -1,78 +0,0 @@
|
||||
import asyncio
|
||||
|
||||
from prime_rl.synthesize.config import SynthesizeConfig
|
||||
from prime_rl.synthesize.utils import generate_synthetic_data
|
||||
from prime_rl.utils.client import (
|
||||
check_health,
|
||||
maybe_check_has_model,
|
||||
setup_admin_clients,
|
||||
setup_clients,
|
||||
)
|
||||
from prime_rl.utils.logger import intercept_verifiers_logging, setup_logger
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
from prime_rl.utils.utils import clean_exit, get_env_ids_to_install, install_env
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def synthesize(config: SynthesizeConfig):
|
||||
# Initialize the logger
|
||||
logger = setup_logger(
|
||||
config.log.level,
|
||||
log_file=config.output_dir / "logs" / "synthesize.log" if config.log.file else None,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
intercept_verifiers_logging(level=config.log.vf_level)
|
||||
|
||||
env_names = [env.name or env.id for env in config.env]
|
||||
logger.info(f"Starting synthetic data generation for {config.model.name} in environments {', '.join(env_names)}")
|
||||
logger.info(f"Using sampling config {config.sampling}")
|
||||
|
||||
# Install environments
|
||||
env_ids_to_install = get_env_ids_to_install(config.env)
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id)
|
||||
|
||||
# Setup clients
|
||||
logger.info(
|
||||
f"Initializing OpenAI client (base_url={', '.join(config.client.base_url)}, api_key_var={config.client.api_key_var}, headers={config.client.headers})"
|
||||
)
|
||||
clients = setup_clients(config.client)
|
||||
admin_clients = setup_admin_clients(config.client)
|
||||
|
||||
# Check health of the client
|
||||
logger.info("Waiting for inference pool to be ready")
|
||||
await check_health(admin_clients)
|
||||
await maybe_check_has_model(clients, config.model.name, skip_model_check=config.client.skip_model_check)
|
||||
logger.success(f"Inference pool is healthy and serves {config.model.name}")
|
||||
|
||||
# Generate synthetic data
|
||||
logger.info("Starting synthetic data generation")
|
||||
await asyncio.gather(
|
||||
*[
|
||||
generate_synthetic_data(
|
||||
clients=clients,
|
||||
env_id=env.id,
|
||||
env_name=env.name,
|
||||
env_args=env.args,
|
||||
num_examples=env.num_examples or config.num_examples,
|
||||
rollouts_per_example=env.rollouts_per_example or config.rollouts_per_example,
|
||||
reasoning_field=config.reasoning_field,
|
||||
skip_first=env.skip_first,
|
||||
output_dir=config.output_dir,
|
||||
model_config=config.model,
|
||||
sampling_config=config.sampling,
|
||||
client_config=config.client,
|
||||
)
|
||||
for env in config.env
|
||||
]
|
||||
)
|
||||
|
||||
logger.success("Synthetic data generation finished!")
|
||||
|
||||
|
||||
def main():
|
||||
asyncio.run(synthesize(parse_argv(SynthesizeConfig)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,189 +0,0 @@
|
||||
import asyncio
|
||||
import json
|
||||
from itertools import cycle
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import aiofiles
|
||||
import verifiers as vf
|
||||
from openai import AsyncOpenAI
|
||||
from verifiers import load_environment
|
||||
from verifiers.utils.path_utils import get_results_path
|
||||
|
||||
from prime_rl.orchestrator.config import ClientConfig, EvalSamplingConfig, ModelConfig
|
||||
from prime_rl.utils.logger import ProgressTracker, get_logger
|
||||
from prime_rl.utils.utils import strip_env_version
|
||||
from prime_rl.utils.vf import generate_group
|
||||
|
||||
WRITE_LOCK = asyncio.Lock()
|
||||
|
||||
|
||||
def prepare_sampling_args(sampling_config: EvalSamplingConfig, client_config: ClientConfig) -> dict[str, Any]:
|
||||
"""Prepare sampling args for synthetic data generation."""
|
||||
# Initialize sampling args
|
||||
sampling_args: dict[str, Any] = {}
|
||||
|
||||
# Apply sampling arguments, if specified
|
||||
if sampling_config.temperature is not None:
|
||||
sampling_args["temperature"] = sampling_config.temperature
|
||||
if sampling_config.max_tokens is not None:
|
||||
sampling_args["max_tokens"] = sampling_config.max_tokens
|
||||
if sampling_config.top_p is not None:
|
||||
sampling_args["top_p"] = sampling_config.top_p
|
||||
if sampling_config.reasoning_effort is not None:
|
||||
sampling_args["reasoning_effort"] = sampling_config.reasoning_effort
|
||||
|
||||
extra_body: dict[str, Any] = sampling_config.extra_body.copy()
|
||||
|
||||
# Apply vLLM-specific sampling arguments, if specified
|
||||
if sampling_config.top_k is not None:
|
||||
extra_body["top_k"] = sampling_config.top_k
|
||||
if sampling_config.min_p is not None:
|
||||
extra_body["min_p"] = sampling_config.min_p
|
||||
if sampling_config.min_tokens is not None:
|
||||
extra_body["min_tokens"] = sampling_config.min_tokens
|
||||
if sampling_config.repetition_penalty is not None:
|
||||
extra_body["repetition_penalty"] = sampling_config.repetition_penalty
|
||||
|
||||
sampling_args["extra_body"] = extra_body
|
||||
|
||||
return sampling_args
|
||||
|
||||
|
||||
# TODO: This is a hotfix for as long as verifiers doesn't support reasoning content parsing
|
||||
def merge_reasoning_content(
|
||||
completion: list[vf.ChatMessage],
|
||||
trajectory: list[vf.TrajectoryStep],
|
||||
reasoning_field: str = "reasoning_content",
|
||||
) -> list[vf.ChatMessage]:
|
||||
"""Parse reasoning content from the raw model response and add it to the completion."""
|
||||
# Parse responses from trajectory
|
||||
responses: list[vf.ModelResponse] = [trajectory_step["response"] for trajectory_step in trajectory]
|
||||
assistant_messages: list[vf.ChatMessage] = [c for c in completion if c.get("role") == "assistant"]
|
||||
assert len(assistant_messages) == len(responses), "Number of assistant messages and responses must match"
|
||||
|
||||
for assistant_message, response in zip(assistant_messages, responses):
|
||||
assert isinstance(response, vf.ChatCompletion)
|
||||
response_message = response.choices[0].message
|
||||
if getattr(response_message, reasoning_field, None) is not None:
|
||||
assistant_message[reasoning_field] = getattr(response_message, reasoning_field)
|
||||
|
||||
return completion
|
||||
|
||||
|
||||
# TODO: Move to verifiers to avoid code drift
|
||||
def make_result(state: vf.State, reasoning_field: str) -> dict:
|
||||
"""Translates a finished rollout state to a synthetic dataset row."""
|
||||
completion = merge_reasoning_content(state["completion"], state["trajectory"], reasoning_field)
|
||||
result_dict = {
|
||||
"example_id": state["example_id"],
|
||||
"prompt": state["prompt"],
|
||||
"completion": completion,
|
||||
"task": state["task"],
|
||||
"reward": state["reward"],
|
||||
"generation_ms": state["timing"]["generation_ms"],
|
||||
"scoring_ms": state["timing"]["scoring_ms"],
|
||||
"total_ms": state["timing"]["total_ms"],
|
||||
"info": state.get("info", {}),
|
||||
"answer": state.get("answer", ""),
|
||||
}
|
||||
for metric_name, metric_value in state["metrics"].items():
|
||||
result_dict[metric_name] = metric_value
|
||||
|
||||
result_dict["oai_tools"] = json.dumps(state.get("oai_tools", []))
|
||||
|
||||
return result_dict
|
||||
|
||||
|
||||
async def save_result(result_dict: dict, save_file: Path):
|
||||
"""Saves a finished rollout to a file."""
|
||||
async with WRITE_LOCK:
|
||||
async with aiofiles.open(save_file, "a") as f:
|
||||
await f.write(json.dumps(result_dict) + "\n")
|
||||
|
||||
|
||||
async def make_and_save_result(state: vf.State, save_file: Path, reasoning_field: str):
|
||||
"""Translates and saves a finished rollout state to a synthetic dataset row."""
|
||||
result_dict = await asyncio.to_thread(make_result, state, reasoning_field)
|
||||
await save_result(result_dict, save_file)
|
||||
|
||||
|
||||
async def generate_and_save_group(
|
||||
client: AsyncOpenAI,
|
||||
env: vf.Environment,
|
||||
model_name: str,
|
||||
example: dict,
|
||||
index: int,
|
||||
rollouts_per_example: int,
|
||||
sampling_args: dict,
|
||||
save_file: Path,
|
||||
reasoning_field: str,
|
||||
pbar: ProgressTracker,
|
||||
) -> None:
|
||||
logger = get_logger()
|
||||
try:
|
||||
states = await generate_group(client, env, model_name, example, rollouts_per_example, sampling_args)
|
||||
await asyncio.gather(*[make_and_save_result(state, save_file, reasoning_field) for state in states])
|
||||
pbar.update(rollouts_per_example)
|
||||
except Exception as e:
|
||||
logger.error(f"Error generating synthetic data for group {index}: {repr(e)}")
|
||||
|
||||
|
||||
async def generate_synthetic_data(
|
||||
clients: list[AsyncOpenAI],
|
||||
env_id: str,
|
||||
env_name: str | None,
|
||||
env_args: dict,
|
||||
num_examples: int,
|
||||
rollouts_per_example: int,
|
||||
skip_first: int,
|
||||
reasoning_field: str,
|
||||
output_dir: Path,
|
||||
model_config: ModelConfig,
|
||||
sampling_config: EvalSamplingConfig,
|
||||
client_config: ClientConfig,
|
||||
) -> None:
|
||||
"""Generates synthetic data for an environment."""
|
||||
# Get the logger
|
||||
logger = get_logger()
|
||||
|
||||
# Load the environment
|
||||
env_name_or_id = env_name or env_id
|
||||
env = load_environment(strip_env_version(env_id), **env_args)
|
||||
try:
|
||||
dataset = env.get_dataset(n=num_examples + skip_first)
|
||||
except ValueError:
|
||||
logger.warning(f"Could not find a training dataset for {env_name_or_id}. Falling back to eval dataset.")
|
||||
dataset = env.get_eval_dataset(n=num_examples + skip_first)
|
||||
if skip_first > 0:
|
||||
dataset = dataset.skip(skip_first)
|
||||
sampling_args = prepare_sampling_args(sampling_config, client_config)
|
||||
path_to_save = get_results_path(env_name_or_id, model_config.name, base_path=output_dir) / "results.jsonl"
|
||||
path_to_save.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
logger.info(
|
||||
f"Generating synthetic data for {env_name_or_id} (num_examples={len(dataset)}, {rollouts_per_example=}) {'with default args' if env_args == {} else f'with args {env_args}'}"
|
||||
)
|
||||
|
||||
total_rollouts = len(dataset) * rollouts_per_example
|
||||
pbar = ProgressTracker(total=total_rollouts, desc="Generating synthetic data")
|
||||
|
||||
await asyncio.gather(
|
||||
*[
|
||||
generate_and_save_group(
|
||||
client,
|
||||
env,
|
||||
model_config.name,
|
||||
example,
|
||||
index,
|
||||
rollouts_per_example,
|
||||
sampling_args,
|
||||
path_to_save,
|
||||
reasoning_field,
|
||||
pbar,
|
||||
)
|
||||
for index, (client, example) in enumerate(zip(cycle(clients), dataset.to_list()))
|
||||
]
|
||||
)
|
||||
|
||||
logger.info(f"Synthetic data generated for {env_name_or_id} and saved to {path_to_save}")
|
||||
@@ -2,13 +2,14 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from itertools import cycle
|
||||
from pathlib import Path
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
import httpx
|
||||
import verifiers as vf
|
||||
from httpx import AsyncClient
|
||||
from openai import AsyncOpenAI, NotFoundError
|
||||
from prime_evals import AsyncEvalsClient
|
||||
from openai import NotFoundError
|
||||
from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential
|
||||
|
||||
from prime_rl.utils.config import ClientConfig
|
||||
@@ -20,7 +21,7 @@ class InferencePool(Protocol):
|
||||
"""Protocol for inference pools (static or elastic)."""
|
||||
|
||||
@property
|
||||
def clients(self) -> list[AsyncOpenAI]:
|
||||
def clients(self) -> list[vf.ClientConfig]:
|
||||
"""Get inference clients."""
|
||||
...
|
||||
|
||||
@@ -29,6 +30,14 @@ class InferencePool(Protocol):
|
||||
"""Get admin clients."""
|
||||
...
|
||||
|
||||
def update_model_name(self, model_name: str) -> None:
|
||||
"""Update the model name."""
|
||||
...
|
||||
|
||||
async def get_next_client(self) -> vf.ClientConfig:
|
||||
"""Get next client in round-robin fashion."""
|
||||
...
|
||||
|
||||
async def wait_for_ready(self, model_name: str, timeout: int = 1800) -> None:
|
||||
"""Wait for inference pool to be ready."""
|
||||
...
|
||||
@@ -49,22 +58,33 @@ class InferencePool(Protocol):
|
||||
class StaticInferencePool:
|
||||
"""Static inference pool with fixed client list."""
|
||||
|
||||
def __init__(self, clients: list[AsyncOpenAI], admin_clients: list[AsyncClient], skip_model_check: bool = False):
|
||||
def __init__(
|
||||
self, clients: list[vf.ClientConfig], admin_clients: list[AsyncClient], skip_model_check: bool = False
|
||||
):
|
||||
self._clients = clients
|
||||
self._admin_clients = admin_clients
|
||||
self._skip_model_check = skip_model_check
|
||||
self._idx_to_client = {client.client_idx: client for client in clients}
|
||||
self._client_cycle = cycle(clients)
|
||||
self.model_name = None # unused
|
||||
|
||||
@property
|
||||
def clients(self) -> list[AsyncOpenAI]:
|
||||
def clients(self) -> list[vf.ClientConfig]:
|
||||
return self._clients
|
||||
|
||||
@property
|
||||
def admin_clients(self) -> list[AsyncClient]:
|
||||
return self._admin_clients
|
||||
|
||||
def update_model_name(self, model_name: str) -> None:
|
||||
self.model_name = model_name
|
||||
|
||||
async def get_next_client(self) -> vf.ClientConfig:
|
||||
return next(self._client_cycle)
|
||||
|
||||
async def wait_for_ready(self, model_name: str, timeout: int = 1800) -> None:
|
||||
await check_health(self._admin_clients, timeout=timeout)
|
||||
await maybe_check_has_model(self._clients, model_name, skip_model_check=self._skip_model_check)
|
||||
await maybe_check_has_model(self._admin_clients, model_name, skip_model_check=self._skip_model_check)
|
||||
|
||||
async def update_weights(self, weight_dir: Path | None, lora_name: str | None = None, step: int = 0) -> None:
|
||||
await update_weights(self._admin_clients, weight_dir, lora_name=lora_name, step=step)
|
||||
@@ -76,14 +96,14 @@ class StaticInferencePool:
|
||||
pass
|
||||
|
||||
|
||||
async def setup_inference_pool(client_config: ClientConfig, base_model: str | None = None) -> InferencePool:
|
||||
async def setup_inference_pool(client_config: ClientConfig, model_name: str) -> InferencePool:
|
||||
"""Create an inference pool from config (static or elastic)."""
|
||||
logger = get_logger()
|
||||
|
||||
if client_config.is_elastic:
|
||||
from prime_rl.utils.elastic import ElasticInferencePool
|
||||
|
||||
return await ElasticInferencePool.from_config(client_config, base_model=base_model)
|
||||
return await ElasticInferencePool.from_config(client_config, model_name=model_name)
|
||||
|
||||
logger.info(
|
||||
f"Initializing OpenAI client (base_url={', '.join(client_config.base_url)}, "
|
||||
@@ -96,28 +116,20 @@ async def setup_inference_pool(client_config: ClientConfig, base_model: str | No
|
||||
)
|
||||
|
||||
|
||||
def setup_clients(client_config: ClientConfig) -> list[AsyncOpenAI]:
|
||||
def _setup_client(base_url: str) -> AsyncOpenAI:
|
||||
# We use a longer request timeout than default, but if more than 20min, we probably need faster inference deployment
|
||||
timeout = httpx.Timeout(client_config.timeout)
|
||||
# We use as many concurrent connections as possible, but lower than available ports
|
||||
limits = httpx.Limits(
|
||||
max_connections=8192, # OAI default: 1000
|
||||
max_keepalive_connections=8192, # OAI default: 100
|
||||
)
|
||||
http_client = httpx.AsyncClient(limits=limits, timeout=timeout, headers=client_config.headers)
|
||||
return AsyncOpenAI(
|
||||
base_url=base_url,
|
||||
api_key=os.getenv(client_config.api_key_var, "EMPTY"),
|
||||
max_retries=10, # OAI default: 2 (does exponential backoff and reasonable timeout in between retries)
|
||||
http_client=http_client,
|
||||
def setup_clients(client_config: ClientConfig) -> list[vf.ClientConfig]:
|
||||
def _setup_client(client_idx: int, base_url: str) -> vf.ClientConfig:
|
||||
return vf.ClientConfig(
|
||||
client_idx=client_idx,
|
||||
api_base_url=base_url,
|
||||
api_key_var=client_config.api_key_var,
|
||||
timeout=client_config.timeout,
|
||||
max_connections=8192,
|
||||
max_keepalive_connections=8192,
|
||||
max_retries=10,
|
||||
extra_headers=client_config.headers,
|
||||
)
|
||||
|
||||
return [_setup_client(base_url) for base_url in client_config.base_url]
|
||||
|
||||
|
||||
def setup_evals_client() -> AsyncEvalsClient:
|
||||
return AsyncEvalsClient()
|
||||
return [_setup_client(client_idx, base_url) for client_idx, base_url in enumerate(client_config.base_url)]
|
||||
|
||||
|
||||
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
@@ -145,16 +157,18 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
return [_setup_admin_client(base_url) for base_url in client_config.base_url]
|
||||
|
||||
|
||||
async def maybe_check_has_model(clients: list[AsyncOpenAI], model_name: str, skip_model_check: bool = False) -> None:
|
||||
async def maybe_check_has_model(
|
||||
admin_clients: list[AsyncClient], model_name: str, skip_model_check: bool = False
|
||||
) -> None:
|
||||
if skip_model_check:
|
||||
return
|
||||
logger = get_logger()
|
||||
logger.debug(f"Checking if model {model_name} is in the inference pool")
|
||||
results = await asyncio.gather(*[client.models.list() for client in clients])
|
||||
for client, result in zip(clients, results):
|
||||
models = result.data
|
||||
if not any(model.id == model_name for model in models):
|
||||
raise ValueError(f"Model {model_name} was not found in the inference pool on {client.base_url}")
|
||||
results = await asyncio.gather(*[admin_client.get("/v1/models") for admin_client in admin_clients])
|
||||
for admin_client, result in zip(admin_clients, results):
|
||||
models = result.json()["data"]
|
||||
if not any(model["id"] == model_name for model in models):
|
||||
raise ValueError(f"Model {model_name} was not found in the inference pool on {admin_client.base_url}")
|
||||
logger.debug(f"Model {model_name} was found in the inference pool")
|
||||
|
||||
|
||||
|
||||
+32
-118
@@ -16,8 +16,8 @@ from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
import verifiers as vf
|
||||
from httpx import AsyncClient
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from prime_rl.utils.client import load_lora_adapter, setup_admin_clients, setup_clients
|
||||
from prime_rl.utils.config import ClientConfig
|
||||
@@ -62,7 +62,7 @@ async def discover_ready_servers(hostname: str, port: int, model_name: str) -> l
|
||||
|
||||
with_model = set()
|
||||
for ip, result in zip(ips, results):
|
||||
if isinstance(result, Exception):
|
||||
if isinstance(result, BaseException):
|
||||
continue
|
||||
has_model, _ = result
|
||||
if has_model:
|
||||
@@ -71,108 +71,6 @@ async def discover_ready_servers(hostname: str, port: int, model_name: str) -> l
|
||||
return sorted(with_model)
|
||||
|
||||
|
||||
# --- ServerDiscovery: for env workers ---
|
||||
|
||||
|
||||
class ServerDiscovery:
|
||||
"""DNS-based server discovery for env workers.
|
||||
|
||||
Discovers servers via DNS, checks if they have the model, provides clients.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hostname: str,
|
||||
port: int,
|
||||
model_name: str,
|
||||
client_config: ClientConfig,
|
||||
sync_interval: float = 5.0,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.hostname = hostname
|
||||
self.port = port
|
||||
self.model_name = model_name
|
||||
self.client_config = client_config
|
||||
self.sync_interval = sync_interval
|
||||
|
||||
self._clients: list[AsyncOpenAI] = []
|
||||
self._urls: list[str] = []
|
||||
self._client_index = 0
|
||||
self._last_refresh = 0.0
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config: ClientConfig, model_name: str) -> ServerDiscovery:
|
||||
return cls(
|
||||
hostname=config.elastic.hostname,
|
||||
port=config.elastic.port,
|
||||
model_name=model_name,
|
||||
client_config=config,
|
||||
sync_interval=config.elastic.sync_interval,
|
||||
)
|
||||
|
||||
@property
|
||||
def has_clients(self) -> bool:
|
||||
return len(self._clients) > 0
|
||||
|
||||
@property
|
||||
def clients(self) -> list[AsyncOpenAI]:
|
||||
"""Get the current list of clients."""
|
||||
return self._clients
|
||||
|
||||
def get_next_client(self) -> AsyncOpenAI | None:
|
||||
"""Get next client in round-robin fashion."""
|
||||
if not self._clients:
|
||||
return None
|
||||
client = self._clients[self._client_index % len(self._clients)]
|
||||
self._client_index += 1
|
||||
return client
|
||||
|
||||
async def refresh(self) -> bool:
|
||||
"""Refresh clients via DNS discovery. Rate-limited by sync_interval."""
|
||||
if time.time() - self._last_refresh < self.sync_interval:
|
||||
return False
|
||||
self._last_refresh = time.time()
|
||||
|
||||
urls = await discover_ready_servers(self.hostname, self.port, self.model_name)
|
||||
if set(urls) == set(self._urls):
|
||||
return False
|
||||
|
||||
self._urls = urls
|
||||
if urls:
|
||||
self.logger.debug(f"Discovered {len(urls)} ready server(s)")
|
||||
self._clients = setup_clients(
|
||||
ClientConfig(
|
||||
timeout=self.client_config.timeout,
|
||||
base_url=urls,
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
)
|
||||
)
|
||||
else:
|
||||
self.logger.debug("No ready inference servers found")
|
||||
self._clients = []
|
||||
self._client_index = 0
|
||||
return True
|
||||
|
||||
async def wait_for_clients(self) -> list[AsyncOpenAI]:
|
||||
"""Wait for clients to be available and return them."""
|
||||
while not self.has_clients:
|
||||
await self.refresh()
|
||||
if not self.has_clients:
|
||||
self.logger.debug(f"Waiting for inference servers with model {self.model_name}...")
|
||||
await asyncio.sleep(self.sync_interval)
|
||||
|
||||
return self._clients
|
||||
|
||||
async def stop(self) -> None:
|
||||
for client in self._clients:
|
||||
await client.close()
|
||||
self._clients = []
|
||||
|
||||
|
||||
# --- ElasticInferencePool: for orchestrator ---
|
||||
|
||||
|
||||
@dataclass
|
||||
class AdapterState:
|
||||
"""State of a LoRA adapter (loaded or desired)."""
|
||||
@@ -206,14 +104,15 @@ class ElasticInferencePool:
|
||||
self,
|
||||
hostname: str,
|
||||
client_config: ClientConfig,
|
||||
base_model: str | None = None,
|
||||
model_name: str,
|
||||
port: int = 8000,
|
||||
sync_interval: float = 5.0,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.hostname = hostname
|
||||
self.client_config = client_config
|
||||
self.base_model = base_model
|
||||
self.model_name = model_name
|
||||
self.base_model_name = model_name # Keep original for health checks
|
||||
self.port = port
|
||||
self.sync_interval = sync_interval
|
||||
|
||||
@@ -222,24 +121,30 @@ class ElasticInferencePool:
|
||||
self._lock = asyncio.Lock()
|
||||
self._desired: AdapterState = AdapterState()
|
||||
|
||||
self._clients: list[AsyncOpenAI] = []
|
||||
self._clients: list[vf.ClientConfig] = []
|
||||
self._client_urls: list[str] = []
|
||||
self._client_index = 0
|
||||
|
||||
self._sync_task: asyncio.Task | None = None
|
||||
self._started = False
|
||||
|
||||
@classmethod
|
||||
async def from_config(cls, config: ClientConfig, base_model: str | None = None) -> ElasticInferencePool:
|
||||
async def from_config(cls, config: ClientConfig, model_name: str) -> ElasticInferencePool:
|
||||
if config.elastic is None:
|
||||
raise ValueError("Elastic inference pool requires elastic config")
|
||||
pool = cls(
|
||||
hostname=config.elastic.hostname,
|
||||
client_config=config,
|
||||
base_model=base_model,
|
||||
model_name=model_name,
|
||||
port=config.elastic.port,
|
||||
sync_interval=config.elastic.sync_interval,
|
||||
)
|
||||
await pool.start()
|
||||
return pool
|
||||
|
||||
def update_model_name(self, model_name: str) -> None:
|
||||
self.model_name = model_name
|
||||
|
||||
def _build_url(self, ip: str) -> str:
|
||||
return f"http://{ip}:{self.port}"
|
||||
|
||||
@@ -251,10 +156,11 @@ class ElasticInferencePool:
|
||||
return [self._build_inference_url(ip) for ip, s in self._servers.items() if s.status == "ready"]
|
||||
|
||||
@property
|
||||
def clients(self) -> list[AsyncOpenAI]:
|
||||
def clients(self) -> list[vf.ClientConfig]:
|
||||
urls = self.ready_urls
|
||||
if set(urls) != set(self._client_urls):
|
||||
self._client_urls = urls
|
||||
self._client_index = 0
|
||||
self._clients = (
|
||||
setup_clients(
|
||||
ClientConfig(
|
||||
@@ -269,6 +175,18 @@ class ElasticInferencePool:
|
||||
)
|
||||
return self._clients
|
||||
|
||||
@property
|
||||
def has_clients(self) -> bool:
|
||||
return len(self.clients) > 0
|
||||
|
||||
async def get_next_client(self) -> vf.ClientConfig:
|
||||
"""Get next client in round-robin fashion."""
|
||||
while not self.has_clients:
|
||||
await asyncio.sleep(self.sync_interval)
|
||||
client = self._clients[self._client_index % len(self._clients)]
|
||||
self._client_index += 1
|
||||
return client
|
||||
|
||||
@property
|
||||
def admin_clients(self) -> list[AsyncClient]:
|
||||
return list(self._admin_clients.values())
|
||||
@@ -310,7 +228,7 @@ class ElasticInferencePool:
|
||||
continue
|
||||
elif not parent:
|
||||
continue
|
||||
elif self.base_model is not None and parent != self.base_model:
|
||||
elif parent != self.model_name:
|
||||
continue
|
||||
|
||||
root = model.get("root", "")
|
||||
@@ -406,8 +324,8 @@ class ElasticInferencePool:
|
||||
data = response.json()
|
||||
models = [m.get("id") for m in data.get("data", [])]
|
||||
|
||||
if self.base_model is not None and self.base_model not in models:
|
||||
self.logger.debug(f"Server {ip} does not have base model {self.base_model}")
|
||||
if self.base_model_name not in models:
|
||||
self.logger.debug(f"Server {ip} does not have base model {self.base_model_name}")
|
||||
return False
|
||||
except Exception as e:
|
||||
self.logger.debug(f"Server {ip} model check failed: {e}")
|
||||
@@ -502,15 +420,11 @@ class ElasticInferencePool:
|
||||
for ip in list(self._servers.keys()):
|
||||
await self._remove_server(ip)
|
||||
|
||||
# Close inference clients (admin clients are closed in _remove_server)
|
||||
for client in self._clients:
|
||||
await client.close()
|
||||
self._clients = []
|
||||
self._client_urls = []
|
||||
|
||||
self._started = False
|
||||
|
||||
async def sync_weights(self, weights_path: Path, lora_name: str | None = None, step: int = 0) -> None:
|
||||
async def sync_weights(self, weights_path: Path | None, lora_name: str | None = None, step: int = 0) -> None:
|
||||
async with self._lock:
|
||||
self._desired = AdapterState(
|
||||
name=lora_name,
|
||||
|
||||
@@ -79,8 +79,12 @@ class _JsonFileSink:
|
||||
self._file.flush()
|
||||
|
||||
|
||||
class _VerifiersInterceptHandler(logging.Handler):
|
||||
"""Intercept stdlib logging from verifiers and route to loguru with [verifiers] prefix."""
|
||||
class InterceptHandler(logging.Handler):
|
||||
"""Intercept standard logging library and routes to our prime-rl logger with specified prefix."""
|
||||
|
||||
def __init__(self, prefix: str):
|
||||
super().__init__()
|
||||
self.prefix = prefix
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
logger = get_logger()
|
||||
@@ -94,7 +98,7 @@ class _VerifiersInterceptHandler(logging.Handler):
|
||||
frame = frame.f_back
|
||||
depth += 1
|
||||
|
||||
logger.opt(depth=depth, exception=record.exc_info).log(level, f"[verifiers] {record.getMessage()}")
|
||||
logger.opt(depth=depth, exception=record.exc_info).log(level, f"[{self.prefix}] {record.getMessage()}")
|
||||
|
||||
|
||||
def setup_logger(
|
||||
@@ -260,12 +264,3 @@ class ProgressTracker:
|
||||
percent = int(100 * self.current / self.total)
|
||||
if percent > self._last_logged_percent:
|
||||
self._emit_progress(percent)
|
||||
|
||||
|
||||
def intercept_verifiers_logging(level: str = "DEBUG"):
|
||||
"""Intercept all verifiers stdlib logging and route through prime-rl loguru with [verifiers] prefix."""
|
||||
vf_logger = logging.getLogger("verifiers")
|
||||
vf_logger.handlers.clear()
|
||||
vf_logger.addHandler(_VerifiersInterceptHandler())
|
||||
vf_logger.setLevel(level.upper())
|
||||
vf_logger.propagate = False
|
||||
|
||||
@@ -16,7 +16,7 @@ class Monitor(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def log_samples(self, rollouts: list[vf.State], step: int) -> None:
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -45,7 +45,7 @@ class NoOpMonitor(Monitor):
|
||||
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
|
||||
self.history.append(metrics)
|
||||
|
||||
def log_samples(self, rollouts: list[vf.State], step: int) -> None:
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
pass
|
||||
|
||||
def log_final_samples(self) -> None:
|
||||
|
||||
@@ -26,7 +26,7 @@ class MultiMonitor(Monitor):
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to log metrics to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def log_samples(self, rollouts: list[vf.State], step: int) -> None:
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
monitor.log_samples(rollouts=rollouts, step=step)
|
||||
|
||||
@@ -92,7 +92,7 @@ class PrimeMonitor(Monitor):
|
||||
},
|
||||
)
|
||||
|
||||
def log_samples(self, rollouts: list[vf.State], step: int) -> None:
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
"""Logs rollouts to Prime Intellect API."""
|
||||
if not self.is_master:
|
||||
return
|
||||
|
||||
@@ -79,7 +79,7 @@ class WandbMonitor(Monitor):
|
||||
return
|
||||
wandb.log(metrics, step=step)
|
||||
|
||||
def log_samples(self, rollouts: list[vf.State], step: int) -> None:
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
"""Logs rollouts to W&B table."""
|
||||
if not self.is_master:
|
||||
return
|
||||
|
||||
@@ -29,10 +29,6 @@ def get_broadcast_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "broadcasts"
|
||||
|
||||
|
||||
def get_env_worker_log_file(output_dir: Path, env_name: str) -> Path:
|
||||
return output_dir / "logs" / "env_workers" / f"{env_name}.log"
|
||||
|
||||
|
||||
def get_step_path(path: Path, step: int) -> Path:
|
||||
return path / f"step_{step}"
|
||||
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
import asyncio
|
||||
from itertools import cycle
|
||||
from typing import Any, cast
|
||||
|
||||
import verifiers as vf
|
||||
from openai import AsyncOpenAI
|
||||
from openai.types.chat.chat_completion import ChatCompletion
|
||||
|
||||
from prime_rl.utils.logger import ProgressTracker
|
||||
|
||||
|
||||
async def generate_group(
|
||||
client: AsyncOpenAI,
|
||||
env: vf.Environment,
|
||||
model_name: str,
|
||||
example: dict,
|
||||
rollouts_per_example: int,
|
||||
sampling_args: dict,
|
||||
max_retries: int = 0,
|
||||
state_columns: list[str] = ["trajectory"],
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""Asynchronously generate and score rollouts for a single group."""
|
||||
group_inputs = [vf.RolloutInput(**example) for _ in range(rollouts_per_example)]
|
||||
return await env.run_group(
|
||||
group_inputs=group_inputs,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=sampling_args,
|
||||
max_retries=max_retries,
|
||||
state_columns=state_columns,
|
||||
)
|
||||
|
||||
|
||||
async def generate_rollout(
|
||||
client: AsyncOpenAI,
|
||||
env: vf.Environment,
|
||||
model_name: str,
|
||||
example: dict,
|
||||
sampling_args: dict,
|
||||
max_retries: int = 0,
|
||||
state_columns: list[str] = ["trajectory"],
|
||||
) -> vf.RolloutOutput:
|
||||
"""Asynchronously generate and score a single rollout."""
|
||||
rollout_input = vf.RolloutInput(**example)
|
||||
return await env.run_rollout(
|
||||
rollout_input, client, model_name, sampling_args, max_retries=max_retries, state_columns=state_columns
|
||||
)
|
||||
|
||||
|
||||
async def generate_batch(
|
||||
clients: list[AsyncOpenAI],
|
||||
env: vf.Environment,
|
||||
model_name: str,
|
||||
examples: list[dict],
|
||||
rollouts_per_example: int,
|
||||
sampling_args: dict,
|
||||
pbar_description: str = "Generating rollouts",
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""Asynchronously generate and score rollouts for a list of groups (batch)."""
|
||||
|
||||
total_rollouts = len(examples) * rollouts_per_example
|
||||
pbar = ProgressTracker(total=total_rollouts, desc=pbar_description)
|
||||
|
||||
async def generate_group_with_progress(client, example):
|
||||
"""Generate rollouts for one problem and update progress."""
|
||||
result = await generate_group(client, env, model_name, example, rollouts_per_example, sampling_args)
|
||||
pbar.update(rollouts_per_example)
|
||||
return result
|
||||
|
||||
try:
|
||||
group_outputs_list: list[list[vf.RolloutOutput]] = await asyncio.gather(
|
||||
*[generate_group_with_progress(client, example) for client, example in zip(cycle(clients), examples)]
|
||||
)
|
||||
finally:
|
||||
pbar.close()
|
||||
|
||||
return [output for group_outputs in group_outputs_list for output in group_outputs]
|
||||
|
||||
|
||||
def get_prompt_len(state: vf.State) -> int:
|
||||
"""Compute the number of prompt tokens from vf.State. Defined as the number of prompt IDs from the first trajectory step. If raw tokens are not available, falls back to checking the usage of the first response."""
|
||||
if not state["trajectory"]:
|
||||
return 0
|
||||
first_step = state["trajectory"][0]
|
||||
if first_step["tokens"] is not None:
|
||||
return len(first_step["tokens"]["prompt_ids"])
|
||||
first_step_response = cast(ChatCompletion, first_step["response"])
|
||||
return getattr(first_step_response.usage, "prompt_tokens", 0)
|
||||
|
||||
|
||||
def get_seq_len(state: vf.State) -> int:
|
||||
"""Compute the number of tokens from vf.State. Defined as the sum of prompt and completion tokens from the last trajectory step. If raw tokens are not available, falls back to checking the usage of the last response."""
|
||||
if not state["trajectory"]:
|
||||
return 0
|
||||
last_step = state["trajectory"][-1]
|
||||
if last_step["tokens"] is not None:
|
||||
return len(last_step["tokens"]["prompt_ids"]) + len(last_step["tokens"]["completion_ids"])
|
||||
last_step_response = cast(ChatCompletion, last_step["response"])
|
||||
return getattr(last_step_response.usage, "total_tokens", 0)
|
||||
|
||||
|
||||
def get_completion_len(state: vf.State) -> int:
|
||||
"""Compute the number of completion tokens from vf.State. Defined as the difference between the total number of tokens and the number of prompt tokens."""
|
||||
return get_seq_len(state) - get_prompt_len(state)
|
||||
|
||||
|
||||
def get_is_truncated(state: vf.State) -> bool:
|
||||
"""Check if the rollout is truncated. If raw tokens are not available, falls back to checking the finish reason of the last response."""
|
||||
if not state["trajectory"]:
|
||||
return False
|
||||
last_step = state["trajectory"][-1]
|
||||
if last_step["tokens"] is not None:
|
||||
return last_step["tokens"]["is_truncated"]
|
||||
last_step_response = cast(ChatCompletion, last_step["response"])
|
||||
return last_step_response.choices[0].finish_reason == "length"
|
||||
|
||||
|
||||
def to_serializable_trajectory_step(step: vf.TrajectoryStep) -> dict:
|
||||
"""Returns a serializable version of vf.TrajectoryStep."""
|
||||
serializable_trajectory_step = cast(dict, step.copy())
|
||||
if "response" in step and isinstance(step["response"], ChatCompletion):
|
||||
serializable_trajectory_step["response"] = step["response"].model_dump()
|
||||
return serializable_trajectory_step
|
||||
|
||||
|
||||
def from_serializable_trajectory_step(step: dict) -> vf.TrajectoryStep:
|
||||
"""Inverse of to_serializable_trajectory_step."""
|
||||
deserialized_trajectory_step = vf.TrajectoryStep(**step)
|
||||
if "response" in step and isinstance(step["response"], dict):
|
||||
deserialized_trajectory_step["response"] = ChatCompletion.model_validate(step["response"])
|
||||
return deserialized_trajectory_step
|
||||
|
||||
|
||||
def to_serializable_state(state: vf.State) -> dict:
|
||||
"""Returns a serializable copy of vf.State."""
|
||||
serializable_state = cast(dict, state.copy())
|
||||
|
||||
# Flatten input fields to top level for serialization
|
||||
# This is necessary because the dict object cannot forward access to input fields anymore, e.g. state["prompt"] will automatically forward to state["input"]["prompt"] in vf.State but not in dict. We solve this by populating the inputs into the top-level explicitly
|
||||
if "input" in state:
|
||||
input_dict = serializable_state.pop("input")
|
||||
for field in vf.State.INPUT_FIELDS:
|
||||
if field in input_dict:
|
||||
serializable_state[field] = input_dict[field]
|
||||
|
||||
if "trajectory" in state:
|
||||
serializable_state["trajectory"] = [to_serializable_trajectory_step(step) for step in state["trajectory"]]
|
||||
|
||||
return serializable_state
|
||||
|
||||
|
||||
def from_serializable_state(serializable_state: dict) -> vf.State:
|
||||
"""Inverse of to_serializable_state."""
|
||||
# Extract input fields from top level and reconstruct input dict
|
||||
input_dict: dict[str, Any] = {}
|
||||
for field in vf.State.INPUT_FIELDS:
|
||||
if field in serializable_state:
|
||||
input_dict[field] = serializable_state.pop(field)
|
||||
|
||||
if input_dict:
|
||||
serializable_state["input"] = input_dict
|
||||
|
||||
state = vf.State(**serializable_state)
|
||||
|
||||
if "trajectory" in state:
|
||||
state["trajectory"] = [from_serializable_trajectory_step(step) for step in state["trajectory"]]
|
||||
|
||||
return state
|
||||
@@ -1,56 +0,0 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import Command, Environment, ProcessResult
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.slow,
|
||||
pytest.mark.skipif(not os.environ.get("OPENAI_API_KEY"), reason="OPENAI_API_KEY not set"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
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, {})
|
||||
|
||||
|
||||
@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,85 +0,0 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import Command, Environment, ProcessResult
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.slow,
|
||||
pytest.mark.skipif(not os.environ.get("OPENAI_API_KEY"), reason="OPENAI_API_KEY not set"),
|
||||
]
|
||||
|
||||
|
||||
@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})"
|
||||
)
|
||||
@@ -51,19 +51,17 @@ def dummy_env_group(mock_openai_client, dummy_dataset) -> vf.EnvGroup:
|
||||
|
||||
@pytest.fixture
|
||||
def make_rollouts():
|
||||
def _make_rollouts(dataset: Dataset, rewards: list[float]) -> list[vf.State]:
|
||||
rollouts = []
|
||||
def _make_rollouts(dataset: Dataset, rewards: list[float]) -> list[vf.RolloutOutput]:
|
||||
all_rollouts = []
|
||||
for i, reward in enumerate(rewards):
|
||||
task = dataset[i]["task"]
|
||||
example_id = dataset[i]["example_id"]
|
||||
prompt = dataset[i]["prompt"]
|
||||
problem_rollouts = [
|
||||
vf.State(
|
||||
input=vf.RolloutInput(
|
||||
example_id=example_id,
|
||||
task=task,
|
||||
prompt=prompt,
|
||||
),
|
||||
rollouts = [
|
||||
vf.RolloutOutput(
|
||||
example_id=example_id,
|
||||
task=task,
|
||||
prompt=prompt,
|
||||
prompt_ids=[0],
|
||||
prompt_mask=[1],
|
||||
completion_ids=[1],
|
||||
@@ -75,8 +73,8 @@ def make_rollouts():
|
||||
metrics={},
|
||||
)
|
||||
] * 2
|
||||
rollouts.extend(problem_rollouts)
|
||||
return rollouts
|
||||
all_rollouts.extend(rollouts)
|
||||
return all_rollouts
|
||||
|
||||
return _make_rollouts
|
||||
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
"""Tests for EnvWorker auto-restart functionality."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import signal
|
||||
import time
|
||||
from multiprocessing import Process, Queue
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from prime_rl.orchestrator.env_worker import EnvWorker, WorkerDiedError
|
||||
|
||||
|
||||
def dummy_worker_main(request_queue: Queue, response_queue: Queue, **kwargs):
|
||||
"""A minimal worker that just sleeps until killed."""
|
||||
while True:
|
||||
try:
|
||||
request = request_queue.get(timeout=0.1)
|
||||
if request is None:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_client_config():
|
||||
"""Create a mock client config."""
|
||||
config = MagicMock()
|
||||
config.model_dump.return_value = {}
|
||||
return config
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env_worker(mock_client_config):
|
||||
"""Create an EnvWorker with mocked dependencies."""
|
||||
worker = EnvWorker(
|
||||
env_id="test_env",
|
||||
env_args={},
|
||||
client_config=mock_client_config,
|
||||
model_name="test-model",
|
||||
seq_len=1024,
|
||||
interleaved_rollouts=True,
|
||||
max_concurrent_groups=1,
|
||||
tasks_per_minute=60,
|
||||
example_lookup={},
|
||||
worker_name="test_worker",
|
||||
)
|
||||
return worker
|
||||
|
||||
|
||||
def test_restart_drains_queues(env_worker):
|
||||
"""Test that restart() drains any stale data from queues."""
|
||||
# Put some data in the queues
|
||||
env_worker.request_queue.put("stale_request")
|
||||
env_worker.response_queue.put("stale_response")
|
||||
|
||||
with patch.object(env_worker, "start"):
|
||||
env_worker._restart()
|
||||
|
||||
# Queues should be empty after restart
|
||||
assert env_worker.request_queue.empty()
|
||||
assert env_worker.response_queue.empty()
|
||||
|
||||
|
||||
def test_pending_count_returns_large_when_dead(env_worker):
|
||||
"""Test that pending_count returns large number when worker is dead."""
|
||||
env_worker._dead = False
|
||||
env_worker.pending_futures = {"a": None, "b": None}
|
||||
assert env_worker.pending_count == 2
|
||||
|
||||
env_worker._dead = True
|
||||
assert env_worker.pending_count == 999999
|
||||
|
||||
|
||||
def test_collect_responses_restarts_on_worker_death(env_worker):
|
||||
"""Test that collect_responses auto-restarts worker when it dies."""
|
||||
|
||||
async def run_test():
|
||||
# Create a real process that we can kill
|
||||
env_worker.process = Process(
|
||||
target=dummy_worker_main,
|
||||
args=(env_worker.request_queue, env_worker.response_queue),
|
||||
daemon=True,
|
||||
)
|
||||
env_worker.process.start()
|
||||
env_worker._stopping = False
|
||||
env_worker._dead = False
|
||||
|
||||
# Add a pending future that should be failed
|
||||
loop = asyncio.get_event_loop()
|
||||
pending_future = loop.create_future()
|
||||
env_worker.pending_futures["test_request"] = pending_future
|
||||
|
||||
# Start collect_responses in background
|
||||
# Use side_effect to actually restart the process so the loop doesn't spin
|
||||
def real_restart():
|
||||
env_worker.process = Process(
|
||||
target=dummy_worker_main,
|
||||
args=(env_worker.request_queue, env_worker.response_queue),
|
||||
daemon=True,
|
||||
)
|
||||
env_worker.process.start()
|
||||
env_worker._dead = False
|
||||
|
||||
with patch.object(env_worker, "_restart", side_effect=real_restart) as mock_restart:
|
||||
collect_task = asyncio.create_task(env_worker.collect_responses())
|
||||
|
||||
# Give it a moment to start
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
# Kill the worker process
|
||||
os.kill(env_worker.process.pid, signal.SIGKILL)
|
||||
env_worker.process.join(timeout=1)
|
||||
|
||||
# Wait for collect_responses to detect death and restart
|
||||
await asyncio.sleep(0.2)
|
||||
|
||||
# Cancel the collect task
|
||||
collect_task.cancel()
|
||||
try:
|
||||
await collect_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
# Cleanup the restarted process
|
||||
if env_worker.process and env_worker.process.is_alive():
|
||||
env_worker.process.terminate()
|
||||
env_worker.process.join(timeout=1)
|
||||
|
||||
# Verify restart was called exactly once
|
||||
mock_restart.assert_called_once()
|
||||
|
||||
# Verify pending future was failed with WorkerDiedError
|
||||
assert pending_future.done()
|
||||
with pytest.raises(WorkerDiedError):
|
||||
pending_future.result()
|
||||
|
||||
asyncio.run(run_test())
|
||||
|
||||
|
||||
def test_update_model_name(env_worker):
|
||||
"""Test that update_model_name changes the model used for future requests."""
|
||||
assert env_worker.model_name == "test-model"
|
||||
|
||||
env_worker.update_model_name("new-lora-model")
|
||||
|
||||
assert env_worker.model_name == "new-lora-model"
|
||||
|
||||
|
||||
def test_submit_request_uses_current_model_name(env_worker):
|
||||
"""Test that submit_request uses the current model_name."""
|
||||
import asyncio
|
||||
|
||||
captured_requests = []
|
||||
|
||||
def capture_put(request):
|
||||
captured_requests.append(request)
|
||||
|
||||
async def run_test():
|
||||
# Mock the queue put to capture requests
|
||||
env_worker.request_queue.put = capture_put
|
||||
|
||||
# Initial model name
|
||||
future, request_id = await env_worker.submit_request(
|
||||
example_id=1, rollouts_per_example=1, sampling_args={"temperature": 1.0}
|
||||
)
|
||||
assert captured_requests[-1].model_name == "test-model"
|
||||
|
||||
# Update model name
|
||||
env_worker.update_model_name("lora-model")
|
||||
|
||||
# New request should use new model name
|
||||
future2, request_id2 = await env_worker.submit_request(
|
||||
example_id=1, rollouts_per_example=1, sampling_args={"temperature": 1.0}
|
||||
)
|
||||
assert captured_requests[-1].model_name == "lora-model"
|
||||
|
||||
asyncio.run(run_test())
|
||||
|
||||
|
||||
def test_full_restart_cycle(mock_client_config):
|
||||
"""Test a full restart cycle with actual process management."""
|
||||
worker = EnvWorker(
|
||||
env_id="test_env",
|
||||
env_args={},
|
||||
client_config=mock_client_config,
|
||||
model_name="test-model",
|
||||
seq_len=1024,
|
||||
interleaved_rollouts=True,
|
||||
max_concurrent_groups=1,
|
||||
tasks_per_minute=60,
|
||||
example_lookup={},
|
||||
worker_name="test_worker",
|
||||
)
|
||||
|
||||
# Patch worker_main to use our dummy
|
||||
with patch("prime_rl.orchestrator.env_worker.worker_main", dummy_worker_main):
|
||||
# Start worker
|
||||
worker.start()
|
||||
assert worker.process is not None
|
||||
assert worker.process.is_alive()
|
||||
original_pid = worker.process.pid
|
||||
|
||||
# Kill it
|
||||
os.kill(worker.process.pid, signal.SIGKILL)
|
||||
worker.process.join(timeout=1)
|
||||
assert not worker.process.is_alive()
|
||||
|
||||
# Restart
|
||||
worker._restart()
|
||||
assert worker.process is not None
|
||||
assert worker.process.is_alive()
|
||||
assert worker.process.pid != original_pid # New process
|
||||
assert not worker._dead
|
||||
|
||||
# Cleanup
|
||||
worker.stop()
|
||||
@@ -16,8 +16,9 @@ from prime_rl.orchestrator.trajectories import (
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def single_step_trajectory_state():
|
||||
state = vf.State(
|
||||
def single_step_trajectory_output():
|
||||
output = vf.RolloutOutput(
|
||||
example_id=0,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "U1"}],
|
||||
@@ -34,18 +35,21 @@ def single_step_trajectory_state():
|
||||
),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
)
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
return state
|
||||
return output
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def multi_step_trajectory_state():
|
||||
state = vf.State(
|
||||
def multi_step_trajectory_output():
|
||||
output = vf.RolloutOutput(
|
||||
example_id=0,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "U1"}],
|
||||
@@ -62,8 +66,9 @@ def multi_step_trajectory_state():
|
||||
),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
),
|
||||
vf.TrajectoryStep(
|
||||
prompt=[
|
||||
@@ -84,18 +89,21 @@ def multi_step_trajectory_state():
|
||||
),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
return state
|
||||
return output
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def multi_step_trajectory_with_tool_calls():
|
||||
state = vf.State(
|
||||
def multi_step_trajectory_with_tool_calls_output():
|
||||
output = vf.RolloutOutput(
|
||||
example_id=0,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "U1"}],
|
||||
@@ -112,8 +120,9 @@ def multi_step_trajectory_with_tool_calls():
|
||||
),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
),
|
||||
vf.TrajectoryStep(
|
||||
prompt=[
|
||||
@@ -134,17 +143,19 @@ def multi_step_trajectory_with_tool_calls():
|
||||
),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
),
|
||||
],
|
||||
reward=1.0,
|
||||
advantage=None,
|
||||
stop_condition=None,
|
||||
metrics={"has_error": 0.0, "tool_calls": 1.0},
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
return state
|
||||
return output
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -153,8 +164,8 @@ def multi_step_trajectory_extension_never_holds():
|
||||
2-step trajectory where extension NEVER holds (step 2 has completely different tokens).
|
||||
This simulates e.g. a chat template that re-renders the entire conversation differently.
|
||||
"""
|
||||
state = vf.State(
|
||||
input=vf.RolloutInput(messages=[], example_id="test-no-extension"),
|
||||
output = vf.RolloutOutput(
|
||||
example_id=0,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "U1"}],
|
||||
@@ -171,8 +182,9 @@ def multi_step_trajectory_extension_never_holds():
|
||||
),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
),
|
||||
vf.TrajectoryStep(
|
||||
prompt=[
|
||||
@@ -194,20 +206,22 @@ def multi_step_trajectory_extension_never_holds():
|
||||
),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
return state
|
||||
return output
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def multi_step_trajectory_with_tool_calls_extension_never_holds():
|
||||
"""2-step trajectory with tool calls where extension NEVER holds."""
|
||||
state = vf.State(
|
||||
input=vf.RolloutInput(messages=[], example_id="test-no-extension-tools"),
|
||||
output = vf.RolloutOutput(
|
||||
example_id=0,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "U1"}],
|
||||
@@ -225,7 +239,8 @@ def multi_step_trajectory_with_tool_calls_extension_never_holds():
|
||||
reward=None,
|
||||
advantage=None,
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
),
|
||||
vf.TrajectoryStep(
|
||||
prompt=[
|
||||
@@ -248,21 +263,24 @@ def multi_step_trajectory_with_tool_calls_extension_never_holds():
|
||||
reward=None,
|
||||
advantage=None,
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
),
|
||||
],
|
||||
reward=1.0,
|
||||
advantage=None,
|
||||
stop_condition=None,
|
||||
sampling_args={"temperature": 1.0},
|
||||
metrics={"has_error": 0.0, "tool_calls": 1.0},
|
||||
error=None,
|
||||
)
|
||||
return state
|
||||
return output
|
||||
|
||||
|
||||
def test_branching_equivalent_multi_step_trajectory(multi_step_trajectory_extension_never_holds):
|
||||
"""When extension never holds, each step becomes its own sample (same as old branching)."""
|
||||
rollouts = interleave_rollout(multi_step_trajectory_extension_never_holds)
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 2
|
||||
|
||||
# first step
|
||||
@@ -289,6 +307,7 @@ def test_branching_equivalent_multi_step_trajectory_with_tool_calls(
|
||||
):
|
||||
"""When extension never holds (with tool calls), same as old branching."""
|
||||
rollouts = interleave_rollout(multi_step_trajectory_with_tool_calls_extension_never_holds)
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 2
|
||||
|
||||
# first step
|
||||
@@ -310,8 +329,9 @@ def test_branching_equivalent_multi_step_trajectory_with_tool_calls(
|
||||
assert rollout.completion_temperatures == [1.0, 1.0]
|
||||
|
||||
|
||||
def test_interleave_rollout_single_step_trajectory(single_step_trajectory_state):
|
||||
rollouts = interleave_rollout(single_step_trajectory_state)
|
||||
def test_interleave_rollout_single_step_trajectory(single_step_trajectory_output):
|
||||
rollouts = interleave_rollout(single_step_trajectory_output)
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 1
|
||||
rollout = rollouts[0]
|
||||
|
||||
@@ -323,8 +343,9 @@ def test_interleave_rollout_single_step_trajectory(single_step_trajectory_state)
|
||||
assert rollout.completion_temperatures == [1.0, 1.0]
|
||||
|
||||
|
||||
def test_interleave_rollout_multi_step_trajectory(multi_step_trajectory_state):
|
||||
rollouts = interleave_rollout(multi_step_trajectory_state)
|
||||
def test_interleave_rollout_multi_step_trajectory(multi_step_trajectory_output):
|
||||
rollouts = interleave_rollout(multi_step_trajectory_output)
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 1
|
||||
rollout = rollouts[0]
|
||||
|
||||
@@ -337,8 +358,9 @@ def test_interleave_rollout_multi_step_trajectory(multi_step_trajectory_state):
|
||||
assert rollout.completion_temperatures == [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
|
||||
|
||||
|
||||
def test_interleave_rollout_multi_step_trajectory_with_tool_calls(multi_step_trajectory_with_tool_calls):
|
||||
rollouts = interleave_rollout(multi_step_trajectory_with_tool_calls)
|
||||
def test_interleave_rollout_multi_step_trajectory_with_tool_calls(multi_step_trajectory_with_tool_calls_output):
|
||||
rollouts = interleave_rollout(multi_step_trajectory_with_tool_calls_output)
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 1
|
||||
rollout = rollouts[0]
|
||||
|
||||
@@ -362,8 +384,8 @@ def five_step_trajectory_with_extension_break():
|
||||
|
||||
Expected: 2 samples (steps 1-3 merged, steps 4-5 merged)
|
||||
"""
|
||||
state = vf.State(
|
||||
input=vf.RolloutInput(messages=[], example_id="test-extension-break"),
|
||||
output = vf.RolloutOutput(
|
||||
example_id=0,
|
||||
trajectory=[
|
||||
# Step 1: initial prompt and completion
|
||||
vf.TrajectoryStep(
|
||||
@@ -382,7 +404,8 @@ def five_step_trajectory_with_extension_break():
|
||||
reward=None,
|
||||
advantage=None,
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
),
|
||||
# Step 2: extends step 1 (prefix [1,2,3,4] matches)
|
||||
vf.TrajectoryStep(
|
||||
@@ -405,7 +428,8 @@ def five_step_trajectory_with_extension_break():
|
||||
reward=None,
|
||||
advantage=None,
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
),
|
||||
# Step 3: extends step 2 (prefix [1,2,3,4,5,6,7,8] matches)
|
||||
vf.TrajectoryStep(
|
||||
@@ -430,7 +454,8 @@ def five_step_trajectory_with_extension_break():
|
||||
reward=None,
|
||||
advantage=None,
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
),
|
||||
# Step 4: EXTENSION BREAKS - different prefix (e.g. thinking stripped, context compacted)
|
||||
vf.TrajectoryStep(
|
||||
@@ -457,7 +482,8 @@ def five_step_trajectory_with_extension_break():
|
||||
reward=None,
|
||||
advantage=None,
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
),
|
||||
# Step 5: extends step 4 (prefix [100,101,102,103,104,105] matches)
|
||||
vf.TrajectoryStep(
|
||||
@@ -486,12 +512,14 @@ def five_step_trajectory_with_extension_break():
|
||||
reward=None,
|
||||
advantage=None,
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
return state
|
||||
return output
|
||||
|
||||
|
||||
def test_interleave_rollout_extension_break_creates_multiple_samples(five_step_trajectory_with_extension_break):
|
||||
@@ -503,6 +531,7 @@ def test_interleave_rollout_extension_break_creates_multiple_samples(five_step_t
|
||||
"""
|
||||
rollouts = interleave_rollout(five_step_trajectory_with_extension_break)
|
||||
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 2, "Should produce 2 samples when extension breaks at step 4"
|
||||
|
||||
# First sample: steps 1-3 merged
|
||||
@@ -539,7 +568,7 @@ def interleaved_agents_trajectory():
|
||||
agent2-step1: prompt=[100,101], completion=[102,103] (different prefix, new sample)
|
||||
agent1-step3: prompt=[1,2,3,4,5,6,7,8,9,10], completion=[11,12] (extends agent1-step2!)
|
||||
"""
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
task="test",
|
||||
trajectory=[
|
||||
@@ -562,7 +591,6 @@ def interleaved_agents_trajectory():
|
||||
is_truncated=False,
|
||||
trajectory_id="traj1",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
),
|
||||
# agent1-step2 (extends agent1-step1)
|
||||
vf.TrajectoryStep(
|
||||
@@ -583,7 +611,6 @@ def interleaved_agents_trajectory():
|
||||
is_truncated=False,
|
||||
trajectory_id="traj1",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
),
|
||||
# agent2-step1 (different prefix, starts new sample)
|
||||
vf.TrajectoryStep(
|
||||
@@ -604,7 +631,6 @@ def interleaved_agents_trajectory():
|
||||
is_truncated=False,
|
||||
trajectory_id="traj2",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
),
|
||||
# agent1-step3 (extends agent1-step2, should merge back!)
|
||||
vf.TrajectoryStep(
|
||||
@@ -625,12 +651,12 @@ def interleaved_agents_trajectory():
|
||||
is_truncated=False,
|
||||
trajectory_id="traj1",
|
||||
extras={},
|
||||
temperature=1.0,
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
return state
|
||||
return output
|
||||
|
||||
|
||||
def test_interleave_rollout_interleaved_agents(interleaved_agents_trajectory):
|
||||
@@ -640,6 +666,7 @@ def test_interleave_rollout_interleaved_agents(interleaved_agents_trajectory):
|
||||
"""
|
||||
rollouts = interleave_rollout(interleaved_agents_trajectory)
|
||||
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 2, "Should produce 2 samples (agent1 merged, agent2 separate)"
|
||||
|
||||
# First sample: agent1 steps 1, 2, 3 merged
|
||||
@@ -713,7 +740,7 @@ def test_extract_images_from_messages_multiple_images():
|
||||
|
||||
def test_extract_images_from_examples_single_turn():
|
||||
image_url = _create_test_image("red")
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
@@ -721,13 +748,18 @@ def test_extract_images_from_examples_single_turn():
|
||||
completion=[{"role": "assistant", "content": "A red square"}],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
temperature=1.0,
|
||||
)
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
all_images, images_per_step = _extract_images_from_examples([(1, state)])
|
||||
all_images, images_per_step = _extract_images_from_examples([(1, output)])
|
||||
|
||||
assert len(all_images) == 1
|
||||
assert images_per_step == {1: [1]} # 1 image after step 0
|
||||
@@ -738,7 +770,7 @@ def test_extract_images_from_examples_multi_turn_new_image_each_turn():
|
||||
red_url = _create_test_image("red")
|
||||
green_url = _create_test_image("green")
|
||||
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
# Turn 1: just the red image
|
||||
@@ -747,7 +779,11 @@ def test_extract_images_from_examples_multi_turn_new_image_each_turn():
|
||||
completion=[{"role": "assistant", "content": "Red"}],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Turn 2: cumulative prompt with red image + green image
|
||||
vf.TrajectoryStep(
|
||||
@@ -759,13 +795,18 @@ def test_extract_images_from_examples_multi_turn_new_image_each_turn():
|
||||
completion=[{"role": "assistant", "content": "Green"}],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
all_images, images_per_step = _extract_images_from_examples([(1, state)])
|
||||
all_images, images_per_step = _extract_images_from_examples([(1, output)])
|
||||
|
||||
assert len(all_images) == 2 # 2 unique images total
|
||||
assert images_per_step == {1: [1, 2]} # 1 after step 0, 2 after step 1
|
||||
@@ -775,7 +816,7 @@ def test_extract_images_from_examples_multi_turn_no_new_images():
|
||||
"""Test turns where no new images are added."""
|
||||
red_url = _create_test_image("red")
|
||||
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
@@ -783,7 +824,11 @@ def test_extract_images_from_examples_multi_turn_no_new_images():
|
||||
completion=[{"role": "assistant", "content": "Red"}],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Turn 2: same image, no new ones
|
||||
vf.TrajectoryStep(
|
||||
@@ -795,13 +840,18 @@ def test_extract_images_from_examples_multi_turn_no_new_images():
|
||||
completion=[{"role": "assistant", "content": "Yes"}],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
all_images, images_per_step = _extract_images_from_examples([(1, state)])
|
||||
all_images, images_per_step = _extract_images_from_examples([(1, output)])
|
||||
|
||||
assert len(all_images) == 1 # Only 1 unique image
|
||||
assert images_per_step == {1: [1, 1]} # 1 after step 0, still 1 after step 1
|
||||
@@ -877,7 +927,7 @@ def test_interleave_rollout_with_vlm_cache():
|
||||
}
|
||||
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
|
||||
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
@@ -893,7 +943,11 @@ def test_interleave_rollout_with_vlm_cache():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "Turn 2"}],
|
||||
@@ -908,16 +962,22 @@ def test_interleave_rollout_with_vlm_cache():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
rollouts = interleave_rollout(state, vlm_cache=cache)
|
||||
rollouts = interleave_rollout(output, vlm_cache=cache)
|
||||
|
||||
# Extension holds (step 1 prompt [1,2,3,4,5] extends prefix [1,2,3,4])
|
||||
# so both steps merge into a single sample with cumulative images from step 1
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 1
|
||||
rollout = rollouts[0]
|
||||
assert rollout.prompt_ids == [1, 2]
|
||||
@@ -937,7 +997,7 @@ def test_interleave_rollout_uses_cache_key_override():
|
||||
}
|
||||
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
|
||||
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=123,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
@@ -953,14 +1013,20 @@ def test_interleave_rollout_uses_cache_key_override():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
rollouts = interleave_rollout(state, vlm_cache=cache, cache_key=7)
|
||||
rollouts = interleave_rollout(output, vlm_cache=cache, cache_key=7)
|
||||
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 1
|
||||
assert rollouts[0].pixel_values == [[9.0]]
|
||||
assert rollouts[0].image_grid_thw == [[1, 2, 3]]
|
||||
@@ -981,7 +1047,7 @@ def test_interleave_rollout_vlm_image_then_text_turns():
|
||||
}
|
||||
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
|
||||
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
# Step 0: user sends image
|
||||
@@ -998,7 +1064,11 @@ def test_interleave_rollout_vlm_image_then_text_turns():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 1: text-only follow-up (extension holds)
|
||||
vf.TrajectoryStep(
|
||||
@@ -1014,7 +1084,11 @@ def test_interleave_rollout_vlm_image_then_text_turns():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 2: another text-only follow-up (extension holds)
|
||||
vf.TrajectoryStep(
|
||||
@@ -1030,15 +1104,21 @@ def test_interleave_rollout_vlm_image_then_text_turns():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
rollouts = interleave_rollout(state, vlm_cache=cache)
|
||||
rollouts = interleave_rollout(output, vlm_cache=cache)
|
||||
|
||||
# All 3 steps merge into 1 sample (extension always holds)
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 1
|
||||
rollout = rollouts[0]
|
||||
assert rollout.prompt_ids == [1, 2]
|
||||
@@ -1065,7 +1145,7 @@ def test_interleave_rollout_vlm_new_image_mid_conversation():
|
||||
}
|
||||
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
|
||||
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
@@ -1081,7 +1161,11 @@ def test_interleave_rollout_vlm_new_image_mid_conversation():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "Text only"}],
|
||||
@@ -1096,7 +1180,11 @@ def test_interleave_rollout_vlm_new_image_mid_conversation():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "Image 2"}],
|
||||
@@ -1111,14 +1199,20 @@ def test_interleave_rollout_vlm_new_image_mid_conversation():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
rollouts = interleave_rollout(state, vlm_cache=cache)
|
||||
rollouts = interleave_rollout(output, vlm_cache=cache)
|
||||
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 1
|
||||
rollout = rollouts[0]
|
||||
assert rollout.prompt_ids == [1, 2]
|
||||
@@ -1143,7 +1237,7 @@ def test_interleave_rollout_vlm_extension_break():
|
||||
}
|
||||
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
|
||||
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
@@ -1159,7 +1253,11 @@ def test_interleave_rollout_vlm_extension_break():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 1: extends step 0
|
||||
vf.TrajectoryStep(
|
||||
@@ -1175,7 +1273,11 @@ def test_interleave_rollout_vlm_extension_break():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 2: extension breaks (different prefix, e.g. context compaction)
|
||||
vf.TrajectoryStep(
|
||||
@@ -1191,14 +1293,20 @@ def test_interleave_rollout_vlm_extension_break():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
rollouts = interleave_rollout(state, vlm_cache=cache)
|
||||
rollouts = interleave_rollout(output, vlm_cache=cache)
|
||||
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 2
|
||||
|
||||
# Sample 1: steps 0-1 merged, images from step 1 (still 1 image)
|
||||
@@ -1229,7 +1337,7 @@ def test_interleave_rollout_vlm_image_appears_late():
|
||||
}
|
||||
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
|
||||
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
# Step 0: text-only
|
||||
@@ -1246,7 +1354,11 @@ def test_interleave_rollout_vlm_image_appears_late():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 1: text-only (extension holds)
|
||||
vf.TrajectoryStep(
|
||||
@@ -1262,7 +1374,11 @@ def test_interleave_rollout_vlm_image_appears_late():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 2: user sends image (extension holds)
|
||||
vf.TrajectoryStep(
|
||||
@@ -1278,14 +1394,20 @@ def test_interleave_rollout_vlm_image_appears_late():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
rollouts = interleave_rollout(state, vlm_cache=cache)
|
||||
rollouts = interleave_rollout(output, vlm_cache=cache)
|
||||
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 1
|
||||
rollout = rollouts[0]
|
||||
assert rollout.prompt_ids == [1, 2]
|
||||
@@ -1298,20 +1420,20 @@ def test_interleave_rollout_vlm_image_appears_late():
|
||||
|
||||
def test_interleave_rollout_empty_trajectory():
|
||||
"""Empty trajectory returns None."""
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[],
|
||||
error=None,
|
||||
)
|
||||
assert interleave_rollout(state) is None
|
||||
assert interleave_rollout(output) is None
|
||||
|
||||
|
||||
def test_interleave_rollout_error_state_masks_all_false():
|
||||
def test_interleave_rollout_error_masks_all_false():
|
||||
"""
|
||||
When state has an error, all completion_mask values should be False
|
||||
When rollout output has an error, all completion_mask values should be False
|
||||
across both make_sample (step 0) and extend_sample (step 1).
|
||||
"""
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
@@ -1327,7 +1449,11 @@ def test_interleave_rollout_error_state_masks_all_false():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=0.8,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "U2"}],
|
||||
@@ -1342,14 +1468,20 @@ def test_interleave_rollout_error_state_masks_all_false():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=0.8,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
error="timeout: environment exceeded time limit",
|
||||
sampling_args={"temperature": 0.8},
|
||||
)
|
||||
|
||||
rollouts = interleave_rollout(state)
|
||||
rollouts = interleave_rollout(output)
|
||||
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 1
|
||||
rollout = rollouts[0]
|
||||
# Extension holds so tokens merge, but ALL completion_mask should be False
|
||||
@@ -1385,7 +1517,7 @@ def test_interleave_rollout_vlm_interleaved_agents():
|
||||
}
|
||||
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
|
||||
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
# Step 0: agent1-step1
|
||||
@@ -1402,7 +1534,11 @@ def test_interleave_rollout_vlm_interleaved_agents():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 1: agent1-step2 (extends step 0)
|
||||
vf.TrajectoryStep(
|
||||
@@ -1418,7 +1554,11 @@ def test_interleave_rollout_vlm_interleaved_agents():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 2: agent2-step1 (different prefix)
|
||||
vf.TrajectoryStep(
|
||||
@@ -1434,7 +1574,11 @@ def test_interleave_rollout_vlm_interleaved_agents():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 3: agent1-step3 (extends agent1, merges back)
|
||||
vf.TrajectoryStep(
|
||||
@@ -1450,14 +1594,20 @@ def test_interleave_rollout_vlm_interleaved_agents():
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
error=None,
|
||||
sampling_args={"temperature": 1.0},
|
||||
)
|
||||
|
||||
rollouts = interleave_rollout(state, vlm_cache=cache)
|
||||
rollouts = interleave_rollout(output, vlm_cache=cache)
|
||||
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 2
|
||||
|
||||
# Agent1: steps 0,1,3 merged → images from step 3 (A+C)
|
||||
@@ -1485,7 +1635,7 @@ def test_build_vlm_image_cache_handles_divergent_rollouts():
|
||||
blue_url = _create_test_image("blue")
|
||||
green_url = _create_test_image("green")
|
||||
|
||||
rollout_a = vf.State(
|
||||
rollout_a = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
@@ -1493,13 +1643,18 @@ def test_build_vlm_image_cache_handles_divergent_rollouts():
|
||||
completion=[{"role": "assistant", "content": "Red"}],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
rollout_b = vf.State(
|
||||
rollout_b = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
@@ -1507,7 +1662,11 @@ def test_build_vlm_image_cache_handles_divergent_rollouts():
|
||||
completion=[{"role": "assistant", "content": "Blue"}],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
vf.TrajectoryStep(
|
||||
prompt=[
|
||||
@@ -1518,9 +1677,14 @@ def test_build_vlm_image_cache_handles_divergent_rollouts():
|
||||
completion=[{"role": "assistant", "content": "Green"}],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
@@ -1552,7 +1716,7 @@ def test_build_vlm_image_cache_handles_divergent_rollouts():
|
||||
|
||||
|
||||
def test_build_vlm_image_cache_no_images():
|
||||
state = vf.State(
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
@@ -1560,13 +1724,18 @@ def test_build_vlm_image_cache_no_images():
|
||||
completion=[{"role": "assistant", "content": "Hi"}],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
temperature=1.0,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
)
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
cache = build_vlm_image_cache([state], MagicMock())
|
||||
cache = build_vlm_image_cache([output], MagicMock())
|
||||
|
||||
pv, grid = cache.get_for_step(0, 0)
|
||||
assert pv is None
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import json
|
||||
from copy import deepcopy
|
||||
|
||||
import pytest
|
||||
import verifiers as vf
|
||||
from openai.types.chat.chat_completion import ChatCompletion, Choice
|
||||
from openai.types.chat.chat_completion_message import ChatCompletionMessage
|
||||
from openai.types.completion_usage import CompletionUsage
|
||||
|
||||
from prime_rl.utils.vf import from_serializable_state, to_serializable_state
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def single_step_trajectory_state():
|
||||
state = vf.State(
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "U1"}],
|
||||
completion=[{"role": "assistant", "content": "A1"}],
|
||||
response=ChatCompletion(
|
||||
id="cm123",
|
||||
object="chat.completion",
|
||||
created=1716806400,
|
||||
model="gpt-4o",
|
||||
choices=[
|
||||
Choice(
|
||||
index=0,
|
||||
message=ChatCompletionMessage(
|
||||
role="assistant",
|
||||
content="A1",
|
||||
),
|
||||
finish_reason="stop",
|
||||
)
|
||||
],
|
||||
usage=CompletionUsage(prompt_tokens=2, completion_tokens=1, total_tokens=3),
|
||||
),
|
||||
tokens=vf.TrajectoryStepTokens(
|
||||
prompt_ids=[1, 2],
|
||||
prompt_mask=[0, 0],
|
||||
completion_ids=[3, 4],
|
||||
completion_mask=[1, 1],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
overlong_prompt=False,
|
||||
is_truncated=False,
|
||||
),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
extras={},
|
||||
)
|
||||
],
|
||||
)
|
||||
return state
|
||||
|
||||
|
||||
def test_serialize_state(single_step_trajectory_state):
|
||||
# Regular state is not JSON serializable
|
||||
with pytest.raises(Exception):
|
||||
json.dumps(single_step_trajectory_state)
|
||||
|
||||
# Serialized state is JSON serializable
|
||||
serializable_state = to_serializable_state(single_step_trajectory_state)
|
||||
json.dumps(serializable_state)
|
||||
|
||||
|
||||
def test_deserialize_state(single_step_trajectory_state):
|
||||
original_state = deepcopy(single_step_trajectory_state)
|
||||
serialized_state = to_serializable_state(single_step_trajectory_state)
|
||||
deserialized_state = from_serializable_state(serialized_state)
|
||||
assert deserialized_state == original_state
|
||||
@@ -4,7 +4,6 @@ from pathlib import Path
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from prime_rl.eval.config import OfflineEvalConfig
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.rl import RLConfig
|
||||
@@ -13,7 +12,7 @@ from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
|
||||
# All config config classes
|
||||
CONFIG_CLASSES = [RLConfig, RLTrainerConfig, SFTTrainerConfig, OrchestratorConfig, InferenceConfig, OfflineEvalConfig]
|
||||
CONFIG_CLASSES = [RLConfig, RLTrainerConfig, SFTTrainerConfig, OrchestratorConfig, InferenceConfig]
|
||||
|
||||
|
||||
def get_config_files() -> list[Path]:
|
||||
@@ -27,9 +26,6 @@ def get_config_files() -> list[Path]:
|
||||
@pytest.mark.parametrize("config_file", get_config_files(), ids=lambda x: x.as_posix())
|
||||
def test_load_configs(config_file: Path, monkeypatch: pytest.MonkeyPatch):
|
||||
"""Tests that all config files can be loaded by at least one config class."""
|
||||
if "intellect_3/evals" in config_file.as_posix():
|
||||
pytest.skip("Skipped because uses partial configs, which are not supported by this test.")
|
||||
|
||||
monkeypatch.setattr(
|
||||
sys,
|
||||
"argv",
|
||||
|
||||
@@ -8,7 +8,6 @@ import httpx
|
||||
from prime_rl.utils.elastic import (
|
||||
AdapterState,
|
||||
ElasticInferencePool,
|
||||
ServerDiscovery,
|
||||
check_server_model,
|
||||
discover_ready_servers,
|
||||
discover_server_ips,
|
||||
@@ -189,6 +188,7 @@ def test_adapter_matches_when_no_adapter_desired():
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
# No adapter desired (base model inference)
|
||||
@@ -201,6 +201,7 @@ def test_adapter_matches_by_path():
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
pool._desired.path = Path("/weights/step_100")
|
||||
@@ -218,6 +219,7 @@ def test_adapter_matches_by_step_when_nonzero():
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
pool._desired.path = Path("/weights/step_100")
|
||||
@@ -233,6 +235,7 @@ def test_adapter_does_not_match_by_zero_step():
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
pool._desired.path = Path("/weights/step_0")
|
||||
@@ -248,6 +251,7 @@ def test_adapter_returns_false_when_no_adapter_loaded():
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
pool._desired.path = Path("/weights/step_100")
|
||||
@@ -256,132 +260,6 @@ def test_adapter_returns_false_when_no_adapter_loaded():
|
||||
assert pool._adapter_matches_desired(None) is False
|
||||
|
||||
|
||||
# ServerDiscovery tests
|
||||
|
||||
|
||||
def test_server_discovery_initialization():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
mock_config = MagicMock()
|
||||
mock_config.timeout = 30
|
||||
mock_config.api_key_var = "TEST_KEY"
|
||||
mock_config.headers = {}
|
||||
|
||||
discovery = ServerDiscovery(
|
||||
hostname="test.hostname",
|
||||
port=8000,
|
||||
model_name="my-model",
|
||||
client_config=mock_config,
|
||||
sync_interval=5.0,
|
||||
)
|
||||
|
||||
assert discovery.hostname == "test.hostname"
|
||||
assert discovery.port == 8000
|
||||
assert discovery.sync_interval == 5.0
|
||||
assert discovery.model_name == "my-model"
|
||||
assert discovery.has_clients is False
|
||||
assert discovery.get_next_client() is None
|
||||
|
||||
|
||||
def test_server_discovery_round_robin():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
mock_config = MagicMock()
|
||||
|
||||
discovery = ServerDiscovery(
|
||||
hostname="test.hostname",
|
||||
port=8000,
|
||||
model_name="my-model",
|
||||
client_config=mock_config,
|
||||
sync_interval=5.0,
|
||||
)
|
||||
|
||||
# Manually set clients to test round-robin
|
||||
client1, client2, client3 = MagicMock(), MagicMock(), MagicMock()
|
||||
discovery._clients = [client1, client2, client3]
|
||||
discovery._urls = ["url1", "url2", "url3"]
|
||||
|
||||
assert discovery.has_clients is True
|
||||
assert discovery.get_next_client() is client1
|
||||
assert discovery.get_next_client() is client2
|
||||
assert discovery.get_next_client() is client3
|
||||
assert discovery.get_next_client() is client1 # wraps around
|
||||
|
||||
|
||||
def test_server_discovery_refresh_creates_clients_on_discovery():
|
||||
with (
|
||||
patch("prime_rl.utils.elastic.get_logger"),
|
||||
patch("prime_rl.utils.elastic.discover_ready_servers") as mock_discover,
|
||||
patch("prime_rl.utils.elastic.setup_clients") as mock_setup_clients,
|
||||
):
|
||||
mock_config = MagicMock()
|
||||
mock_config.timeout = 30
|
||||
mock_config.api_key_var = "TEST_KEY"
|
||||
mock_config.headers = {}
|
||||
|
||||
mock_discover.return_value = ["http://10.0.0.1:8000/v1"]
|
||||
mock_client = MagicMock()
|
||||
mock_setup_clients.return_value = [mock_client]
|
||||
|
||||
discovery = ServerDiscovery(
|
||||
hostname="test.hostname",
|
||||
port=8000,
|
||||
model_name="my-model",
|
||||
client_config=mock_config,
|
||||
sync_interval=0.0, # No throttling for tests
|
||||
)
|
||||
|
||||
changed = asyncio.run(discovery.refresh())
|
||||
|
||||
assert changed is True
|
||||
mock_discover.assert_called_once_with("test.hostname", 8000, "my-model")
|
||||
|
||||
|
||||
def test_server_discovery_refresh_no_change_when_urls_same():
|
||||
with (
|
||||
patch("prime_rl.utils.elastic.get_logger"),
|
||||
patch("prime_rl.utils.elastic.discover_ready_servers") as mock_discover,
|
||||
):
|
||||
mock_config = MagicMock()
|
||||
mock_config.timeout = 30
|
||||
mock_config.api_key_var = "TEST_KEY"
|
||||
mock_config.headers = {}
|
||||
|
||||
mock_discover.return_value = ["http://10.0.0.1:8000/v1"]
|
||||
|
||||
discovery = ServerDiscovery(
|
||||
hostname="test.hostname",
|
||||
port=8000,
|
||||
model_name="my-model",
|
||||
client_config=mock_config,
|
||||
sync_interval=0.0,
|
||||
)
|
||||
discovery._urls = ["http://10.0.0.1:8000/v1"]
|
||||
discovery._last_refresh = 0 # Allow refresh
|
||||
|
||||
changed = asyncio.run(discovery.refresh())
|
||||
|
||||
assert changed is False
|
||||
|
||||
|
||||
def test_server_discovery_model_name_can_be_updated():
|
||||
"""Test that discovery model name can be updated for LoRA switching."""
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
mock_config = MagicMock()
|
||||
|
||||
discovery = ServerDiscovery(
|
||||
hostname="test.hostname",
|
||||
port=8000,
|
||||
model_name="base-model",
|
||||
client_config=mock_config,
|
||||
sync_interval=5.0,
|
||||
)
|
||||
assert discovery.model_name == "base-model"
|
||||
|
||||
# Simulate LoRA switch by updating model name
|
||||
discovery.model_name = "lora-adapter"
|
||||
discovery._urls = [] # Force refresh
|
||||
assert discovery.model_name == "lora-adapter"
|
||||
|
||||
|
||||
# _get_loaded_adapter tests
|
||||
|
||||
|
||||
@@ -391,7 +269,7 @@ def test_get_loaded_adapter_finds_correct_adapter_when_multiple_loaded():
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
base_model="base-model",
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
|
||||
@@ -442,7 +320,7 @@ def test_get_loaded_adapter_returns_none_when_desired_adapter_not_found():
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
base_model="base-model",
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
|
||||
@@ -473,6 +351,7 @@ def test_get_loaded_adapter_parses_step_from_path():
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
|
||||
@@ -501,6 +380,7 @@ def test_get_loaded_adapter_handles_step_dash_format():
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
|
||||
|
||||
@@ -2581,7 +2581,7 @@ requires-dist = [
|
||||
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
|
||||
{ name = "transformers", specifier = ">=4.57.6" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=e85c598" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3409cb5" },
|
||||
{ name = "vllm", specifier = "==0.14.0" },
|
||||
{ name = "wandb", specifier = ">=0.20.1" },
|
||||
]
|
||||
@@ -3956,7 +3956,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "verifiers"
|
||||
version = "0.1.10.dev3"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=e85c598#e85c5981bd68c8e3b476838acf99e0e43dfdc2b9" }
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3409cb5#3409cb5f1d780def683bfa7eec4010f1e4682d9b" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "gepa" },
|
||||
|
||||
Reference in New Issue
Block a user