Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2da1e4ac5a | ||
|
|
7d8da4cbcc | ||
|
|
7036a15119 | ||
|
|
aef4a600f9 | ||
|
|
a3a307e70c | ||
|
|
83c21ddac5 | ||
|
|
5f2dc0fe42 | ||
|
|
5b15e54e88 | ||
|
|
4825d76e75 | ||
|
|
668579aaf0 | ||
|
|
ce55c150e7 | ||
|
|
75355f497b | ||
|
|
1c559feb25 |
+5
-1
@@ -63,7 +63,9 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
|
||||
- **`orchestrator.use_token_client`**: Added flag to use the token-in-token-out (TITO) client for training across all environments. When enabled, uses `openai_chat_completions_token` client type instead of `openai_chat_completions`. Only use when environments have linear history and the chat template has the extension property (default: False) (2026-02-21)
|
||||
- **`model.cp` + AFMoE**: Context parallelism now works with AFMoE models via unified `substitute_ring_attn` which patches `_compute_attention` on both `FlashAttention` and `AfmoeFlashAttention` to use ring attention. Sliding window layers automatically get per-layer `window_size`; full attention layers default to `(-1, -1)`. Also plumbed `window_size` through the FA3 ring attention wrapper (`ring_fa3_varlen_func`). (2026-02-21)
|
||||
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-0
|
||||
- **`orchestrator.token_batch_size`** and **`orchestrator.max_inflight_rollouts`**: Added token-based batching via `token_batch_size` and explicit in-flight rollout control via `max_inflight_rollouts` (2026-02-23)
|
||||
- **`orchestrator.batch_size`**: Now optional and mutually exclusive with `token_batch_size`. If neither is set, defaults to rollout mode with `batch_size=128` (2026-02-23)
|
||||
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-02-23)
|
||||
- **`rl_slurm` / `sft_slurm` entrypoints**: Removed. SLURM submission is now handled by the unified `rl` and `sft` entrypoints. Add a `[slurm]` section to your config to submit via SLURM instead of running locally (2026-02-23)
|
||||
- **`inference_gpu_ids` / `trainer_gpu_ids` / `teacher_gpu_ids`**: Removed from `RLConfig`. Replaced by `[deployment]` section with `type = "single_node"` (fields: `num_train_gpus`, `num_infer_gpus`, `num_teacher_gpus`) or `type = "multi_node"` (fields: `num_train_nodes`, `num_infer_nodes`, `num_teacher_nodes`, `nodes_per_fsdp_group`). Default is `single_node` with 1 train GPU and 1 infer GPU (2026-02-23)
|
||||
- **`RLSLURMConfig`**: Removed. Fields `job_name`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in the unified `RLConfig` (2026-02-23)
|
||||
@@ -79,3 +81,5 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`clean_output_dir`**: Added to `RLConfig` and `SFTConfig` (default: `False`). Training now raises `FileExistsError` when `output_dir` contains checkpoints from a previous run and not resuming. Set `clean_output_dir=true` to delete and start fresh, or set `ckpt.resume_step` to resume (2026-02-24)
|
||||
- **`clean`**: Removed from `RLConfig`. The old `clean` flag (default: `True`) silently deleted logs, rollouts, and broadcasts on every local RL run. Superseded by the explicit `clean_output_dir` flag (2026-02-24)
|
||||
- **Config consolidation**: All config modules moved into `prime_rl.configs` subpackage. `utils/config.py` + `transport/config.py` → `configs/shared.py`; `trainer/config.py` + `trainer/rl/config.py` → `configs/trainer.py`; `trainer/sft/config.py` → `configs/sft.py`; `orchestrator/config.py` → `configs/orchestrator.py`; `inference/config.py` → `configs/inference.py`; `rl_config.py` → `configs/rl.py`. Class renames: `SFTTrainerConfig` → `SFTConfig`, `RLTrainerConfig` → `TrainerConfig`. Component prefixes dropped from orchestrator and inference config classes (e.g. `OrchestratorCheckpointConfig` → `CheckpointConfig`). TypeAlias renames: dropped `Type` suffix (e.g. `LossConfigType` → `LossConfig`, `TransportConfigType` → `TransportConfig`), renamed `LossConfig` class → `DefaultLossConfig`. No TOML key changes. (2026-02-24)
|
||||
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
|
||||
- **`model.fused_lm_head_chunk_size`**: Changed default value from 2048 to 8192 for RL training (2026-02-26)
|
||||
|
||||
+16
-16
@@ -15,34 +15,34 @@
|
||||
"cp": 1,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "a76eec30",
|
||||
"timestamp": "2026-02-01T00:37:17.504432+00:00",
|
||||
"commit_sha": "83c21ddac",
|
||||
"timestamp": "2026-02-26T02:07:06+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 276.12556480802596
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 17.08174826544651,
|
||||
"std": 0.00860887294908562,
|
||||
"min": 17.07595532741123,
|
||||
"max": 17.091640740120457
|
||||
"mean": 16.41977165630161,
|
||||
"std": 0.010586646038388221,
|
||||
"min": 16.407648988464405,
|
||||
"max": 16.42719598975201
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 2040.0423352992304,
|
||||
"std": 1.0281421434405753,
|
||||
"min": 2039.3504951752516,
|
||||
"max": 2041.2237756777045
|
||||
"mean": 1960.9836648020673,
|
||||
"std": 1.2643440104327244,
|
||||
"min": 1959.5358764831926,
|
||||
"max": 1961.8703395331793
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 63.29752009687945,
|
||||
"std": 0.1304965028229097,
|
||||
"min": 63.170207182411104,
|
||||
"max": 63.430982740130275
|
||||
"mean": 65.87,
|
||||
"std": 0.13,
|
||||
"min": 65.74,
|
||||
"max": 66.0
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 22.685546875,
|
||||
"pct": 47.72
|
||||
"gib": 31.806640625,
|
||||
"pct": 67.03
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-17
@@ -13,36 +13,36 @@
|
||||
"micro_batches": 2,
|
||||
"ep": 1,
|
||||
"cp": 1,
|
||||
"docker_image": "primeintellect/prime-rl@sha256:d3e9636af265f5ba2e56cd2555534489f5ff64e04a3f645059ca7989508de419",
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "a76eec30",
|
||||
"timestamp": "2026-01-31T01:13:40.536972+00:00",
|
||||
"commit_sha": "83c21ddac",
|
||||
"timestamp": "2026-02-26T02:07:06+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 291.91085167229176
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 16.165875888064594,
|
||||
"std": 0.010063094728313886,
|
||||
"min": 16.154265967508614,
|
||||
"max": 16.172097002189034
|
||||
"mean": 15.634260517326164,
|
||||
"std": 0.009817863071768202,
|
||||
"min": 15.622927380137481,
|
||||
"max": 15.640172924064188
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 7722.645407567771,
|
||||
"std": 4.80726889329249,
|
||||
"min": 7717.099200218126,
|
||||
"max": 7725.61731325081
|
||||
"mean": 7468.685954343421,
|
||||
"std": 4.690118598479809,
|
||||
"min": 7463.271969943842,
|
||||
"max": 7471.510386564679
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 66.21160964062437,
|
||||
"std": 0.11667723461510121,
|
||||
"min": 66.1170196281746,
|
||||
"max": 66.34198968904093
|
||||
"mean": 68.34095695288852,
|
||||
"std": 0.16054587555887065,
|
||||
"min": 68.16114284005016,
|
||||
"max": 68.46991707291454
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 14.1328125,
|
||||
"pct": 29.74
|
||||
"gib": 23.25390625,
|
||||
"pct": 49.05701678145735
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,5 @@ api_server_count = 8
|
||||
gpu_memory_utilization = 0.8
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
max_model_len = 8192
|
||||
@@ -25,6 +25,5 @@ args = { sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox
|
||||
api_server_count = 4
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
max_model_len = 4096
|
||||
@@ -40,5 +40,4 @@ online_difficulty_filtering = true
|
||||
id = "primeintellect/wiki-search"
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
|
||||
@@ -49,5 +49,4 @@ id = "primeintellect/wiki-search"
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
|
||||
+4
-2
@@ -58,8 +58,10 @@ flash-attn-3 = [
|
||||
flash-attn-cute = [
|
||||
"flash-attn-cute",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
fp8-inference = [
|
||||
"deep-gemm @ https://github.com/hallerite/DeepGEMM/releases/download/v2.3.0/deep_gemm-2.3.0+35c4bc8-cp312-cp312-linux_x86_64.whl",
|
||||
]
|
||||
dev = [
|
||||
"ipykernel>=6.29.5",
|
||||
"ipywidgets>=8.1.7",
|
||||
@@ -87,7 +89,7 @@ verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev =
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
|
||||
vllm = { url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" }
|
||||
vllm = { url = "https://vllm-wheels.s3.us-west-2.amazonaws.com/7a06e5b05b170d7da31845866da0a99fc65253a1/vllm-0.16.0rc3-cp38-abi3-manylinux_2_31_x86_64.whl" }
|
||||
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "main" }
|
||||
reverse-text = { index = "primeintellect" }
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
name: installation
|
||||
description: How to install prime-rl and its optional dependencies. Use when setting up the project, installing extras like deep-gemm for FP8 models, or troubleshooting dependency issues.
|
||||
---
|
||||
|
||||
# Installation
|
||||
|
||||
## Basic install
|
||||
|
||||
```bash
|
||||
uv sync
|
||||
```
|
||||
|
||||
This installs all core dependencies defined in `pyproject.toml`.
|
||||
|
||||
## All extras at once
|
||||
|
||||
The recommended way to install for most users:
|
||||
|
||||
```bash
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
This installs all optional extras (flash-attn, flash-attn-cute, etc.) in one go.
|
||||
|
||||
## FP8 inference with deep-gemm
|
||||
|
||||
For certain models like GLM-5-FP8, you need `deep-gemm`. Install it via the `fp8-inference` dependency group:
|
||||
|
||||
```bash
|
||||
uv sync --group fp8-inference
|
||||
```
|
||||
|
||||
This installs the pre-built `deep-gemm` wheel. No CUDA build step is needed.
|
||||
|
||||
## Dev dependencies
|
||||
|
||||
```bash
|
||||
uv sync --group dev
|
||||
```
|
||||
|
||||
Installs pytest, ruff, pre-commit, and other development tools.
|
||||
|
||||
## Key files
|
||||
|
||||
- `pyproject.toml` — all dependencies, extras, and dependency groups
|
||||
- `uv.lock` — pinned lockfile (update with `uv sync --all-extras`)
|
||||
@@ -7,84 +7,6 @@ from prime_rl.configs.shared import BaseModelConfig
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, get_all_fields
|
||||
from prime_rl.utils.utils import rgetattr, rsetattr
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
# GLM-4.5
|
||||
"zai-org/GLM-4.5": "glm45",
|
||||
"zai-org/GLM-4.5-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Base": "glm45",
|
||||
"zai-org/GLM-4.5-Air": "glm45",
|
||||
"zai-org/GLM-4.5-Air-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Air-Base": "glm45",
|
||||
"zai-org/GLM-4.5V": "glm45",
|
||||
"zai-org/GLM-4.5V-FP8": "glm45",
|
||||
# GLM-4.7
|
||||
"zai-org/GLM-4.7": "glm47",
|
||||
"zai-org/GLM-4.7-FP8": "glm47",
|
||||
"zai-org/GLM-4.7-Flash": "glm47",
|
||||
# MiniMax M2
|
||||
"MiniMaxAI/MiniMax-M2": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
|
||||
# INTELLECT-3
|
||||
"PrimeIntellect/INTELLECT-3": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3.1": "hermes",
|
||||
# Qwen3 dense
|
||||
"Qwen/Qwen3-0.6B": "hermes",
|
||||
"Qwen/Qwen3-0.6B-Base": "hermes",
|
||||
"Qwen/Qwen3-0.6B-FP8": "hermes",
|
||||
"Qwen/Qwen3-1.7B": "hermes",
|
||||
"Qwen/Qwen3-1.7B-Base": "hermes",
|
||||
"Qwen/Qwen3-1.7B-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B": "hermes",
|
||||
"Qwen/Qwen3-4B-Base": "hermes",
|
||||
"Qwen/Qwen3-4B-FP8": "hermes",
|
||||
"Qwen/Qwen3-8B": "hermes",
|
||||
"Qwen/Qwen3-8B-Base": "hermes",
|
||||
"Qwen/Qwen3-8B-FP8": "hermes",
|
||||
"Qwen/Qwen3-14B": "hermes",
|
||||
"Qwen/Qwen3-14B-Base": "hermes",
|
||||
"Qwen/Qwen3-14B-FP8": "hermes",
|
||||
"Qwen/Qwen3-32B": "hermes",
|
||||
"Qwen/Qwen3-32B-FP8": "hermes",
|
||||
# Qwen3 MoE
|
||||
"Qwen/Qwen3-30B-A3B": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Base": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
|
||||
# Qwen3 2507
|
||||
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
|
||||
# Qwen3-Next
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
|
||||
# Qwen3-Coder
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
|
||||
# Qwen3-Coder-Next
|
||||
"Qwen/Qwen3-Coder-Next": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-Base": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
|
||||
# Qwen3.5
|
||||
"Qwen/Qwen3.5-397B-A17B": "hermes",
|
||||
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
|
||||
}
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
|
||||
|
||||
@@ -148,19 +70,11 @@ class ModelConfig(BaseModelConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
enable_auto_tool_choice: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`. "
|
||||
"Automatically set to True when tool_call_parser is configured.",
|
||||
),
|
||||
] = False
|
||||
|
||||
tool_call_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
|
||||
"If not set, automatically inferred from the model name.",
|
||||
'Set to "auto" to infer from the model name.',
|
||||
),
|
||||
] = None
|
||||
|
||||
@@ -178,18 +92,6 @@ class ModelConfig(BaseModelConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_tool_call_parser(self):
|
||||
if self.tool_call_parser is None:
|
||||
parser = MODEL_TOOL_CALL_PARSER.get(self.name)
|
||||
if parser is not None:
|
||||
self.tool_call_parser = parser
|
||||
|
||||
if self.tool_call_parser is not None:
|
||||
self.enable_auto_tool_choice = True
|
||||
|
||||
return self
|
||||
|
||||
|
||||
class WeightBroadcastConfig(BaseSettings):
|
||||
"""Configures weight broadcast settings."""
|
||||
@@ -354,7 +256,6 @@ class InferenceConfig(BaseSettings):
|
||||
"model.max_model_len": "max_model_len",
|
||||
"model.enforce_eager": "enforce_eager",
|
||||
"model.trust_remote_code": "trust_remote_code",
|
||||
"model.enable_auto_tool_choice": "enable_auto_tool_choice",
|
||||
"model.tool_call_parser": "tool_call_parser",
|
||||
"model.reasoning_parser": "reasoning_parser",
|
||||
"model.rope_scaling": "rope_scaling",
|
||||
|
||||
@@ -746,15 +746,44 @@ class OrchestratorConfig(BaseSettings):
|
||||
),
|
||||
] = None
|
||||
|
||||
batch_size: Annotated[int, Field(ge=1, description="Number of samples to train on per step.")] = 128
|
||||
|
||||
oversampling_factor: Annotated[
|
||||
float,
|
||||
batch_size: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Factor by which to oversample the batch. Will lead to more in-flight group rollout requests at the same time.",
|
||||
description="Number of samples to train on per step (rollout-based batching). Set this OR token_batch_size.",
|
||||
),
|
||||
] = 1.0
|
||||
] = None
|
||||
|
||||
token_batch_size: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Number of tokens to train on per step (token-based batching). Set this OR batch_size.",
|
||||
),
|
||||
] = None
|
||||
|
||||
oversampling_factor: Annotated[
|
||||
float | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Rollout-mode batching only. Multiplier used to derive max_inflight_rollouts from batch_size "
|
||||
"when max_inflight_rollouts is unset."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
max_inflight_rollouts: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Maximum number of rollouts to keep in-flight. Required for token-based batching. "
|
||||
"If batch_size is set and this is unset, defaults to batch_size * oversampling_factor "
|
||||
"(or batch_size when oversampling_factor is unset)."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
rollouts_per_example: Annotated[
|
||||
int,
|
||||
@@ -848,9 +877,35 @@ class OrchestratorConfig(BaseSettings):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_batch_size(self):
|
||||
if self.batch_size % self.rollouts_per_example != 0:
|
||||
raise ValueError("Batch size must be divisible by the number of samples per problem")
|
||||
def resolve_batching(self):
|
||||
has_rollout_batch = self.batch_size is not None
|
||||
has_token_batch = self.token_batch_size is not None
|
||||
|
||||
if has_rollout_batch and has_token_batch:
|
||||
raise ValueError("Set exactly one of batch_size or token_batch_size")
|
||||
|
||||
if not has_rollout_batch and not has_token_batch:
|
||||
self.batch_size = 128
|
||||
|
||||
if has_token_batch:
|
||||
if self.oversampling_factor is not None:
|
||||
raise ValueError("oversampling_factor can only be set when batch_size is set")
|
||||
if self.max_inflight_rollouts is None:
|
||||
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
|
||||
else:
|
||||
assert self.batch_size is not None
|
||||
if self.batch_size % self.rollouts_per_example != 0:
|
||||
raise ValueError("Batch size must be divisible by the number of samples per problem")
|
||||
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
|
||||
expected_max_inflight_rollouts = int(self.batch_size * self.oversampling_factor)
|
||||
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
|
||||
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
|
||||
if self.max_inflight_rollouts is None:
|
||||
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
|
||||
self.max_inflight_rollouts = int(self.batch_size * oversampling_factor)
|
||||
|
||||
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.rollouts_per_example:
|
||||
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -428,9 +428,6 @@ class RLConfig(BaseSettings):
|
||||
self.orchestrator.model.name = self.model.name
|
||||
if self.inference is not None:
|
||||
self.inference.model.name = self.model.name
|
||||
self.inference.model.tool_call_parser = None
|
||||
self.inference.model.enable_auto_tool_choice = False
|
||||
self.inference.model.resolve_tool_call_parser()
|
||||
|
||||
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
@@ -275,7 +276,7 @@ class ModelConfig(BaseModelConfig):
|
||||
"The chunk size to use for the fused LM head. "
|
||||
"Three behaviors: "
|
||||
"(1) int >= 512: explicitly set chunk size for fused LM head; "
|
||||
"(2) 'auto': auto-enable (RL training auto-sets to 2048); "
|
||||
"(2) 'auto': auto-enable (RL training auto-sets to 8192); "
|
||||
"(3) 'disabled': explicitly disable fused LM head (use vanilla). "
|
||||
"Explicitly setting an integer value for this feature isn't supported for SFT training."
|
||||
),
|
||||
@@ -326,10 +327,16 @@ class ModelConfig(BaseModelConfig):
|
||||
def fused_lm_head_chunk_size_is_valid(self):
|
||||
if isinstance(self.fused_lm_head_chunk_size, int):
|
||||
low = 512
|
||||
warn_threshold = 8192
|
||||
if self.fused_lm_head_chunk_size < low:
|
||||
raise ValueError(
|
||||
f"Fused LM head chunk size must be at least {low}, got {self.fused_lm_head_chunk_size}"
|
||||
)
|
||||
if self.fused_lm_head_chunk_size < warn_threshold:
|
||||
warnings.warn(
|
||||
f"Fused LM head chunk size is set to {self.fused_lm_head_chunk_size}, which is less than the recommended threshold of {warn_threshold}. This may cause some runs to diverge due to numerical instability in floating point arithmetic."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -798,7 +805,7 @@ class TrainerConfig(BaseSettings):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_fused_lm_head_chunk_size(self):
|
||||
if self.model.fused_lm_head_chunk_size == "auto":
|
||||
self.model.fused_lm_head_chunk_size = 2048
|
||||
self.model.fused_lm_head_chunk_size = 8192
|
||||
|
||||
return self
|
||||
|
||||
|
||||
@@ -24,6 +24,92 @@ from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
# GLM-4.5
|
||||
"zai-org/GLM-4.5": "glm45",
|
||||
"zai-org/GLM-4.5-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Base": "glm45",
|
||||
"zai-org/GLM-4.5-Air": "glm45",
|
||||
"zai-org/GLM-4.5-Air-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Air-Base": "glm45",
|
||||
"zai-org/GLM-4.5V": "glm45",
|
||||
"zai-org/GLM-4.5V-FP8": "glm45",
|
||||
# GLM-4.7
|
||||
"zai-org/GLM-4.7": "glm47",
|
||||
"zai-org/GLM-4.7-FP8": "glm47",
|
||||
"zai-org/GLM-4.7-Flash": "glm47",
|
||||
# MiniMax M2
|
||||
"MiniMaxAI/MiniMax-M2": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
|
||||
# INTELLECT-3
|
||||
"PrimeIntellect/INTELLECT-3": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3.1": "hermes",
|
||||
# Qwen3 dense
|
||||
"Qwen/Qwen3-0.6B": "hermes",
|
||||
"Qwen/Qwen3-0.6B-Base": "hermes",
|
||||
"Qwen/Qwen3-0.6B-FP8": "hermes",
|
||||
"Qwen/Qwen3-1.7B": "hermes",
|
||||
"Qwen/Qwen3-1.7B-Base": "hermes",
|
||||
"Qwen/Qwen3-1.7B-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B": "hermes",
|
||||
"Qwen/Qwen3-4B-Base": "hermes",
|
||||
"Qwen/Qwen3-4B-FP8": "hermes",
|
||||
"Qwen/Qwen3-8B": "hermes",
|
||||
"Qwen/Qwen3-8B-Base": "hermes",
|
||||
"Qwen/Qwen3-8B-FP8": "hermes",
|
||||
"Qwen/Qwen3-14B": "hermes",
|
||||
"Qwen/Qwen3-14B-Base": "hermes",
|
||||
"Qwen/Qwen3-14B-FP8": "hermes",
|
||||
"Qwen/Qwen3-32B": "hermes",
|
||||
"Qwen/Qwen3-32B-FP8": "hermes",
|
||||
# Qwen3 MoE
|
||||
"Qwen/Qwen3-30B-A3B": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Base": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
|
||||
# Qwen3 2507
|
||||
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
|
||||
# Qwen3-Next
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
|
||||
# Qwen3-Coder
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
|
||||
# Qwen3-Coder-Next
|
||||
"Qwen/Qwen3-Coder-Next": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-Base": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
|
||||
# Qwen3.5
|
||||
"Qwen/Qwen3.5-397B-A17B": "hermes",
|
||||
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
|
||||
}
|
||||
|
||||
|
||||
def resolve_tool_call_parser(model_name: str, tool_call_parser: str | None) -> str | None:
|
||||
"""Resolve tool_call_parser from model name if set to "auto"."""
|
||||
if tool_call_parser == "auto":
|
||||
return MODEL_TOOL_CALL_PARSER.get(model_name)
|
||||
return tool_call_parser
|
||||
|
||||
|
||||
logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_hermes_tool_parser_thread_safety,
|
||||
@@ -233,15 +319,17 @@ def server(config: InferenceConfig, vllm_args: list[str]):
|
||||
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
|
||||
from vllm.entrypoints.openai.api_server import run_server
|
||||
|
||||
if config.model.tool_call_parser is not None:
|
||||
logger.info(f"Using tool_call_parser='{config.model.tool_call_parser}' for model '{config.model.name}'")
|
||||
|
||||
parser = FlexibleArgumentParser(description="vLLM OpenAI-Compatible RESTful API server.")
|
||||
parser = make_arg_parser(parser)
|
||||
args = parser.parse_args(args=vllm_args, namespace=config.to_vllm())
|
||||
assert args is not None
|
||||
validate_parsed_serve_args(args)
|
||||
|
||||
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
|
||||
args.enable_auto_tool_choice = args.tool_call_parser is not None
|
||||
if args.tool_call_parser is not None:
|
||||
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
|
||||
|
||||
# Set the worker extension class based on the broadcast backend
|
||||
args.worker_extension_cls = WORKER_EXTENSION_CLS[config.weight_broadcast.type]
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ async def evaluate_env(
|
||||
rollouts_per_example: int,
|
||||
max_retries: int,
|
||||
ckpt_step: int,
|
||||
step: int | None,
|
||||
step: int,
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]],
|
||||
):
|
||||
logger = get_logger()
|
||||
@@ -142,6 +142,6 @@ async def evaluate_env(
|
||||
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})
|
||||
eval_metrics.update({"progress/ckpt_step": ckpt_step, "step": step})
|
||||
monitor = get_monitor()
|
||||
monitor.log(eval_metrics, step=None)
|
||||
monitor.log(eval_metrics, step=step)
|
||||
|
||||
@@ -12,9 +12,9 @@ from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
import verifiers as vf
|
||||
from loguru import logger
|
||||
|
||||
from prime_rl.configs.orchestrator import FilterConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -173,7 +173,7 @@ def apply_filters(
|
||||
|
||||
if total_detected > 0:
|
||||
enforced_msg = f", enforced {total_enforced}" if total_enforced > 0 else ""
|
||||
logger.info(
|
||||
get_logger().info(
|
||||
f"Detected {total_detected}/{n} rollouts "
|
||||
f"({', '.join(f'{name}={c}' for name, c in counts.items() if c > 0)})" + enforced_msg
|
||||
)
|
||||
|
||||
@@ -268,7 +268,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
env=train_env_group,
|
||||
buffer=buffer,
|
||||
inference_pool=inference_pool,
|
||||
oversampling_factor=config.oversampling_factor,
|
||||
max_inflight_rollouts=config.max_inflight_rollouts,
|
||||
max_async_level=config.max_async_level,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
strict_async_level=config.strict_async_level,
|
||||
@@ -338,9 +338,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
is_first_step = True
|
||||
await set_semaphore(config.max_concurrent or -1)
|
||||
|
||||
# Start update policy loop
|
||||
update_policy_task = asyncio.create_task(scheduler.update_policy_loop())
|
||||
|
||||
# Track consecutive empty batches for retry logic
|
||||
empty_batch_retries = 0
|
||||
max_empty_batch_retries = 5
|
||||
@@ -355,13 +352,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
reason = evicted_path.read_text().strip()
|
||||
raise RuntimeError(f"Run evicted by trainer: {reason}")
|
||||
|
||||
# Check if update_policy_task has failed and propagate the exception
|
||||
if update_policy_task.done():
|
||||
# End all other tasks
|
||||
for task in asyncio.all_tasks():
|
||||
task.cancel()
|
||||
update_policy_task.result() # Raises if the task failed
|
||||
# Capture ckpt_step once for consistency (it's updated by update_policy_loop concurrently)
|
||||
# Capture ckpt_step once for consistency (it's updated inside the scheduler)
|
||||
ckpt_step = scheduler.ckpt_step
|
||||
|
||||
# Save checkpoint (if we are at an interval step and not at the first or last step)
|
||||
@@ -403,7 +394,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# For heavy eval workloads, it might be necessary additionally cancel in-flight training rollouts
|
||||
if config.eval.cancel_inflight_rollouts_on_eval:
|
||||
logger.info("Cancelling in-flight training rollouts before starting evals to avoid congestion.")
|
||||
scheduler.cancel_inflight_rollouts()
|
||||
await scheduler.cancel_inflight_rollouts()
|
||||
|
||||
results = await asyncio.gather(
|
||||
*[
|
||||
@@ -460,6 +451,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Compute advantages
|
||||
example_ids = [r["example_id"] for r in train_rollouts]
|
||||
num_rollouts = len(train_rollouts)
|
||||
num_unique_examples = len(set(example_ids))
|
||||
rewards = [r["reward"] for r in train_rollouts]
|
||||
completion_lens = [get_completion_len(r) for r in train_rollouts]
|
||||
advantages = compute_advantages(
|
||||
@@ -471,7 +464,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Convert rollouts to training samples
|
||||
parallel_preprocess_start = time.perf_counter()
|
||||
num_unique_examples = len(set(example_ids))
|
||||
|
||||
# VLM: build image cache for efficient batched preprocessing
|
||||
if is_vlm:
|
||||
@@ -607,8 +599,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Update progress metrics and throughput
|
||||
num_tokens = int(results_df.seq_len.sum())
|
||||
progress.total_tokens += num_tokens
|
||||
progress.total_samples += config.batch_size
|
||||
progress.total_problems += config.batch_size // config.rollouts_per_example
|
||||
progress.total_samples += num_rollouts
|
||||
progress.total_problems += num_unique_examples
|
||||
throughput = num_tokens / generate_completions_time
|
||||
|
||||
# Compute solve all and none tensors
|
||||
@@ -624,8 +616,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"progress/tokens": num_tokens,
|
||||
"progress/prefill_tokens": num_prefill_tokens,
|
||||
"progress/decode_tokens": num_decode_tokens,
|
||||
"progress/samples": config.batch_size,
|
||||
"progress/problems": config.batch_size // config.rollouts_per_example,
|
||||
"progress/samples": num_rollouts,
|
||||
"progress/problems": num_unique_examples,
|
||||
"progress/total_tokens": progress.total_tokens,
|
||||
"progress/total_samples": progress.total_samples,
|
||||
"progress/total_problems": progress.total_problems,
|
||||
@@ -728,7 +720,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
to_log.update({f"val_batch/{env}": ratio for env, ratio in per_env_ratio.items()})
|
||||
|
||||
# Log metrics to monitor(s)
|
||||
monitor.log(to_log)
|
||||
monitor.log(to_log, step=progress.step)
|
||||
|
||||
# Log samples to monitor(s) if enabled
|
||||
subset_train_rollouts = random.sample(train_rollouts, min(8, len(train_rollouts)))
|
||||
@@ -743,6 +735,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
step=progress.step,
|
||||
)
|
||||
|
||||
# Flush all accumulated metrics for this step
|
||||
monitor.flush(step=progress.step)
|
||||
|
||||
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Reward: {results_df.reward.mean():.4f} |{f' Val. Reward: {val_results_df.reward.mean():.4f} |' if val_results_df is not None else ''} Throughput: {throughput:.1f} tokens/s | Seq. Length: {results_df.groupby('example_id').seq_len.mean().mean():.1f} tokens/sample | Async Level: {scheduler.async_level} | Max. Off-Policy Level: {scheduler.max_off_policy_level}"
|
||||
logger.success(step_message)
|
||||
|
||||
@@ -792,8 +787,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
rollout_executor.shutdown(wait=False)
|
||||
|
||||
# Stop scheduler
|
||||
scheduler.cancel_inflight_rollouts()
|
||||
update_policy_task.cancel()
|
||||
await scheduler.stop()
|
||||
|
||||
# Stop inference pool
|
||||
await inference_pool.stop()
|
||||
|
||||
@@ -12,7 +12,8 @@ from aiolimiter import AsyncLimiter
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.utils import get_sampling_args
|
||||
from prime_rl.orchestrator.vf_utils import run_group
|
||||
from prime_rl.orchestrator.vf_utils import get_seq_len, run_group
|
||||
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import ProgressTracker, get_logger
|
||||
from prime_rl.utils.temp_scheduling import compute_temperature
|
||||
@@ -48,7 +49,7 @@ class Scheduler:
|
||||
inference_pool: InferencePool,
|
||||
buffer: Buffer,
|
||||
config: OrchestratorConfig,
|
||||
oversampling_factor: float,
|
||||
max_inflight_rollouts: int,
|
||||
max_async_level: int,
|
||||
max_off_policy_steps: int,
|
||||
strict_async_level: bool,
|
||||
@@ -65,9 +66,11 @@ class Scheduler:
|
||||
self.buffer = buffer
|
||||
self.config = config
|
||||
self.batch_size = config.batch_size
|
||||
self.token_batch_size = config.token_batch_size
|
||||
self.rollouts_per_example = config.rollouts_per_example
|
||||
self.seq_len = config.seq_len
|
||||
self.problems_per_batch = int(oversampling_factor * self.batch_size // self.rollouts_per_example)
|
||||
self.max_inflight_rollouts = max_inflight_rollouts
|
||||
self.max_inflight_group_rollouts = max(1, self.max_inflight_rollouts // self.rollouts_per_example)
|
||||
self.max_async_level = max_async_level
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
self.strict_async_level = strict_async_level
|
||||
@@ -91,16 +94,37 @@ class Scheduler:
|
||||
self.cancelled_rollouts_count = 0
|
||||
self.last_batch_generation_time = 0.0
|
||||
|
||||
@property
|
||||
def uses_token_batching(self) -> bool:
|
||||
return self.token_batch_size is not None
|
||||
|
||||
@property
|
||||
def batch_target(self) -> int:
|
||||
if self.uses_token_batching:
|
||||
assert self.token_batch_size is not None
|
||||
return self.token_batch_size
|
||||
assert self.batch_size is not None
|
||||
return self.batch_size
|
||||
|
||||
def get_batch_progress_increment(self, rollouts: list[vf.RolloutOutput]) -> int:
|
||||
if self.uses_token_batching:
|
||||
return sum(get_seq_len(rollout) for rollout in rollouts)
|
||||
return len(rollouts)
|
||||
|
||||
def finalize_batch_rollouts(self, rollouts: list[vf.RolloutOutput]) -> list[vf.RolloutOutput]:
|
||||
if self.batch_size is None:
|
||||
return rollouts
|
||||
return rollouts[: self.batch_size]
|
||||
|
||||
def set_sampling_args(self, sampling_args: dict) -> None:
|
||||
"""Update sampling args for future rollout requests."""
|
||||
self.sampling_args = sampling_args
|
||||
|
||||
def cancel_inflight_rollouts(self):
|
||||
async def cancel_inflight_rollouts(self):
|
||||
"""Cancel all in-flight rollout requests."""
|
||||
count = len(self.inflight_group_rollouts)
|
||||
for future in list(self.inflight_group_rollouts.keys()):
|
||||
if not future.done():
|
||||
future.cancel()
|
||||
await safe_cancel(future)
|
||||
self.inflight_group_rollouts.clear()
|
||||
self.cancelled_rollouts_count += count
|
||||
|
||||
@@ -135,10 +159,10 @@ class Scheduler:
|
||||
async def update_policy_loop(self):
|
||||
"""Continuously checks for new policy checkpoints."""
|
||||
while True:
|
||||
await self.update_policy()
|
||||
await self.maybe_update_policy()
|
||||
await asyncio.sleep(1)
|
||||
|
||||
async def update_policy(self):
|
||||
async def maybe_update_policy(self):
|
||||
"""Updates the policy to the latest available checkpoint. Aborts rollout requests that are older than the max retention steps."""
|
||||
latest_ckpt_step = get_latest_ckpt_step(get_broadcast_dir(self.config.output_dir)) or 0
|
||||
async_away_ckpt_step = max(self.step - self.max_async_level, 0)
|
||||
@@ -177,33 +201,22 @@ class Scheduler:
|
||||
|
||||
self.checkpoint_ready.set()
|
||||
|
||||
# Handle off-policy tracking - cancel old requests
|
||||
tasks_to_remove = []
|
||||
tasks_to_update = []
|
||||
|
||||
for task, info in self.inflight_group_rollouts.items():
|
||||
if info.off_policy_steps > self.max_off_policy_steps:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
tasks_to_remove.append((task, info.client_config))
|
||||
# Cancel stale rollouts and bump off-policy step for the rest
|
||||
cancelled = []
|
||||
updated = {}
|
||||
for task, info in list(self.inflight_group_rollouts.items()):
|
||||
new_off_policy_steps = info.off_policy_steps + 1
|
||||
if new_off_policy_steps > self.max_off_policy_steps:
|
||||
cancelled.append(task)
|
||||
else:
|
||||
tasks_to_update.append((task, info.off_policy_steps + 1, info.client_config))
|
||||
updated[task] = InflightRolloutInfo(new_off_policy_steps, info.client_config)
|
||||
self.inflight_group_rollouts = updated
|
||||
await safe_cancel_all(cancelled)
|
||||
self.cancelled_rollouts_count += len(cancelled)
|
||||
|
||||
# Remove cancelled
|
||||
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 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, client_config=client_config
|
||||
)
|
||||
|
||||
if len(tasks_to_remove) > 0:
|
||||
if len(cancelled) > 0:
|
||||
self.logger.warning(
|
||||
f"Cancelled {len(tasks_to_remove)} old rollout requests (will refill naturally). Consider increasing max_off_policy_steps to avoid this."
|
||||
f"Cancelled {len(cancelled)} group rollout requests because they would be generated by >{self.max_off_policy_steps} policy versions. These requests will refill naturally. To avoid cancellation, consider increasing max_off_policy_steps."
|
||||
)
|
||||
|
||||
self.ckpt_step = next_ckpt_step
|
||||
@@ -211,19 +224,29 @@ class Scheduler:
|
||||
async def generate_batch(self, step: int) -> list[vf.RolloutOutput]:
|
||||
"""Continuously generates a batch of rollouts."""
|
||||
self.step = step
|
||||
|
||||
# Cancel the previous update policy task to avoid concurrent updates
|
||||
if self.update_policy_task is not None:
|
||||
await safe_cancel(self.update_policy_task)
|
||||
|
||||
# Manually check the async barrier before starting the step, the re-create the update policy loop
|
||||
# This ensures that we respect max_async_level, while still listening for policy updates mid-step
|
||||
await self.maybe_update_policy()
|
||||
self.update_policy_task = asyncio.create_task(self.update_policy_loop())
|
||||
|
||||
batch_start_time = time.perf_counter()
|
||||
|
||||
# Schedule initial tasks
|
||||
self.logger.debug("Starting to generate batch rollouts")
|
||||
while len(self.inflight_group_rollouts) < self.problems_per_batch:
|
||||
await self.schedule_group_rollout()
|
||||
|
||||
batch_rollouts: list[vf.RolloutOutput] = []
|
||||
batch_progress = 0
|
||||
pbar = ProgressTracker(
|
||||
total=self.config.batch_size, desc="Generating rollouts (train)", json_logging=self.json_logging, step=step
|
||||
total=self.batch_target, desc="Generating rollouts (train)", json_logging=self.json_logging, step=step
|
||||
)
|
||||
|
||||
while len(batch_rollouts) < self.config.batch_size:
|
||||
while batch_progress < self.batch_target:
|
||||
# Fill up
|
||||
while len(self.inflight_group_rollouts) < self.max_inflight_group_rollouts:
|
||||
await self.schedule_group_rollout()
|
||||
|
||||
# Wait for at least one future to complete
|
||||
finished_tasks, _ = await asyncio.wait(
|
||||
self.inflight_group_rollouts.keys(),
|
||||
@@ -233,8 +256,7 @@ class Scheduler:
|
||||
await self.checkpoint_ready.wait()
|
||||
|
||||
for finished_task in finished_tasks:
|
||||
if len(batch_rollouts) >= self.config.batch_size:
|
||||
batch_rollouts = batch_rollouts[: self.config.batch_size]
|
||||
if batch_progress >= self.batch_target:
|
||||
break
|
||||
|
||||
# Safely pop the future from tracking
|
||||
@@ -249,19 +271,27 @@ class Scheduler:
|
||||
accepted_rollouts = self.buffer.sample_rollouts(n=self.config.rollouts_per_example)
|
||||
|
||||
batch_rollouts.extend(accepted_rollouts)
|
||||
pbar.update(len(accepted_rollouts))
|
||||
progress_increment = self.get_batch_progress_increment(accepted_rollouts)
|
||||
batch_progress += progress_increment
|
||||
pbar.update(progress_increment)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
pass # Request was cancelled, will be rescheduled
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Rollout failed: {e}")
|
||||
|
||||
await self.schedule_group_rollout()
|
||||
batch_rollouts = self.finalize_batch_rollouts(batch_rollouts)
|
||||
|
||||
pbar.close()
|
||||
self.last_batch_generation_time = time.perf_counter() - batch_start_time
|
||||
return batch_rollouts
|
||||
|
||||
async def stop(self) -> None:
|
||||
await self.cancel_inflight_rollouts()
|
||||
if self.update_policy_task is not None:
|
||||
await safe_cancel(self.update_policy_task)
|
||||
self.update_policy_task = None
|
||||
|
||||
@property
|
||||
def max_off_policy_level(self) -> int:
|
||||
if not self.inflight_group_rollouts:
|
||||
|
||||
@@ -149,8 +149,8 @@ def interleave_rollout(
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def _extract_images_from_messages(messages: list) -> list[Image.Image]:
|
||||
"""Extract images from OpenAI-style chat messages."""
|
||||
def _extract_images_from_messages(messages: list) -> list[tuple[Image.Image, str]]:
|
||||
"""Extract (image, b64_key) pairs from OpenAI-style chat messages."""
|
||||
images = []
|
||||
if not messages or not isinstance(messages, list):
|
||||
return images
|
||||
@@ -165,79 +165,78 @@ def _extract_images_from_messages(messages: list) -> list[Image.Image]:
|
||||
b64_data = url.split(",", 1)[1]
|
||||
img_bytes = base64.b64decode(b64_data)
|
||||
img = Image.open(BytesIO(img_bytes))
|
||||
images.append(img)
|
||||
images.append((img, b64_data))
|
||||
return images
|
||||
|
||||
|
||||
def _extract_images_from_examples(
|
||||
examples: list[tuple[int, vf.RolloutOutput]],
|
||||
) -> tuple[list[Image.Image], dict[int, list[int]]]:
|
||||
) -> tuple[list[Image.Image], dict[int, list[list[int]]]]:
|
||||
"""
|
||||
Extract images from all trajectory steps of each example.
|
||||
|
||||
Parses OpenAI-style message content looking for image_url items with base64 data URLs
|
||||
(e.g., "data:image/png;base64,..."). Each trajectory step's prompt is cumulative (contains
|
||||
full conversation history), so we extract only the NEW images introduced in each step.
|
||||
Parses OpenAI-style message content looking for image_url items with base64 data URLs.
|
||||
Images are deduplicated across the batch by their base64 content. Each step records
|
||||
the indices of its images into the deduplicated all_images list.
|
||||
|
||||
Args:
|
||||
examples: List of (cache_key, output) tuples where output contains a "trajectory"
|
||||
list with steps that have "prompt" messages in OpenAI chat format.
|
||||
|
||||
Returns:
|
||||
Tuple of (all_images, images_per_step_per_example)
|
||||
- all_images: flat list of decoded PIL images, ordered by example then by step
|
||||
- images_per_step_per_example: dict mapping cache_key to list of cumulative image
|
||||
counts per step (e.g., [1, 2, 2] means 1 image after step 0, 2 after step 1, 2 after step 2)
|
||||
Tuple of (all_images, step_image_indices_per_example)
|
||||
- all_images: deduplicated flat list of decoded PIL images
|
||||
- step_image_indices_per_example: dict mapping cache_key to per-step lists of
|
||||
indices into all_images (e.g., [[0], [0, 1], [1]] for the decreasing-images case)
|
||||
"""
|
||||
all_images = []
|
||||
images_per_step_per_example = {}
|
||||
all_images: list[Image.Image] = []
|
||||
image_registry: dict[str, int] = {} # b64_key -> index in all_images
|
||||
step_image_indices_per_example: dict[int, list[list[int]]] = {}
|
||||
|
||||
for eid, output in examples:
|
||||
trajectory = output.get("trajectory", [])
|
||||
if not trajectory:
|
||||
images_per_step_per_example[eid] = []
|
||||
step_image_indices_per_example[eid] = []
|
||||
continue
|
||||
|
||||
example_images = []
|
||||
cumulative_counts = []
|
||||
|
||||
step_image_indices = []
|
||||
for step in trajectory:
|
||||
prompt = step.get("prompt")
|
||||
# Extract all images from this step's prompt (which is cumulative)
|
||||
step_images = _extract_images_from_messages(prompt)
|
||||
# Only take images beyond what we already have (new images in this step)
|
||||
new_images = step_images[len(example_images) :]
|
||||
example_images.extend(new_images)
|
||||
cumulative_counts.append(len(example_images))
|
||||
step_image_pairs = _extract_images_from_messages(prompt)
|
||||
indices = []
|
||||
for img, key in step_image_pairs:
|
||||
if key not in image_registry:
|
||||
image_registry[key] = len(all_images)
|
||||
all_images.append(img)
|
||||
indices.append(image_registry[key])
|
||||
step_image_indices.append(indices)
|
||||
|
||||
images_per_step_per_example[eid] = cumulative_counts
|
||||
all_images.extend(example_images)
|
||||
step_image_indices_per_example[eid] = step_image_indices
|
||||
|
||||
return all_images, images_per_step_per_example
|
||||
return all_images, step_image_indices_per_example
|
||||
|
||||
|
||||
def _preprocess_images_batched(
|
||||
images: list[Image.Image],
|
||||
images_per_step_per_example: dict[int, list[int]],
|
||||
step_image_indices_per_example: dict[int, list[list[int]]],
|
||||
processor,
|
||||
) -> dict[int, list[tuple[list | None, list | None]]]:
|
||||
"""
|
||||
Preprocess all images in a single batched call, then distribute results per step.
|
||||
|
||||
Args:
|
||||
images: Flat list of all PIL images
|
||||
images_per_step_per_example: Dict mapping cache_key to list of cumulative image
|
||||
counts per step
|
||||
images: Deduplicated flat list of all PIL images
|
||||
step_image_indices_per_example: Dict mapping cache_key to per-step lists of
|
||||
indices into images
|
||||
processor: HuggingFace processor with image_processor attribute
|
||||
|
||||
Returns:
|
||||
Dict mapping cache_key to list of (pixel_values, image_grid_thw) per step.
|
||||
Each step's entry contains cumulative images up to that step.
|
||||
"""
|
||||
if not images or processor is None:
|
||||
return {
|
||||
eid: [(None, None)] * len(counts) if counts else [(None, None)]
|
||||
for eid, counts in images_per_step_per_example.items()
|
||||
eid: [(None, None)] * max(len(step_indices), 1)
|
||||
for eid, step_indices in step_image_indices_per_example.items()
|
||||
}
|
||||
|
||||
image_sizes = [(img.width, img.height) for img in images]
|
||||
@@ -251,33 +250,27 @@ def _preprocess_images_batched(
|
||||
f"pixel_values={all_pixel_values.shape}, grid_thw={all_grid_thw.tolist()}"
|
||||
)
|
||||
|
||||
result = {}
|
||||
img_idx = 0
|
||||
patch_idx = 0
|
||||
# Pre-compute patch start offset for each image
|
||||
patch_starts = [0]
|
||||
for g in all_grid_thw:
|
||||
patch_starts.append(patch_starts[-1] + int(g[0] * g[1] * g[2]))
|
||||
|
||||
for eid, cumulative_counts in images_per_step_per_example.items():
|
||||
if not cumulative_counts or cumulative_counts[-1] == 0:
|
||||
result[eid] = [(None, None)] * max(len(cumulative_counts), 1)
|
||||
result = {}
|
||||
for eid, step_indices_list in step_image_indices_per_example.items():
|
||||
if not step_indices_list:
|
||||
result[eid] = [(None, None)]
|
||||
continue
|
||||
|
||||
total_images = cumulative_counts[-1]
|
||||
example_grids = all_grid_thw[img_idx : img_idx + total_images]
|
||||
num_patches = sum(int(g[0] * g[1] * g[2]) for g in example_grids)
|
||||
example_pixels = all_pixel_values[patch_idx : patch_idx + num_patches]
|
||||
|
||||
# Build per-step cumulative entries
|
||||
per_step = []
|
||||
for cum_count in cumulative_counts:
|
||||
if cum_count == 0:
|
||||
for indices in step_indices_list:
|
||||
if not indices:
|
||||
per_step.append((None, None))
|
||||
else:
|
||||
step_grids = example_grids[:cum_count]
|
||||
step_patches = sum(int(g[0] * g[1] * g[2]) for g in step_grids)
|
||||
per_step.append((example_pixels[:step_patches].tolist(), step_grids.tolist()))
|
||||
grids = all_grid_thw[indices]
|
||||
patches = sum([all_pixel_values[patch_starts[i] : patch_starts[i + 1]].tolist() for i in indices], [])
|
||||
per_step.append((patches, grids.tolist()))
|
||||
|
||||
result[eid] = per_step
|
||||
img_idx += total_images
|
||||
patch_idx += num_patches
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -274,10 +274,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
"reshard_after_forward": config.reshard_after_forward,
|
||||
}
|
||||
|
||||
if config.dp_replicate > 1:
|
||||
hsdp_mesh = parallel_dims.world_mesh["dp_replicate", "dp_shard_cp"]
|
||||
else:
|
||||
hsdp_mesh = parallel_dims.world_mesh["dp_shard_cp"]
|
||||
hsdp_mesh = parallel_dims.get_mesh("hsdp")
|
||||
|
||||
dp_mod_ep_mesh: DeviceMesh | None = None
|
||||
if parallel_dims.ep_enabled:
|
||||
@@ -580,7 +577,7 @@ def apply_ep(model: nn.Module, parallel_dims: ParallelDims):
|
||||
if isinstance(transformer_block.mlp, MoE):
|
||||
parallelize_module(
|
||||
transformer_block.mlp.experts,
|
||||
device_mesh=parallel_dims.world_mesh["ep"],
|
||||
device_mesh=parallel_dims.get_mesh("ep"),
|
||||
parallelize_plan=ExpertParallel(),
|
||||
)
|
||||
|
||||
|
||||
@@ -233,7 +233,7 @@ def _create_muon_optimizer(
|
||||
param_groups.append(dict(params=adamw_params, algorithm="adamw", lr=lr, weight_decay=config.weight_decay))
|
||||
|
||||
if parallel_dims.dp_shard_enabled or parallel_dims.cp_enabled:
|
||||
distributed_mesh = parallel_dims.world_mesh["dp_shard_cp"]
|
||||
distributed_mesh = parallel_dims.get_mesh("dp_shard_cp")
|
||||
else:
|
||||
distributed_mesh = parallel_dims.world_mesh
|
||||
|
||||
|
||||
@@ -43,8 +43,10 @@ class ParallelDims:
|
||||
world_size: int
|
||||
|
||||
_world_mesh: DeviceMesh = None
|
||||
_submeshes: dict = None
|
||||
|
||||
def __post_init__(self):
|
||||
self._submeshes = {}
|
||||
self._validate()
|
||||
|
||||
def _validate(self):
|
||||
@@ -136,10 +138,19 @@ class ParallelDims:
|
||||
dp_cp_mesh_dim_names.append("cp")
|
||||
ep_mesh_dim_names.append("cp")
|
||||
|
||||
mesh[tuple(dp_mesh_dim_names)]._flatten(mesh_dim_name="dp")
|
||||
mesh[tuple(dp_shard_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_shard_cp")
|
||||
mesh[tuple(dp_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_cp")
|
||||
mesh[tuple(ep_mesh_dim_names)]._flatten(mesh_dim_name="ep")
|
||||
self._submeshes["dp"] = mesh[tuple(dp_mesh_dim_names)]._flatten(mesh_dim_name="dp")
|
||||
self._submeshes["dp_shard_cp"] = mesh[tuple(dp_shard_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_shard_cp")
|
||||
self._submeshes["dp_cp"] = mesh[tuple(dp_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_cp")
|
||||
self._submeshes["ep"] = mesh[tuple(ep_mesh_dim_names)]._flatten(mesh_dim_name="ep")
|
||||
|
||||
if self.dp_replicate_enabled:
|
||||
parent = mesh[tuple(["dp_replicate"] + dp_shard_cp_mesh_dim_names)]
|
||||
hsdp_tensor = parent.mesh.reshape(self.dp_replicate, -1)
|
||||
self._submeshes["hsdp"] = DeviceMesh(
|
||||
device_type, hsdp_tensor, mesh_dim_names=("dp_replicate", "dp_shard_cp")
|
||||
)
|
||||
else:
|
||||
self._submeshes["hsdp"] = self._submeshes["dp_shard_cp"]
|
||||
|
||||
return mesh
|
||||
|
||||
@@ -177,11 +188,22 @@ class ParallelDims:
|
||||
dp_cp_mesh_dim_names.append("cp")
|
||||
|
||||
if dp_mesh_dim_names != []:
|
||||
mesh[tuple(dp_mesh_dim_names)]._flatten(mesh_dim_name="dp")
|
||||
self._submeshes["dp"] = mesh[tuple(dp_mesh_dim_names)]._flatten(mesh_dim_name="dp")
|
||||
if dp_shard_cp_mesh_dim_names != []:
|
||||
mesh[tuple(dp_shard_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_shard_cp")
|
||||
self._submeshes["dp_shard_cp"] = mesh[tuple(dp_shard_cp_mesh_dim_names)]._flatten(
|
||||
mesh_dim_name="dp_shard_cp"
|
||||
)
|
||||
if dp_cp_mesh_dim_names != []:
|
||||
mesh[tuple(dp_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_cp")
|
||||
self._submeshes["dp_cp"] = mesh[tuple(dp_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_cp")
|
||||
|
||||
if self.dp_replicate_enabled:
|
||||
parent = mesh[tuple(["dp_replicate"] + dp_shard_cp_mesh_dim_names)]
|
||||
hsdp_tensor = parent.mesh.reshape(self.dp_replicate, -1)
|
||||
self._submeshes["hsdp"] = DeviceMesh(
|
||||
device_type, hsdp_tensor, mesh_dim_names=("dp_replicate", "dp_shard_cp")
|
||||
)
|
||||
else:
|
||||
self._submeshes["hsdp"] = self._submeshes["dp_shard_cp"]
|
||||
|
||||
return mesh
|
||||
|
||||
@@ -193,6 +215,12 @@ class ParallelDims:
|
||||
self._world_mesh = self.build_mesh()
|
||||
return self._world_mesh
|
||||
|
||||
def get_mesh(self, name: str) -> DeviceMesh:
|
||||
mesh = self.world_mesh # ensure lazy init has run
|
||||
if name in self._submeshes:
|
||||
return self._submeshes[name]
|
||||
return mesh[name]
|
||||
|
||||
@property
|
||||
def dp_enabled(self):
|
||||
return self.dp_replicate > 1 or self.dp_shard > 1
|
||||
|
||||
@@ -191,12 +191,12 @@ def train(config: TrainerConfig):
|
||||
# Set up the data loader (Optionally, use a fake data loader for debugging)
|
||||
logger.info(f"Initializing data loader ({config.data})")
|
||||
if config.data.fake:
|
||||
dataloader = FakeDataLoader(config.data.fake, config.model.seq_len, parallel_dims.world_mesh["dp"].size())
|
||||
dataloader = FakeDataLoader(config.data.fake, config.model.seq_len, parallel_dims.get_mesh("dp").size())
|
||||
else:
|
||||
dataloader = DataLoader(
|
||||
config.output_dir,
|
||||
progress.step,
|
||||
parallel_dims.world_mesh["dp"].size(),
|
||||
parallel_dims.get_mesh("dp").size(),
|
||||
config.model.seq_len,
|
||||
config.model.cp,
|
||||
tokenizer,
|
||||
@@ -468,7 +468,7 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Compute step metrics
|
||||
num_local_tokens = seq_len * batch_size
|
||||
num_tokens = parallel_dims.world_mesh["dp"].size() * num_local_tokens
|
||||
num_tokens = parallel_dims.get_mesh("dp").size() * num_local_tokens
|
||||
progress.total_tokens += num_tokens
|
||||
progress.total_samples += batch_size
|
||||
perf_counter = get_perf_counter(model, seq_len)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import asyncio
|
||||
|
||||
|
||||
async def safe_cancel(task: asyncio.Task) -> None:
|
||||
"""Safely cancels and awaits an asyncio.Task."""
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except BaseException:
|
||||
pass
|
||||
|
||||
|
||||
async def safe_cancel_all(tasks: list[asyncio.Task]) -> None:
|
||||
"""Safely cancels and awaits all asyncio.Tasks."""
|
||||
await asyncio.gather(*[safe_cancel(task) for task in tasks])
|
||||
@@ -31,6 +31,10 @@ class Monitor(ABC):
|
||||
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
||||
pass
|
||||
|
||||
def flush(self, step: int) -> None:
|
||||
"""Commit all accumulated metrics for the given step."""
|
||||
pass
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close any resources held by the monitor. Override in subclasses that need cleanup."""
|
||||
pass
|
||||
|
||||
@@ -54,6 +54,13 @@ class MultiMonitor(Monitor):
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to log distributions to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def flush(self, step: int) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
monitor.flush(step=step)
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to flush {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def close(self) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
|
||||
@@ -147,6 +147,11 @@ class WandbMonitor(Monitor):
|
||||
"""Log distributions (no-op for W&B)."""
|
||||
pass
|
||||
|
||||
def flush(self, step: int) -> None:
|
||||
if not self.is_master or not self.enabled:
|
||||
return
|
||||
wandb.log({}, step=step, commit=True)
|
||||
|
||||
def save_final_summary(self, filename: str = "final_summary.json") -> None:
|
||||
"""Save final summary to W&B table."""
|
||||
if not self.is_master or not self.enabled:
|
||||
|
||||
@@ -106,7 +106,7 @@ class BaseSettings(PydanticBaseSettings):
|
||||
|
||||
# Pydantic settings configuration
|
||||
model_config = SettingsConfigDict(
|
||||
env_prefix="PRIME_",
|
||||
env_prefix="PRIME_RL_",
|
||||
env_nested_delimiter="__",
|
||||
cli_parse_args=False,
|
||||
cli_kebab_case=True,
|
||||
|
||||
@@ -725,7 +725,7 @@ def test_extract_images_from_messages_single_image():
|
||||
messages = [_create_image_message(image_url)]
|
||||
images = _extract_images_from_messages(messages)
|
||||
assert len(images) == 1
|
||||
assert isinstance(images[0], Image.Image)
|
||||
assert isinstance(images[0][0], Image.Image)
|
||||
|
||||
|
||||
def test_extract_images_from_messages_multiple_images():
|
||||
@@ -762,7 +762,7 @@ def test_extract_images_from_examples_single_turn():
|
||||
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
|
||||
assert images_per_step == {1: [[0]]} # step 0 has image at index 0
|
||||
|
||||
|
||||
def test_extract_images_from_examples_multi_turn_new_image_each_turn():
|
||||
@@ -809,7 +809,7 @@ def test_extract_images_from_examples_multi_turn_new_image_each_turn():
|
||||
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
|
||||
assert images_per_step == {1: [[0], [0, 1]]} # step 0: [red], step 1: [red, green]
|
||||
|
||||
|
||||
def test_extract_images_from_examples_multi_turn_no_new_images():
|
||||
@@ -853,8 +853,68 @@ def test_extract_images_from_examples_multi_turn_no_new_images():
|
||||
|
||||
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
|
||||
assert len(all_images) == 1 # Only 1 unique image (deduped)
|
||||
assert images_per_step == {1: [[0], [0]]} # both steps reference the same image
|
||||
|
||||
|
||||
def test_extract_images_from_examples_step_with_fewer_images_than_prior_steps():
|
||||
"""Test that image counts reflect the prompt's actual images, not a monotonically increasing total.
|
||||
|
||||
When a later step's prompt contains fewer images than the cumulative total from prior steps
|
||||
(i.e. the prompt is not strictly cumulative), the count for that step should match
|
||||
the number of images actually present in that step's prompt.
|
||||
"""
|
||||
red_url = _create_test_image("red")
|
||||
green_url = _create_test_image("green")
|
||||
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
# Step 0: red only
|
||||
vf.TrajectoryStep(
|
||||
prompt=[_create_image_message(red_url)],
|
||||
completion=[],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 1: cumulative — red + green
|
||||
vf.TrajectoryStep(
|
||||
prompt=[_create_image_message(red_url), _create_image_message(green_url)],
|
||||
completion=[],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
# Step 2: only green — fewer images than cumulative total
|
||||
vf.TrajectoryStep(
|
||||
prompt=[_create_image_message(green_url)],
|
||||
completion=[],
|
||||
response=MagicMock(),
|
||||
tokens=MagicMock(),
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
_, images_per_step = _extract_images_from_examples([(1, output)])
|
||||
|
||||
# Step 0: [red] → index 0; Step 1: [red, green] → indices [0, 1]; Step 2: [green] → index [1]
|
||||
assert images_per_step == {1: [[0], [0, 1], [1]]}
|
||||
|
||||
|
||||
def test_vlm_image_cache_get_for_step():
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
|
||||
from prime_rl.configs.inference import ModelConfig
|
||||
from prime_rl.inference.vllm.server import resolve_tool_call_parser
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -32,10 +32,16 @@ from prime_rl.configs.inference import ModelConfig
|
||||
],
|
||||
)
|
||||
def test_auto_detect_tool_call_parser(model_name: str, expected_parser: str):
|
||||
config = ModelConfig(name=model_name)
|
||||
assert config.tool_call_parser == expected_parser
|
||||
assert resolve_tool_call_parser(model_name, "auto") == expected_parser
|
||||
|
||||
|
||||
def test_explicit_parser_overrides_auto_detect():
|
||||
config = ModelConfig(name="Qwen/Qwen3-4B-Instruct-2507", tool_call_parser="qwen3_xml")
|
||||
assert config.tool_call_parser == "qwen3_xml"
|
||||
def test_explicit_parser_not_overridden():
|
||||
assert resolve_tool_call_parser("Qwen/Qwen3-4B-Instruct-2507", "qwen3_xml") == "qwen3_xml"
|
||||
|
||||
|
||||
def test_auto_unknown_model():
|
||||
assert resolve_tool_call_parser("some/unknown-model", "auto") is None
|
||||
|
||||
|
||||
def test_none_skips_resolution():
|
||||
assert resolve_tool_call_parser("Qwen/Qwen3-0.6B", None) is None
|
||||
|
||||
@@ -562,6 +562,14 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl", hash = "sha256:d316bb415a2d9e2d2b3abcc4084c6502fc09240e292cd76a76afc106a1c8e04a", size = 9190, upload-time = "2025-02-24T04:41:32.565Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deep-gemm"
|
||||
version = "2.3.0+35c4bc8"
|
||||
source = { url = "https://github.com/hallerite/DeepGEMM/releases/download/v2.3.0/deep_gemm-2.3.0+35c4bc8-cp312-cp312-linux_x86_64.whl" }
|
||||
wheels = [
|
||||
{ url = "https://github.com/hallerite/DeepGEMM/releases/download/v2.3.0/deep_gemm-2.3.0+35c4bc8-cp312-cp312-linux_x86_64.whl", hash = "sha256:e335e99dffeee5a10e91f375d3e9a8ed348f144ffa56aebff1576b9a2b56b697" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "depyf"
|
||||
version = "0.20.0"
|
||||
@@ -2361,6 +2369,9 @@ dev = [
|
||||
{ name = "pytest" },
|
||||
{ name = "ruff" },
|
||||
]
|
||||
fp8-inference = [
|
||||
{ name = "deep-gemm" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
@@ -2395,7 +2406,7 @@ requires-dist = [
|
||||
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=609e3d5" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3f555af" },
|
||||
{ name = "vllm", url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" },
|
||||
{ name = "vllm", url = "https://vllm-wheels.s3.us-west-2.amazonaws.com/7a06e5b05b170d7da31845866da0a99fc65253a1/vllm-0.16.0rc3-cp38-abi3-manylinux_2_31_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.24.2" },
|
||||
]
|
||||
provides-extras = ["flash-attn", "flash-attn-3", "flash-attn-cute"]
|
||||
@@ -2408,6 +2419,7 @@ dev = [
|
||||
{ name = "pytest", specifier = ">=8.4.1" },
|
||||
{ name = "ruff", specifier = ">=0.12.1" },
|
||||
]
|
||||
fp8-inference = [{ name = "deep-gemm", url = "https://github.com/hallerite/DeepGEMM/releases/download/v2.3.0/deep_gemm-2.3.0+35c4bc8-cp312-cp312-linux_x86_64.whl" }]
|
||||
|
||||
[[package]]
|
||||
name = "prime-sandboxes"
|
||||
@@ -3788,8 +3800,8 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "vllm"
|
||||
version = "0.16.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" }
|
||||
version = "0.16.0rc3"
|
||||
source = { url = "https://vllm-wheels.s3.us-west-2.amazonaws.com/7a06e5b05b170d7da31845866da0a99fc65253a1/vllm-0.16.0rc3-cp38-abi3-manylinux_2_31_x86_64.whl" }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "anthropic" },
|
||||
@@ -3853,7 +3865,7 @@ dependencies = [
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl", hash = "sha256:5ef17c1fe6536eeb11b34a0174cf2831eaffa5cfecfaa729b2c43b0223dd97ab" },
|
||||
{ url = "https://vllm-wheels.s3.us-west-2.amazonaws.com/7a06e5b05b170d7da31845866da0a99fc65253a1/vllm-0.16.0rc3-cp38-abi3-manylinux_2_31_x86_64.whl", hash = "sha256:15cd8a86c2bbc736551ba72ac7c413127587e0c76bd42cdedb1799f729766124" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
|
||||
Reference in New Issue
Block a user