Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2b4f3f711 | ||
|
|
50aeb3c7d6 | ||
|
|
4beb553525 | ||
|
|
51dc60a895 | ||
|
|
a8f090b444 | ||
|
|
cdea189e3d | ||
|
|
d5f218f708 | ||
|
|
a03c70f55b | ||
|
|
e48a53853e | ||
|
|
f3c85a947a | ||
|
|
f19ba721a9 | ||
|
|
fd5db5df6a | ||
|
|
7b7c7efdfa | ||
|
|
2e2accb121 | ||
|
|
436873190d | ||
|
|
f0c339a234 | ||
|
|
9f425fffcb | ||
|
|
16efd8afda | ||
|
|
7d5f2d74a6 |
@@ -2,6 +2,8 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`[[orchestrator.train.env]].ratio` now defaults to `1` and no longer accepts unset/`None`**: Each train env's sampling weight defaults to `1` (equal weight per env) instead of `None`. The `None`-for-all-envs mode — which sampled proportional to each env's dataset size (the "natural task distribution") — is removed, along with the all-or-none constraint (any subset of envs may now set `ratio`; the rest default to `1`). Multi-env configs that relied on the old default now sample each env equally rather than proportional to dataset size; set each env's `ratio` explicitly to restore a proportional (or any other) mix. (2026-07-02)
|
||||
- **`orchestrator.algo.length_penalty` restructured to a single `linear` shape; `tokens`/`turns` length penalties removed**: The `grpo`-family length penalty keeps the `[orchestrator.algo.length_penalty]` key but is collapsed to a single `type = "linear"` shape; the discriminated `type = "tokens" | "turns"` efficiency-shaping variants (and the `efficiency_shaping` helper) are removed. The linear penalty subtracts a `pass_rate`-scaled penalty from each reward before the GRPO baseline, summing three terms — `num_output_tokens_weight` × output tokens, `num_input_tokens_weight` × input (non-output) tokens, and `num_turns_weight` × turns — each normalized by the group's own max for that quantity. Field renames within the penalty: `coef` → `num_output_tokens_weight` (default `0.25`), `context_coef` → `num_input_tokens_weight` (default `0.1`), `turns_coef` → `num_turns_weight` (default `0.1`); the `gate_by_correctness` flag is removed. `extra="forbid"` rejects the old keys, so existing configs must migrate. (2026-06-29)
|
||||
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
|
||||
- **Memory-saving defaults enabled**: `trainer.model.ac`, `trainer.model.ac_offloading`, `trainer.model.compile`, `trainer.model.optim_cpu_offload`, and `trainer.model.fused_lm_head_token_chunk_size` are now enabled by default to provide sane memory-efficient defaults out of the box. Specifically: `ac` defaults to `ActivationCheckpointConfig()` (full mode), `ac_offloading` defaults to `ActivationOffloadingConfig()`, `compile` defaults to `CompileConfig()` (`fullgraph=false`), `optim_cpu_offload` defaults to `true`, and `fused_lm_head_token_chunk_size` defaults to `1024`. SFT training silently disables `fused_lm_head_token_chunk_size` (sets it to `"disabled"`). Configs using `max_concurrent_runs > 1` must explicitly set `optim_cpu_offload = false`. To disable any of these, set the field to `None` / `"None"` / `false` / `"disabled"` as appropriate.
|
||||
- **`model.ep` defaults to `"auto"`**: The `ep` field type changed from `int` to `int | Literal["auto"]`, defaulting to `"auto"`. At trainer startup, `resolve_ep()` checks if the model is MoE (via `AutoConfig`); if so, it resolves to `min(fsdp_island_size, 8)` where `fsdp_island_size = world_size // dp_replicate`. For non-MoE models, `"auto"` resolves to 1 (no-op). Set `ep` to an explicit integer to override.
|
||||
|
||||
+10
-5
@@ -32,6 +32,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
|
||||
libnl-route-3-dev \
|
||||
libibverbs-dev \
|
||||
librdmacm-dev \
|
||||
python3.12 \
|
||||
python3.12-venv \
|
||||
python3.12-dev \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
ARG UCX_VERSION=1.19.1
|
||||
@@ -60,8 +64,13 @@ ADD https://astral.sh/uv/install.sh /uv-installer.sh
|
||||
# Set install dir to location accessible to non-root users
|
||||
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
ENV UV_PYTHON_INSTALL_DIR="/usr/local/share/uv/python"
|
||||
# Build .venv against the system CPython, so the venv's recorded interpreter
|
||||
# matches the runtime interpreter and no bin/python relink is needed at runtime.
|
||||
ENV UV_PYTHON_PREFERENCE=only-system
|
||||
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
|
||||
# Explicity set venv dir inside /app so to ensure it gets copied over during
|
||||
# the runtime stage's `COPY /app`
|
||||
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
|
||||
|
||||
# Install Python dependencies (The gradual copies help with caching)
|
||||
WORKDIR /app
|
||||
@@ -219,10 +228,6 @@ COPY --from=builder /opt/ucx /opt/ucx
|
||||
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
|
||||
RUN rm /app/.venv/bin/python && ln -s /usr/local/bin/python /app/.venv/bin/python
|
||||
RUN rm /app/.venv/bin/python3 && ln -s /usr/local/bin/python /app/.venv/bin/python3
|
||||
RUN rm /app/.venv/bin/python3.12 && ln -s /usr/local/bin/python /app/.venv/bin/python3.12
|
||||
|
||||
# Place executables in the environment at the front of the path
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
ENV UCX_HOME=/opt/ucx
|
||||
|
||||
@@ -23,7 +23,7 @@ max_completion_tokens = 64
|
||||
[[orchestrator.train.env]]
|
||||
name = "color-codeword"
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ max_completion_tokens = 64
|
||||
[[orchestrator.train.env]]
|
||||
name = "color-codeword"
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
|
||||
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
|
||||
|
||||
@@ -37,6 +37,6 @@ max_completion_tokens = 768
|
||||
[[orchestrator.train.env]]
|
||||
name = "alphabet-sort"
|
||||
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference] # Default inference config
|
||||
|
||||
@@ -42,7 +42,7 @@ name = "qwen3"
|
||||
[[orchestrator.train.env]]
|
||||
# v1 general-agent solver taskset; the tool server is colocated in the harness's modal sandbox.
|
||||
taskset = { id = "general-agent-v1", tools = { colocated = true } }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
@@ -23,7 +23,7 @@ max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
taskset = { id = "gsm8k-v1", split = "train" }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
@@ -34,7 +34,7 @@ max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
taskset = { id = "gsm8k-v1", split = "test" }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ max_inflight_rollouts = 256
|
||||
[[orchestrator.train.env]]
|
||||
name = "hendrycks-math"
|
||||
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
timeout = { scoring = 300 }
|
||||
|
||||
[orchestrator.eval]
|
||||
@@ -39,7 +39,7 @@ interval = 50
|
||||
[[orchestrator.eval.env]]
|
||||
name = "aime2024"
|
||||
taskset = { id = "aime24-v1" }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
timeout = { scoring = 300 }
|
||||
group_size = 32
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ max_completion_tokens = 128
|
||||
taskset = { id = "reverse-text-v1" }
|
||||
# reverse-text is a pure-text single-turn env: disable the bash tool (the model answers
|
||||
# directly) and use the subprocess runtime (no docker).
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
# No eval block, mirroring examples/reverse_text/rl.toml — this is a train-only
|
||||
# smoke. Add an [orchestrator.eval] block (with an interval) to exercise eval.
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the output-token, input-token, and turns coefficients all
|
||||
# set to 0.1. Each term is pass_rate-scaled and normalized by the group's own max before the GRPO
|
||||
# baseline subtraction.
|
||||
#
|
||||
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
|
||||
# CPU offload, and skip-gather / skip-optimizer checkpointing. Derived from
|
||||
# configs/debug/v1/scaleswe.toml + GLM-4.5-Air model settings from the int5 opencode configs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 65536
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/triton-cache-$USER-$SLURM_JOB_ID"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe"
|
||||
project_dir = "."
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
# Linear length penalty at coef 0.1 on all three terms (output tokens, input tokens, turns).
|
||||
[orchestrator.algo.length_penalty]
|
||||
num_output_tokens_weight = 0.1
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "scaleswe"
|
||||
taskset = { id = "scaleswe-v1" }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
skip_first_step = false
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm_cache_$(whoami)"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/flashinfer-$(whoami)"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -1,4 +1,4 @@
|
||||
# GLM-5.2-FP8 16-node P/D, FULL STACK: mooncake + llm-d router, vLLM 0.23.
|
||||
# GLM-5.2-FP8 16-node P/D, FULL STACK: mooncake + llm-d router, vLLM 0.24.
|
||||
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
|
||||
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
|
||||
#
|
||||
|
||||
Vendored
+1
-1
Submodule deps/research-environments updated: bae0ffe5ae...1ed93baeca
Vendored
+1
-1
Submodule deps/verifiers updated: 97be43bfce...22d6333a00
+3
-3
@@ -282,14 +282,14 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
|
||||
|
||||
This is intentionally simple — it does the right thing for most envs. Write a named algorithm class when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …) — see [Authoring an Algorithm](#authoring-an-algorithm).
|
||||
|
||||
Two built-in **length penalties** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling: `tokens` penalizes long completions by weighted token cost, `turns` penalizes long multi-turn rollouts by turn count.
|
||||
A **length penalty** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling. The `linear` penalty subtracts a single `pass_rate`-scaled penalty from each reward before the GRPO baseline, combining output tokens (`num_output_tokens_weight`), input / context tokens (`num_input_tokens_weight`), and turns (`num_turns_weight`) — each normalized by the group's own max for that quantity, with `num_input_tokens_weight` and `num_turns_weight` defaulting to `0.1`.
|
||||
|
||||
```toml
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "tokens"
|
||||
type = "linear"
|
||||
```
|
||||
|
||||
|
||||
@@ -312,7 +312,7 @@ class MyAlgorithm(Algorithm):
|
||||
rollout.assign_advantages(advantage)
|
||||
```
|
||||
|
||||
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask). Shared math like `efficiency_shaping` lives in `prime_rl.orchestrator.algo.advantage`.
|
||||
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask).
|
||||
|
||||
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Advantage-based filters and metrics derive from the streams (the zero-advantage filter checks for all-zero streams; logged distributions use per-rollout means). Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
|
||||
|
||||
|
||||
@@ -151,10 +151,11 @@ Training environments are an array of tables — set one per env, optionally wit
|
||||
id = "math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
ratio = 3 # 75% of batches
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
ratio = 0.25 # 25% of batches; remaining 75% goes to math-env
|
||||
ratio = 1 # default — 25% of batches
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math-env"
|
||||
@@ -162,6 +163,8 @@ name = "gsm8k-eval"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
```
|
||||
|
||||
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
|
||||
|
||||
`args` is forwarded verbatim to the environment's `load_environment(**args)`.
|
||||
|
||||
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
|
||||
|
||||
@@ -91,24 +91,22 @@ class SamplingConfig(BaseConfig):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
class LinearLengthPenaltyConfig(BaseConfig):
|
||||
"""Linear ``pass_rate``-scaled penalty subtracted from each reward before the GRPO baseline — the sum of three terms (completion tokens, input tokens, turns), each normalized by the group's own max for that quantity and disabled by setting its coefficient to 0."""
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
type: Literal["linear"] = "linear"
|
||||
|
||||
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
|
||||
num_output_tokens_weight: float = Field(0.25, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the output-token term. Each reward is reduced by ``num_output_tokens_weight * pass_rate * (rollout num_output_tokens / group's max num_output_tokens)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative; 0 disables the term."""
|
||||
|
||||
num_input_tokens_weight: float = Field(0.1, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the input-token term — tokens the model conditioned on but did not generate (``num_total_tokens - num_output_tokens``: prompts, tool responses), as a fraction of the group's max input tokens. 0 disables the term."""
|
||||
|
||||
num_turns_weight: float = Field(0.1, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the turns term (``pass_rate * (rollout num_turns / group's max num_turns)``). 0 disables the term."""
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
LengthPenaltyConfig: TypeAlias = LinearLengthPenaltyConfig
|
||||
|
||||
|
||||
class EchoRoleConfig(BaseConfig):
|
||||
@@ -199,7 +197,7 @@ class GRPOAlgoConfig(BaseAlgoConfig):
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
|
||||
"""Linear length penalty subtracted from each reward before the GRPO baseline (see ``LinearLengthPenaltyConfig``): a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max for that quantity. None disables it."""
|
||||
|
||||
|
||||
class EchoAlgoConfig(GRPOAlgoConfig):
|
||||
|
||||
@@ -337,10 +337,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class InferenceExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class InferenceConfig(BaseConfig):
|
||||
server: ServerConfig = ServerConfig()
|
||||
|
||||
@@ -436,8 +432,6 @@ class InferenceConfig(BaseConfig):
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: InferenceExperimentalConfig = InferenceExperimentalConfig()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_multi_node_requires_slurm(self):
|
||||
if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None:
|
||||
|
||||
@@ -50,7 +50,7 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
|
||||
class TrainSamplingConfig(BaseConfig):
|
||||
temperature: float = Field(1.0, ge=0)
|
||||
temperature: float = Field(1.0, ge=0, le=2.0)
|
||||
"""Sampling temperature."""
|
||||
|
||||
max_completion_tokens: int | None = Field(
|
||||
@@ -92,7 +92,7 @@ class TrainSamplingConfig(BaseConfig):
|
||||
|
||||
|
||||
class EvalSamplingConfig(BaseConfig):
|
||||
temperature: float | None = Field(None, ge=0)
|
||||
temperature: float | None = Field(None, ge=0, le=2.0)
|
||||
"""Sampling temperature. None defers to the inference server default."""
|
||||
|
||||
top_p: float | None = None
|
||||
@@ -157,11 +157,8 @@ class EnvConfig(vf.EnvServerConfig):
|
||||
address: str | None = None
|
||||
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
|
||||
|
||||
ratio: float | None = Field(None, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Times the env server retries a failed rollout before returning an error."""
|
||||
ratio: float = Field(1.0, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
@@ -193,9 +190,9 @@ class EnvConfig(vf.EnvServerConfig):
|
||||
def validate_env(self):
|
||||
if not self.taskset.id and not self.id:
|
||||
raise ValueError('no env configured — set taskset = { id = "<id>" } (v1) or id = "<id>" (v0/legacy)')
|
||||
if self.resolved_name == "all":
|
||||
if self.resolved_name == "agg":
|
||||
raise ValueError(
|
||||
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
|
||||
'Environment name "agg" is reserved for cross-env metric aggregation. Use a different name or id.'
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -248,13 +245,10 @@ class TrainConfig(BaseConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling and max_retries (the
|
||||
worker ``pool`` is configured per env, defaulting to elastic)."""
|
||||
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
|
||||
is configured per env, defaulting to elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
@@ -262,8 +256,6 @@ class TrainConfig(BaseConfig):
|
||||
else:
|
||||
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
|
||||
env.sampling = TrainSamplingConfig(**merged)
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -276,15 +268,6 @@ class TrainConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env_ratios(self):
|
||||
ratios = [env.ratio for env in self.env]
|
||||
if all(r is None for r in ratios):
|
||||
return self
|
||||
if any(r is None for r in ratios):
|
||||
raise ValueError("Either all envs must have a ratio or none of them. Got a mix of set and unset ratios.")
|
||||
return self
|
||||
|
||||
|
||||
class EvalConfig(BaseConfig):
|
||||
env: list[EvalEnvConfig] = Field(default_factory=list)
|
||||
@@ -299,9 +282,6 @@ class EvalConfig(BaseConfig):
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
"""Step interval at which to evaluate the model."""
|
||||
|
||||
@@ -311,7 +291,7 @@ class EvalConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, max_retries, num_examples,
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
|
||||
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
@@ -326,8 +306,6 @@ class EvalConfig(BaseConfig):
|
||||
env.group_size = self.group_size
|
||||
if "interval" not in env.model_fields_set:
|
||||
env.interval = self.interval
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -443,10 +421,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class OrchestratorExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class OrchestratorConfig(BaseConfig):
|
||||
algo: AlgoConfig = GRPOAlgoConfig()
|
||||
"""Training algorithm: sampling plus the per-token training signal (credit
|
||||
@@ -563,8 +537,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _env_to_train(cls, data: Any) -> Any:
|
||||
|
||||
@@ -46,10 +46,6 @@ from prime_rl.utils.validation import (
|
||||
)
|
||||
|
||||
|
||||
class RLExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
level: str | None = None
|
||||
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
|
||||
@@ -234,8 +230,6 @@ class RLConfig(BaseConfig):
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: RLExperimentalConfig = RLExperimentalConfig()
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -167,10 +167,6 @@ SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class SFTExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class SFTConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
@@ -226,7 +222,7 @@ class SFTConfig(BaseConfig):
|
||||
trace_path: Path | None = None
|
||||
"""Path to write the PyTorch profiler trace to."""
|
||||
|
||||
dist_timeout_seconds: int = 600
|
||||
dist_timeout_seconds: int = 3600
|
||||
"""Timeout in seconds for torch distributed ops."""
|
||||
|
||||
loss_impl: Literal["liger", "torch", "liger_fused", "quack_fused"] = "torch"
|
||||
@@ -243,8 +239,6 @@ class SFTConfig(BaseConfig):
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: SFTExperimentalConfig = SFTExperimentalConfig()
|
||||
|
||||
### Pre-validation normalization
|
||||
|
||||
@model_validator(mode="before")
|
||||
|
||||
@@ -554,7 +554,7 @@ class TrainerConfig(BaseConfig):
|
||||
trace_path: Path | None = None
|
||||
"""Path to write the PyTorch profiler trace to."""
|
||||
|
||||
dist_timeout_seconds: int = 600
|
||||
dist_timeout_seconds: int = 3600
|
||||
"""Timeout in seconds for torch distributed ops."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
@@ -38,19 +37,3 @@ def rsetattr(obj: Any, attr_path: str, value: Any) -> None:
|
||||
return setattr(obj, attr_path, value)
|
||||
parent_path, attr = attr_path.rsplit(".", 1)
|
||||
setattr(rgetattr(obj, parent_path), attr, value)
|
||||
|
||||
|
||||
def get_all_fields(model: BaseModel | type) -> list[str]:
|
||||
if isinstance(model, BaseModel):
|
||||
model_cls = model.__class__
|
||||
else:
|
||||
model_cls = model
|
||||
|
||||
fields = []
|
||||
for name, field in model_cls.model_fields.items():
|
||||
field_type = field.annotation
|
||||
fields.append(name)
|
||||
if field_type is not None and hasattr(field_type, "model_fields"):
|
||||
sub_fields = get_all_fields(field_type)
|
||||
fields.extend(f"{name}.{sub}" for sub in sub_fields)
|
||||
return fields
|
||||
|
||||
@@ -317,14 +317,11 @@ def validate_shared_weight_broadcast(
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
if (
|
||||
inference
|
||||
and trainer.weight_broadcast.type != orchestrator.weight_broadcast.type != inference.weight_broadcast.type
|
||||
):
|
||||
raise ValueError(
|
||||
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
|
||||
)
|
||||
elif trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
|
||||
if trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
|
||||
raise ValueError(
|
||||
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
|
||||
)
|
||||
if inference is not None and inference.weight_broadcast.type != trainer.weight_broadcast.type:
|
||||
raise ValueError(
|
||||
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
|
||||
)
|
||||
|
||||
+11
-6
@@ -19,7 +19,7 @@ dependencies = [
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers==5.6.2",
|
||||
"vllm>=0.23.0",
|
||||
"vllm>=0.24.0",
|
||||
"mooncake-transfer-engine>=0.3.10.post2",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
@@ -33,7 +33,7 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers>=0.1.15.dev404",
|
||||
"verifiers[harbor]>=0.1.15.dev411",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
@@ -54,7 +54,7 @@ orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
@@ -72,6 +72,7 @@ envs = [
|
||||
"alphabet-sort",
|
||||
"alphabet-sort-v1",
|
||||
"apex-shortlist-v1",
|
||||
"arxivmath-v1",
|
||||
"browsecomp-v1",
|
||||
"code-golf-v1",
|
||||
"color-codeword-v1",
|
||||
@@ -93,6 +94,7 @@ envs = [
|
||||
"logic-env",
|
||||
"longcot-mini-v1",
|
||||
"longcot-v1",
|
||||
"longpdfs-v1",
|
||||
"math-env",
|
||||
"math-env-v1",
|
||||
"math-python",
|
||||
@@ -112,6 +114,7 @@ envs = [
|
||||
"reverse-text",
|
||||
"reverse-text-v1",
|
||||
"rlm-search",
|
||||
"s1-deepresearch-v1",
|
||||
"scaleswe-v1",
|
||||
"simpleqa-v1",
|
||||
"simpleqa-verified-v1",
|
||||
@@ -174,7 +177,6 @@ dev = [
|
||||
# *without* the cooldown — bypassing this security policy.
|
||||
required-version = ">=0.11.1"
|
||||
exclude-newer = "7 days"
|
||||
preview = true
|
||||
no-build-isolation-package = ["flash-attn"]
|
||||
environments = [
|
||||
"sys_platform == 'linux' and platform_machine == 'x86_64'",
|
||||
@@ -245,6 +247,7 @@ aime26-v1 = { path = "deps/research-environments/environments/aime26_v1", editab
|
||||
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
|
||||
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
|
||||
apex-shortlist-v1 = { path = "deps/research-environments/environments/apex_shortlist_v1", editable = true }
|
||||
arxivmath-v1 = { path = "deps/research-environments/environments/arxivmath_v1", editable = true }
|
||||
browsecomp-v1 = { path = "deps/research-environments/environments/browsecomp_v1", editable = true }
|
||||
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
|
||||
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
|
||||
@@ -266,6 +269,7 @@ livecodebench-v1 = { path = "deps/research-environments/environments/livecodeben
|
||||
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
|
||||
longcot-mini-v1 = { path = "deps/research-environments/environments/longcot_mini_v1", editable = true }
|
||||
longcot-v1 = { path = "deps/research-environments/environments/longcot_v1", editable = true }
|
||||
longpdfs-v1 = { path = "deps/research-environments/environments/longpdfs_v1", editable = true }
|
||||
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
|
||||
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", editable = true }
|
||||
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
|
||||
@@ -285,6 +289,7 @@ redsearcher-v1 = { path = "deps/research-environments/environments/redsearcher_v
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
s1-deepresearch-v1 = { path = "deps/research-environments/environments/s1_deepresearch_v1", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_v1", editable = true }
|
||||
simpleqa-v1 = { path = "deps/research-environments/environments/simpleqa_v1", editable = true }
|
||||
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_v1", editable = true }
|
||||
@@ -310,8 +315,8 @@ dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
|
||||
+134
-226
@@ -3,20 +3,19 @@ import torch
|
||||
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
|
||||
|
||||
|
||||
def transformers_v5_compat():
|
||||
"""vLLM general plugin: patch transformers v5 config attrs that vLLM still expects.
|
||||
def apply_shared_vllm_patches():
|
||||
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
|
||||
|
||||
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
|
||||
in every vLLM process, including spawned workers.
|
||||
in every vLLM process, including spawned workers. Note vLLM swallows plugin
|
||||
load failures (``load_plugins_by_group`` logs and continues), so a broken
|
||||
entry-point target silently skips ALL of these patches.
|
||||
"""
|
||||
from transformers import Qwen3VLMoeTextConfig
|
||||
|
||||
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
_patch_lora_key_prefix()
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_qwen3_coder_param_newline_trim()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
@@ -100,6 +99,91 @@ def monkey_patch_nano_v3_reasoning_parser():
|
||||
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
|
||||
|
||||
|
||||
def monkey_patch_qwen3_coder_param_newline_trim():
|
||||
"""Restore vLLM 0.23's single-newline trim for qwen3_coder tool parameters.
|
||||
|
||||
vLLM 0.24's parser engine applies a full ``.strip()`` to every parameter
|
||||
value in ``_qwen3_arg_converter``; 0.23's ``Qwen3CoderToolParser`` trimmed
|
||||
exactly one leading and one trailing newline. A full strip corrupts
|
||||
whitespace-significant string parameters (str_replace-style
|
||||
``old_str``/``new_str``, file content with an indented first line, values
|
||||
with intentional trailing newlines), silently changing tool execution and
|
||||
rewards for agentic runs. Copy of ``_qwen3_arg_converter`` with only the
|
||||
trim changed. Also covers ``nemotron_v3``, which reuses ``qwen3_config``.
|
||||
"""
|
||||
import json
|
||||
|
||||
from vllm.parser import qwen3
|
||||
|
||||
def _trim_one_newline(value: str) -> str:
|
||||
if value.startswith("\n"):
|
||||
value = value[1:]
|
||||
if value.endswith("\n"):
|
||||
value = value[:-1]
|
||||
return value
|
||||
|
||||
def _patched_arg_converter(raw_args: str, partial: bool) -> str:
|
||||
params: dict[str, object] = {}
|
||||
|
||||
for match in qwen3._PARAM_RE.finditer(raw_args):
|
||||
name = match.group(1)
|
||||
value = match.group(2)
|
||||
## START PATCHED CODE (upstream: value.strip())
|
||||
params[name] = _trim_one_newline(value)
|
||||
## END PATCHED CODE
|
||||
|
||||
if partial:
|
||||
remaining = qwen3._PARAM_RE.sub("", raw_args)
|
||||
m = qwen3._PARTIAL_PARAM_RE.search(remaining)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
value = m.group(2)
|
||||
if name:
|
||||
## START PATCHED CODE (upstream: value.strip())
|
||||
params[name] = _trim_one_newline(value)
|
||||
## END PATCHED CODE
|
||||
|
||||
return json.dumps(params, ensure_ascii=False)
|
||||
|
||||
qwen3._qwen3_arg_converter = _patched_arg_converter
|
||||
# qwen3_config captures the converter when first built; drop any cached configs.
|
||||
qwen3.qwen3_config.cache_clear()
|
||||
|
||||
|
||||
def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
"""Keep the literal ``</think>`` in MiniMax-M2 content on tool-calling turns.
|
||||
|
||||
prime-rl serves MiniMax-M2 with ``reasoning=minimax_m2_append_think``, which
|
||||
returns content as ``<think>`` + the full completion so think tags round-trip
|
||||
through multi-turn re-serialization. vLLM 0.24's minimax_m2 parser engine
|
||||
added a ``(CONTENT, THINK_END) -> no-events`` transition that silently
|
||||
swallows the ``</think>`` (0.23's regex tool parser passed it through
|
||||
untouched), and it also ``.strip()``s content whenever tool calls are
|
||||
present. Drop the transition — the engine emits unmatched terminals as plain
|
||||
state content — and disable the content strip.
|
||||
"""
|
||||
import dataclasses
|
||||
import functools
|
||||
|
||||
from vllm.parser import minimax_m2
|
||||
from vllm.parser.engine.parser_engine_config import ParserState
|
||||
|
||||
original_config = minimax_m2.minimax_m2_config
|
||||
|
||||
@functools.cache
|
||||
def _patched_config():
|
||||
config = original_config()
|
||||
transitions = dict(config.transitions)
|
||||
del transitions[(ParserState.CONTENT, "THINK_END")]
|
||||
return dataclasses.replace(
|
||||
config,
|
||||
transitions=transitions,
|
||||
strip_content_whitespace_with_tools=False,
|
||||
)
|
||||
|
||||
minimax_m2.minimax_m2_config = _patched_config
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
@@ -185,7 +269,7 @@ def monkey_patch_strip_routed_experts_from_chat():
|
||||
def _patch_qwen35_moe_lora_format():
|
||||
"""Force Qwen3.5-MoE onto vLLM's 2D per-expert LoRA format.
|
||||
|
||||
vLLM 0.23.0 defaults ``Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = True``,
|
||||
vLLM 0.24.0 still defaults ``Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = True``,
|
||||
which makes the LoRA loader expect 3D stacked-expert adapters
|
||||
(``base_layer.lora_{A,B}.weight`` / ``lora_{A,B}.weight``, experts folded into the
|
||||
rank dim; see ``_stack_moe_lora_weights``). Our trainer instead emits the 2D
|
||||
@@ -206,16 +290,23 @@ def _patch_qwen35_moe_lora_format():
|
||||
|
||||
|
||||
def _patch_lora_key_prefix():
|
||||
"""Patch vLLM's LoRA loading to handle keys without base_model.model. prefix.
|
||||
"""Accept both bare-suffix and fully-qualified expert module names in LoRA adapters.
|
||||
|
||||
This is a copy of the upstream patch: https://github.com/vllm-project/vllm/pull/38522
|
||||
We can remove this patch once that PR makes it into a release.
|
||||
Copy of vLLM 0.24.0's ``LoRAModel.from_local_checkpoint`` with one change: the
|
||||
``.experts`` branch of ``check_unexpected_modules`` accepts either the bare suffix
|
||||
(``down_proj``) or the qualified per-expert name (``experts.N.down_proj``), where
|
||||
upstream only accepts the qualified form. Our trainer's 2D per-expert adapters
|
||||
(Qwen3.5-MoE) carry names whose qualified form is not in the expected set while
|
||||
the bare suffix is; Qwen3-30B-A3B adapters go the other way. Upstream fix
|
||||
vllm-project/vllm#38522 was closed unmerged, so this stays.
|
||||
"""
|
||||
from vllm.lora.lora_model import (
|
||||
LoRAModel,
|
||||
MoEEPLoadSpec,
|
||||
PEFTHelper,
|
||||
TensorizerConfig,
|
||||
WeightsMapper,
|
||||
_is_remote_expert_key,
|
||||
get_lora_id,
|
||||
is_base_embedding_weights,
|
||||
os,
|
||||
@@ -236,6 +327,7 @@ def _patch_lora_key_prefix():
|
||||
weights_mapper: WeightsMapper | None = None,
|
||||
tensorizer_config_dict: dict | None = None,
|
||||
skip_prefixes: list[str] | None = None,
|
||||
moe_ep_spec: MoEEPLoadSpec | None = None,
|
||||
) -> "LoRAModel":
|
||||
"""Create a LoRAModel from a local checkpoint.
|
||||
|
||||
@@ -251,6 +343,11 @@ def _patch_lora_key_prefix():
|
||||
skip_prefixes: List of module name prefixes to skip during loading.
|
||||
Models can define this to skip modules not used in inference
|
||||
(e.g., MTP layers). Format: ["mtp."]
|
||||
moe_ep_spec: When 2D FusedMoE LoRA modules are present with
|
||||
expert parallelism enabled, the (ep_rank, local, global)
|
||||
slicing metadata shared across all MoE layers. Non-local
|
||||
expert weights are skipped at read time instead of being
|
||||
loaded and discarded later.
|
||||
|
||||
Returns:
|
||||
Loaded LoRA Model.
|
||||
@@ -275,22 +372,13 @@ def _patch_lora_key_prefix():
|
||||
continue
|
||||
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
|
||||
# Case for expert lora weights.
|
||||
# For standard MoE models the name ends in "...experts",
|
||||
# so expert_idx+1 yields "experts" which is in
|
||||
# expected_lora_modules.
|
||||
# For Qwen 3.5 MoE (and similar models) the expert index
|
||||
# is embedded: "...experts.N.down_proj". Taking everything
|
||||
# after ".experts" gives "experts.N.down_proj" which is
|
||||
# never in the expected set even though "down_proj" is.
|
||||
# Qwen3-30B-A3B goes the other way: the expected set
|
||||
# contains the fully-qualified per-expert name
|
||||
# ("experts.N.down_proj") but not the bare suffix.
|
||||
# Accept either form.
|
||||
## START PATCHED CODE (upstream only accepts the qualified form)
|
||||
if ".experts" in module_name:
|
||||
expert_suffix = module_name.split(".")[-1]
|
||||
experts_qualified = "experts" + module_name.split(".experts", 1)[-1]
|
||||
if expert_suffix not in expected_lora_modules and experts_qualified not in expected_lora_modules:
|
||||
unexpected_modules.append(module_name)
|
||||
## END PATCHED CODE
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
unexpected_modules.append(module_name)
|
||||
@@ -307,11 +395,15 @@ def _patch_lora_key_prefix():
|
||||
from tensorizer import TensorDeserializer
|
||||
|
||||
tensorizer_config = TensorizerConfig(**tensorizer_config_dict)
|
||||
lora_tensor_path = os.path.join(tensorizer_config.tensorizer_dir, "adapter_model.tensors")
|
||||
tensorizer_dir = tensorizer_config.tensorizer_dir
|
||||
if tensorizer_dir is None:
|
||||
raise ValueError("tensorizer_dir must be set in tensorizer config.")
|
||||
lora_tensor_path = os.path.join(tensorizer_dir, "adapter_model.tensors")
|
||||
tensorizer_args = tensorizer_config._construct_tensorizer_args()
|
||||
tensors = TensorDeserializer(
|
||||
lora_tensor_path,
|
||||
dtype=tensorizer_config.dtype,
|
||||
device=device,
|
||||
**tensorizer_args.deserialization_kwargs,
|
||||
)
|
||||
check_unexpected_modules(tensors)
|
||||
@@ -328,11 +420,18 @@ def _patch_lora_key_prefix():
|
||||
# Load tensors if there are only expected modules.
|
||||
check_unexpected_modules(f)
|
||||
for module in f.keys(): # noqa
|
||||
if moe_ep_spec is not None and _is_remote_expert_key(module, moe_ep_spec):
|
||||
continue
|
||||
tensors[module] = f.get_tensor(module)
|
||||
elif os.path.isfile(lora_bin_file_path) or os.path.isfile(lora_pt_file_path):
|
||||
lora_file_path = lora_bin_file_path if os.path.isfile(lora_bin_file_path) else lora_pt_file_path
|
||||
tensors = torch.load(lora_file_path, map_location=device, weights_only=True)
|
||||
check_unexpected_modules(tensors)
|
||||
if moe_ep_spec is not None:
|
||||
# `.bin`/`.pt` adapters can't be lazy-loaded, but pruning
|
||||
# the dict here still frees the non-local expert tensors
|
||||
# before the dtype cast / pin_memory work that follows.
|
||||
tensors = {k: v for k, v in tensors.items() if not _is_remote_expert_key(k, moe_ep_spec)}
|
||||
else:
|
||||
raise ValueError(f"{lora_dir} doesn't contain tensors")
|
||||
|
||||
@@ -350,177 +449,6 @@ def _patch_lora_key_prefix():
|
||||
LoRAModel.from_local_checkpoint = classmethod(_patched_from_local_checkpoint)
|
||||
|
||||
|
||||
# Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
|
||||
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
def monkey_patch_load_lora_adapter():
|
||||
from http import HTTPStatus
|
||||
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.openai.models.serving import (
|
||||
OpenAIServingModels,
|
||||
create_error_response,
|
||||
)
|
||||
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
async def _patched_load_lora_adapter(
|
||||
self: OpenAIServingModels, request: LoadLoRAAdapterRequest, base_model_name: str | None = None
|
||||
) -> ErrorResponse | str:
|
||||
lora_name = request.lora_name
|
||||
|
||||
# Ensure atomicity based on the lora name
|
||||
async with self.lora_resolver_lock[lora_name]:
|
||||
lora_path = request.lora_path
|
||||
## START PATCHED CODE
|
||||
if lora_name in self.lora_requests:
|
||||
lora_request = self.lora_requests[lora_name]
|
||||
lora_request.lora_path = lora_path
|
||||
else:
|
||||
unique_id = self.lora_id_counter.inc(1)
|
||||
lora_request = LoRARequest(lora_name=lora_name, lora_int_id=unique_id, lora_path=lora_path)
|
||||
## END PATCHED CODE
|
||||
if base_model_name is not None and self.is_base_model(base_model_name):
|
||||
lora_request.base_model_name = base_model_name
|
||||
|
||||
# Validate that the adapter can be loaded into the engine
|
||||
# This will also preload it for incoming requests
|
||||
try:
|
||||
await self.engine_client.add_lora(lora_request)
|
||||
except Exception as e:
|
||||
error_type = "BadRequestError"
|
||||
status_code = HTTPStatus.BAD_REQUEST
|
||||
if "No adapter found" in str(e):
|
||||
error_type = "NotFoundError"
|
||||
status_code = HTTPStatus.NOT_FOUND
|
||||
|
||||
return create_error_response(message=str(e), err_type=error_type, status_code=status_code)
|
||||
|
||||
self.lora_requests[lora_name] = lora_request
|
||||
logger.info("Loaded new LoRA adapter: name '%s', path '%s'", lora_name, lora_path)
|
||||
return f"Success: LoRA adapter '{lora_name}' added successfully."
|
||||
|
||||
OpenAIServingModels.load_lora_adapter = _patched_load_lora_adapter
|
||||
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
def monkey_patch_LRUCacheWorkerLoRAManager():
|
||||
from vllm.lora.worker_manager import LoRARequest, LRUCacheLoRAModelManager, LRUCacheWorkerLoRAManager
|
||||
|
||||
# The dunder is intended. It's a private method that we're patching.
|
||||
def _patched__apply_adapters(self: LRUCacheWorkerLoRAManager, lora_requests: set[LoRARequest]) -> None:
|
||||
loras_map = {lora_request.lora_int_id: lora_request for lora_request in lora_requests if lora_request}
|
||||
if len(loras_map) > self._adapter_manager.lora_slots:
|
||||
raise RuntimeError(
|
||||
f"Number of requested LoRAs ({len(loras_map)}) is greater "
|
||||
"than the number of GPU LoRA slots "
|
||||
f"({self._adapter_manager.lora_slots})."
|
||||
)
|
||||
for lora in loras_map.values():
|
||||
## START PATCHED CODE
|
||||
self.add_adapter(lora, force_load=False)
|
||||
## END PATCHED CODE
|
||||
|
||||
def _patched_add_adapter(
|
||||
self: LRUCacheWorkerLoRAManager, lora_request: LoRARequest, force_load: bool = True
|
||||
) -> bool:
|
||||
# Note that this method is not thread-safe. It may be invoked multiple
|
||||
# times for the same adapter when using multiple API servers.
|
||||
# This is ok because it's currently only called from
|
||||
# the single-threaded core engine loop.
|
||||
|
||||
## START PATCHED CODE
|
||||
if lora_request.lora_int_id not in self.list_adapters() or force_load:
|
||||
## END PATCHED CODE
|
||||
# Load the new adapter first to ensure it is actually valid, before
|
||||
# evicting any existing adapters.
|
||||
# This may cause the # of loaded lora adapters to very temporarily
|
||||
# exceed `--max-cpu-loras`.
|
||||
lora = self._load_adapter(lora_request)
|
||||
## START PATCHED CODE
|
||||
self._adapter_manager.remove_adapter(lora.id)
|
||||
## END PATCHED CODE
|
||||
|
||||
# Loading succeeded, now check if we will exceed cache capacity and
|
||||
# evict if the oldest adapter if so
|
||||
if len(self._adapter_manager) + 1 > self._adapter_manager.capacity:
|
||||
assert isinstance(self._adapter_manager, LRUCacheLoRAModelManager)
|
||||
self._adapter_manager.remove_oldest_adapter()
|
||||
# Then add the new adapter to the cache
|
||||
loaded = self._adapter_manager.add_adapter(lora)
|
||||
else:
|
||||
# If the lora is already loaded, just touch it to
|
||||
# update its position in the caches
|
||||
loaded = self._adapter_manager.get_adapter(lora_request.lora_int_id) is not None
|
||||
self._adapter_manager.activate_adapter(lora_request.lora_int_id)
|
||||
return loaded
|
||||
|
||||
LRUCacheWorkerLoRAManager._apply_adapters = _patched__apply_adapters
|
||||
LRUCacheWorkerLoRAManager.add_adapter = _patched_add_adapter
|
||||
|
||||
|
||||
# Monkeypatch WorkerLoRAManager._load_adapter to skip the per-module regex
|
||||
# warning loop. On wide MoE models (Qwen3.5-35B-A3B) it spends minutes
|
||||
# recompiling regex patterns inside is_supported_lora_module — purely to emit
|
||||
# logger.warning_once about modules that will be ignored. Adapter validity is
|
||||
# already enforced by from_local_checkpoint, so dropping the warnings is safe.
|
||||
def monkey_patch_skip_lora_module_warnings():
|
||||
from vllm.exceptions import LoRAAdapterNotFoundError
|
||||
from vllm.lora.lora_model import LoRAModel
|
||||
from vllm.lora.peft_helper import PEFTHelper
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.lora.utils import get_adapter_absolute_path
|
||||
from vllm.lora.worker_manager import WorkerLoRAManager
|
||||
|
||||
def _patched_load_adapter(self: WorkerLoRAManager, lora_request: LoRARequest) -> LoRAModel:
|
||||
try:
|
||||
supported_lora_modules = self._adapter_manager.supported_lora_modules
|
||||
packed_modules_mapping = self._adapter_manager.packed_modules_mapping
|
||||
expected_lora_lst: list[str] = []
|
||||
for module in supported_lora_modules:
|
||||
if module in packed_modules_mapping:
|
||||
expected_lora_lst.extend(packed_modules_mapping[module])
|
||||
else:
|
||||
expected_lora_lst.append(module)
|
||||
if module == "experts":
|
||||
expected_lora_lst.append(module)
|
||||
expected_lora_modules = set(expected_lora_lst)
|
||||
lora_path = get_adapter_absolute_path(lora_request.lora_path)
|
||||
|
||||
peft_helper = PEFTHelper.from_local_dir(
|
||||
lora_path,
|
||||
self.max_position_embeddings,
|
||||
lora_request.tensorizer_config_dict,
|
||||
)
|
||||
peft_helper.validate_legal(self.lora_config)
|
||||
|
||||
model = self._adapter_manager.model
|
||||
hf_to_vllm_mapper = getattr(model, "hf_to_vllm_mapper", None)
|
||||
lora_skip_prefixes = getattr(model, "lora_skip_prefixes", None)
|
||||
|
||||
lora = self._lora_model_cls.from_local_checkpoint(
|
||||
lora_path,
|
||||
expected_lora_modules,
|
||||
peft_helper=peft_helper,
|
||||
lora_model_id=lora_request.lora_int_id,
|
||||
device="cpu",
|
||||
dtype=self.lora_config.lora_dtype,
|
||||
model_vocab_size=self.vocab_size,
|
||||
tensorizer_config_dict=lora_request.tensorizer_config_dict,
|
||||
weights_mapper=hf_to_vllm_mapper,
|
||||
skip_prefixes=lora_skip_prefixes,
|
||||
)
|
||||
except FileNotFoundError as e:
|
||||
raise LoRAAdapterNotFoundError(lora_request.lora_name, lora_request.lora_path) from e
|
||||
|
||||
return lora
|
||||
|
||||
WorkerLoRAManager._load_adapter = _patched_load_adapter
|
||||
|
||||
|
||||
# Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
def monkey_patch_tokenize_params_validation():
|
||||
"""
|
||||
@@ -608,7 +536,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
asserts inputs are float16/bfloat16. Qwen3 MoE doesn't have this
|
||||
problem because its gate uses the model dtype.
|
||||
Fix: rebuild the gate as GateLinear with a bf16 weight (out_dtype=float32
|
||||
keeps fp32 router logits). vLLM 0.23.0's own forward already drops the
|
||||
keeps fp32 router logits). vLLM 0.24.0's own forward already drops the
|
||||
float32 input cast. FusedMoE also has router_logits_dtype=float32, so
|
||||
routing precision is preserved inside the expert dispatch.
|
||||
|
||||
@@ -634,7 +562,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
_original_init(self, config, quant_config, prefix)
|
||||
from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear
|
||||
|
||||
# vLLM 0.23.0 builds the gate as GateLinear with a float32 weight; rebuild it
|
||||
# vLLM 0.24.0 builds the gate as GateLinear with a float32 weight; rebuild it
|
||||
# with a bf16 weight (model dtype) so the LoRA Triton kernel's float16/bfloat16
|
||||
# assertion passes, keeping out_dtype=float32 so router logits stay fp32 (the
|
||||
# GateLinear bf16xbf16->fp32 path).
|
||||
@@ -646,19 +574,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
prefix=f"{prefix}.gate",
|
||||
)
|
||||
|
||||
def _patched_forward(self, hidden_states):
|
||||
from vllm.distributed import tensor_model_parallel_all_reduce
|
||||
|
||||
num_tokens, hidden_dim = hidden_states.shape
|
||||
hidden_states = hidden_states.view(-1, hidden_dim)
|
||||
router_logits, _ = self.gate(hidden_states)
|
||||
final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=router_logits)
|
||||
if self.tp_size > 1:
|
||||
final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)
|
||||
return final_hidden_states.view(num_tokens, hidden_dim)
|
||||
|
||||
MiniMaxM2MoE.__init__ = _patched_init
|
||||
MiniMaxM2MoE.forward = _patched_forward
|
||||
|
||||
# --- Adapter key remapping (only read by vLLM's LoRA adapter loader) ---
|
||||
MiniMaxM2ForCausalLM.hf_to_vllm_mapper = WeightsMapper(
|
||||
@@ -703,23 +619,15 @@ def monkey_patch_no_moe_lora():
|
||||
Otherwise, the oracle will always try to pick TritonExperts.
|
||||
For blackwells, we want TRTLLMFlashInfer.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig, logger
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig
|
||||
|
||||
original_post_init = FusedMoEConfig.__post_init__
|
||||
|
||||
def _patched__post_init__(self: FusedMoEConfig):
|
||||
if self.dp_size > 1:
|
||||
logger.debug_once("Using FusedMoEConfig::max_num_tokens=%d", self.max_num_tokens)
|
||||
|
||||
assert self.max_num_tokens > 0
|
||||
|
||||
if self.router_logits_dtype is None:
|
||||
self.router_logits_dtype = self.in_dtype
|
||||
|
||||
if self.hidden_dim_unpadded is None:
|
||||
self.hidden_dim_unpadded = self.hidden_dim
|
||||
if self.intermediate_size_per_partition_unpadded is None:
|
||||
self.intermediate_size_per_partition_unpadded = self.intermediate_size_per_partition
|
||||
|
||||
# Disable LoRA for MoE layers
|
||||
original_post_init(self)
|
||||
# Disable LoRA for MoE layers. `is_lora_enabled` is only read later during
|
||||
# kernel selection (modular_kernel / unquantized oracle), never inside
|
||||
# `__post_init__`, so flipping it after the original runs is sufficient.
|
||||
self.is_lora_enabled = False
|
||||
|
||||
FusedMoEConfig.__post_init__ = _patched__post_init__
|
||||
@@ -788,11 +696,11 @@ def monkey_patch_fp32_lm_head():
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
|
||||
|
||||
The coordinator child process is spawned on the DP-rank-0 API server while
|
||||
every engine-core rank on the node is importing and loading weights, so its
|
||||
own spawn-time re-import can take well over 30s under that CPU/IO
|
||||
own spawn-time re-import can exceed the hard-coded timeout under that CPU/IO
|
||||
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
|
||||
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
|
||||
"""
|
||||
|
||||
@@ -2,7 +2,6 @@ import logging.config
|
||||
import os
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli
|
||||
|
||||
|
||||
def setup_vllm_env(config: InferenceConfig):
|
||||
@@ -11,7 +10,8 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Force the V1 GPU model runner. vLLM 0.23.0 routes dense Llama/Mistral/Qwen3 to the
|
||||
# Force the V1 GPU model runner. vLLM 0.24.0 routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe; the 0.23 MoE/quantized guard was removed) to the
|
||||
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
|
||||
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
|
||||
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
|
||||
@@ -20,6 +20,12 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
# "required"/named and strict tools — a sampling distribution the trainer never
|
||||
# sees. Keep it off so rollout logprobs stay faithful for importance ratios.
|
||||
os.environ.setdefault("VLLM_ENFORCE_STRICT_TOOL_CALLING", "0")
|
||||
|
||||
deep_gemm_enabled = "1" if config.use_deep_gemm else "0"
|
||||
os.environ["VLLM_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
os.environ["VLLM_MOE_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
@@ -41,17 +47,3 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
os.environ["VLLM_CONFIGURE_LOGGING"] = "1"
|
||||
os.environ["VLLM_LOGGING_CONFIG_PATH"] = str(config_path)
|
||||
logging.config.dictConfig(build_dict_config(config.log.level))
|
||||
|
||||
|
||||
def main():
|
||||
config = cli(InferenceConfig)
|
||||
setup_vllm_env(config)
|
||||
|
||||
# We import here to be able to set environment variables before importing vLLM
|
||||
from prime_rl.inference.vllm.server import server # pyright: ignore
|
||||
|
||||
server(config, vllm_extra=config.vllm_extra)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -22,7 +22,6 @@ logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_dp_coordinator_startup_timeout,
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
@@ -32,9 +31,6 @@ from prime_rl.inference.patches import (
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
|
||||
monkey_patch_harmony_stop_token_propagation()
|
||||
# NOTE: Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
|
||||
# May be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
monkey_patch_load_lora_adapter()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
@@ -50,7 +46,7 @@ monkey_patch_vllm_padded_input_scrub()
|
||||
# routed_experts from chat responses since the server-wide enable flag has no
|
||||
# per-request toggle.
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
# NOTE: vLLM hard-codes a 30s DP coordinator startup timeout, which the rank-0
|
||||
# NOTE: vLLM hard-codes a 120s DP coordinator startup timeout, which the rank-0
|
||||
# API server blows through when all engine-core ranks on the node are loading
|
||||
# weights concurrently (multi-node disaggregated deployments).
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
@@ -97,9 +93,29 @@ async def update_weights(request: Request):
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter."""
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter.
|
||||
|
||||
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
|
||||
changes per policy version; the name is constant, see orchestrator.lora_name).
|
||||
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``,
|
||||
so we force it here — that makes the worker re-read the new weights during
|
||||
``add_lora``, reusing the existing ``lora_int_id``.
|
||||
|
||||
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
|
||||
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
|
||||
every generation request; left ``True`` it would force a disk reload on each
|
||||
scheduler step. The orchestrator awaits this endpoint before dispatching
|
||||
rollouts for the new version, so the reset always lands before generation.
|
||||
The reset runs regardless of success/error: vLLM only stores the adapter on
|
||||
success today, but resetting whatever is stored keeps us correct even if a
|
||||
future version were to leave a ``load_inplace=True`` request behind on error.
|
||||
"""
|
||||
handler = models(raw_request)
|
||||
lora_request.load_inplace = True
|
||||
response = await handler.load_lora_adapter(lora_request)
|
||||
stored = handler.lora_requests.get(lora_request.lora_name)
|
||||
if stored is not None:
|
||||
stored.load_inplace = False
|
||||
if isinstance(response, ErrorResponse):
|
||||
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
|
||||
return {"status": "ok"}
|
||||
@@ -150,7 +166,6 @@ async def custom_init_app_state(
|
||||
"""
|
||||
await init_app_state(engine_client, state, args, supported_tasks)
|
||||
|
||||
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
|
||||
state.liveness_timeout_seconds = args.liveness_timeout_seconds
|
||||
|
||||
# Swap in our ServingTokens subclass for /inference/v1/generate so the
|
||||
|
||||
@@ -3,19 +3,12 @@ import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_LRUCacheWorkerLoRAManager,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
monkey_patch_skip_lora_module_warnings,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
monkey_patch_LRUCacheWorkerLoRAManager()
|
||||
# Skip the per-module regex warning loop in WorkerLoRAManager._load_adapter
|
||||
# (minutes-long stall on wide MoE models like Qwen3.5-35B-A3B)
|
||||
monkey_patch_skip_lora_module_warnings()
|
||||
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
# Disable LoRA on MoE layers so vLLM picks better kernels (e.g. TRTLLMFlashInfer on Blackwell)
|
||||
|
||||
@@ -24,42 +24,6 @@ else:
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nccl")
|
||||
|
||||
# NemotronH mixer.D is dropped by vLLM's layerwise online-reload path (left uninitialized).
|
||||
_RELOAD_CORRUPTED_SUFFIXES = (".mixer.D",)
|
||||
|
||||
|
||||
def _restore_reload_corrupted_params(model: Module, received: dict[str, torch.Tensor]) -> None:
|
||||
"""Work around a vLLM layerwise-reload bug for NemotronH (present through vLLM 0.23.0).
|
||||
|
||||
The online reload drops the weight load for every Mamba layer's ``mixer.D`` (the SSD skip
|
||||
connection), leaving it as uninitialized ``empty_strided`` memory -- it reads back as garbage
|
||||
(NaN/inf) and the logits go NaN after a weight update. Root cause: ``mixer.A`` is loaded with
|
||||
``composed_weight_loader`` (an extra in-place transform copy), so the reload element counter
|
||||
double-counts ``A`` and finalizes the layer before ``D`` (loaded last) is loaded. The received
|
||||
broadcast value is correct, so restore D from it via the param's own ``weight_loader``.
|
||||
|
||||
Fixed upstream by vllm-project/vllm#44814 (merged 2026-06-10) but NOT in the pinned 0.23.0
|
||||
release; remove this shim once we bump to a vLLM release that includes it.
|
||||
"""
|
||||
|
||||
def _layer_key(name: str) -> str:
|
||||
index = name.find("layers.")
|
||||
return name[index:] if index >= 0 else name
|
||||
|
||||
received_by_key = {_layer_key(name): tensor for name, tensor in received.items()}
|
||||
for name, param in model.named_parameters():
|
||||
if not name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
|
||||
continue
|
||||
tensor = received_by_key.get(_layer_key(name))
|
||||
if tensor is None:
|
||||
continue
|
||||
tensor = tensor.to(device=param.device)
|
||||
weight_loader = getattr(param, "weight_loader", None)
|
||||
if weight_loader is not None:
|
||||
weight_loader(param, tensor)
|
||||
elif tensor.shape == param.shape:
|
||||
param.data.copy_(tensor.to(param.dtype))
|
||||
|
||||
|
||||
def receive_integer(communicator: PyNcclCommunicator) -> int:
|
||||
"""Receive an integer from the trainer master rank using NCCL communicator."""
|
||||
@@ -184,20 +148,9 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
# vLLM's layerwise reload drops NemotronH mixer.D's weight load (see
|
||||
# _restore_reload_corrupted_params). Capture the correct received value to restore after.
|
||||
received_reload_fix: dict[str, torch.Tensor] = {}
|
||||
|
||||
def _capture_reload_fix(weights):
|
||||
for name, tensor in weights:
|
||||
if name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
|
||||
received_reload_fix[name] = tensor.detach().to("cpu", copy=True)
|
||||
yield name, tensor
|
||||
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
_capture_reload_fix(state_iter),
|
||||
state_iter,
|
||||
self.model_runner.model_config,
|
||||
self.vllm_config,
|
||||
)
|
||||
_restore_reload_corrupted_params(model, received_reload_fix)
|
||||
|
||||
@@ -5,6 +5,7 @@ from torch.nn import Module
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
|
||||
from vllm.model_executor.model_loader.weight_utils import remap_moe_expert_weights
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
|
||||
|
||||
@@ -47,20 +48,20 @@ def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_p
|
||||
return physical_to_logical
|
||||
|
||||
|
||||
def _build_expert_source_indices(module) -> torch.Tensor | None:
|
||||
if module._expert_map is None:
|
||||
def _build_expert_source_indices(routed_experts, router) -> torch.Tensor | None:
|
||||
if routed_experts._expert_map is None:
|
||||
return None
|
||||
|
||||
physical_indices = torch.where(module._expert_map >= 0)[0]
|
||||
local_indices = module._expert_map[physical_indices]
|
||||
physical_indices = torch.where(routed_experts._expert_map >= 0)[0]
|
||||
local_indices = routed_experts._expert_map[physical_indices]
|
||||
physical_indices = physical_indices[local_indices.argsort()]
|
||||
|
||||
eplb_layer_state = getattr(module, "eplb_state", None)
|
||||
eplb_layer_state = getattr(router, "eplb_state", None)
|
||||
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
|
||||
if logical_to_physical_map is None:
|
||||
return physical_indices
|
||||
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, module.global_num_experts)
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, routed_experts.global_num_experts)
|
||||
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
|
||||
if (logical_indices < 0).any():
|
||||
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
|
||||
@@ -70,14 +71,23 @@ def _build_expert_source_indices(module) -> torch.Tensor | None:
|
||||
|
||||
|
||||
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
|
||||
"""Map FusedMoE module names to source expert indices local to this worker."""
|
||||
from vllm.model_executor.layers.fused_moe.layer import FusedMoE
|
||||
"""Map MoE module names to source expert indices local to this worker.
|
||||
|
||||
vLLM 0.24 turned ``FusedMoE`` into a factory returning a ``MoERunner`` and
|
||||
split the state that used to live on the ``FusedMoE`` module: the expert map
|
||||
(``_expert_map`` / ``global_num_experts``) now lives on
|
||||
``MoERunner.routed_experts`` (a ``RoutedExperts``), and the EPLB state on
|
||||
``MoERunner.router``. Keying by the ``MoERunner`` name prefix-matches the
|
||||
nested ``routed_experts.*`` weight params after ``load_weights_kernel``
|
||||
remaps incoming flat names via ``remap_moe_expert_weights``.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe import MoERunner
|
||||
|
||||
source_indices_by_module: dict[str, torch.Tensor] = {}
|
||||
for module_name, module in model.named_modules():
|
||||
if not isinstance(module, FusedMoE):
|
||||
if not isinstance(module, MoERunner):
|
||||
continue
|
||||
source_indices = _build_expert_source_indices(module)
|
||||
source_indices = _build_expert_source_indices(module.routed_experts, module.router)
|
||||
if source_indices is None:
|
||||
continue
|
||||
source_indices_by_module[module_name] = source_indices
|
||||
@@ -94,7 +104,10 @@ def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Te
|
||||
skipped: list[str] = []
|
||||
shape_mismatches: list[str] = []
|
||||
|
||||
for name, tensor in state_iter:
|
||||
# The trainer emits pre-0.24 flat kernel names (``...experts.w13_weight``); since
|
||||
# vLLM 0.24 the expert params are nested (``...experts.routed_experts.w13_weight``).
|
||||
# ``remap_moe_expert_weights`` is upstream's compat shim for exactly this transition.
|
||||
for name, tensor in remap_moe_expert_weights(state_iter, params):
|
||||
if name not in params:
|
||||
skipped.append(name)
|
||||
continue
|
||||
|
||||
@@ -14,10 +14,9 @@ turns the signal half into runtime objects (the sampling half is the env's
|
||||
and register it below.
|
||||
- ``base`` — the :class:`Algorithm` base class, whose non-virtual
|
||||
``finalize_rollout`` / ``finalize_group`` methods the pipeline drives.
|
||||
- ``advantage`` — shared advantage math (``efficiency_shaping``). Advantages
|
||||
are per-token everywhere they are stored or shipped — there is no scalar
|
||||
advantage in the pipeline. An algorithm assigns credit in its scoring hook
|
||||
via ``Rollout.assign_advantages``: a scalar that is *broadcast* over the
|
||||
Advantages are per-token everywhere they are stored or shipped — there is no
|
||||
scalar advantage in the pipeline. An algorithm assigns credit in its scoring
|
||||
hook via ``Rollout.assign_advantages``: a scalar that is *broadcast* over the
|
||||
rollout's completion tokens (uniform credit, the common case), or an explicit
|
||||
full-length-N per-token list aligned to the concatenated sample token_ids
|
||||
(0.0 off-mask).
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from jaxtyping import Float
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def efficiency_shaping(
|
||||
rewards: Float[Tensor, "group_size"],
|
||||
costs: Float[Tensor, "group_size"],
|
||||
) -> Float[Tensor, "group_size"]:
|
||||
"""Correctness-gated efficiency shaping with bounded advantages.
|
||||
|
||||
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
|
||||
(e.g., completion length in tokens or number of turns).
|
||||
|
||||
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
|
||||
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
|
||||
"""
|
||||
max_reward = rewards.max()
|
||||
correct_mask = rewards >= max_reward
|
||||
num_correct = correct_mask.sum()
|
||||
|
||||
# No shaping when max reward is 0 — no correct rollouts to differentiate
|
||||
if max_reward <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
# Mean cost of correct rollouts
|
||||
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
|
||||
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
|
||||
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
|
||||
if mean_correct_cost <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
return shaped_rewards - shaped_rewards.mean()
|
||||
@@ -4,10 +4,8 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.algorithm import GRPOAlgoConfig, TokensLengthPenaltyConfig
|
||||
from prime_rl.orchestrator.algo.advantage import efficiency_shaping
|
||||
from prime_rl.configs.algorithm import GRPOAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.orchestrator.utils import get_tool_response_len
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
@@ -25,21 +23,21 @@ class GRPOAlgorithm(Algorithm):
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
|
||||
lp = self.length_penalty
|
||||
if lp is None:
|
||||
length_penalty = self.length_penalty
|
||||
if length_penalty is None:
|
||||
advantages = rewards - rewards.mean()
|
||||
elif isinstance(lp, TokensLengthPenaltyConfig):
|
||||
costs = torch.tensor(
|
||||
[
|
||||
lp.completion_weight * rollout.completion_len
|
||||
+ lp.tool_response_weight * get_tool_response_len(rollout)
|
||||
for rollout in group
|
||||
],
|
||||
dtype=rewards.dtype,
|
||||
else:
|
||||
output = torch.tensor([rollout.num_output_tokens for rollout in group], dtype=rewards.dtype)
|
||||
total = torch.tensor([rollout.num_total_tokens for rollout in group], dtype=rewards.dtype)
|
||||
turns = torch.tensor([rollout.num_turns for rollout in group], dtype=rewards.dtype)
|
||||
input = total - output
|
||||
penalty_frac = (
|
||||
length_penalty.num_output_tokens_weight * (output / output.max().clamp(min=1))
|
||||
+ length_penalty.num_input_tokens_weight * (input / input.max().clamp(min=1))
|
||||
+ length_penalty.num_turns_weight * (turns / turns.max().clamp(min=1))
|
||||
)
|
||||
advantages = efficiency_shaping(rewards, costs)
|
||||
else: # TurnsLengthPenaltyConfig
|
||||
costs = torch.tensor([rollout.num_turns for rollout in group], dtype=rewards.dtype)
|
||||
advantages = efficiency_shaping(rewards, costs)
|
||||
penalty = rewards.mean() * penalty_frac
|
||||
shaped_rewards = rewards - penalty
|
||||
advantages = shaped_rewards - shaped_rewards.mean()
|
||||
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
|
||||
rollout.assign_advantages(advantage)
|
||||
|
||||
@@ -201,12 +201,21 @@ class RolloutDispatcher:
|
||||
def queued_eval_examples(self) -> int:
|
||||
return len(self.eval_source) if self.eval_source is not None else 0
|
||||
|
||||
@property
|
||||
def eval_has_work(self) -> bool:
|
||||
"""Eval has work while its source queue is non-empty OR any opened eval group still has
|
||||
rollouts to schedule. An example leaves ``eval_source`` when its group opens
|
||||
(``next_fresh_group``), but its ``group_size`` rollouts dispatch one at a time across
|
||||
``fill_inflight`` passes — so the queue can be empty while a group is still mid-schedule."""
|
||||
return bool(self.eval_source) or any(
|
||||
g.kind == "eval" and g.rollouts_to_schedule > 0 for g in self.groups.values()
|
||||
)
|
||||
|
||||
@property
|
||||
def is_idle(self) -> bool:
|
||||
"""True once nothing is in flight, no eval queued, and ``out_q`` is
|
||||
empty — the pipeline has fully drained."""
|
||||
eval_drained = self.eval_source is None or not self.eval_source
|
||||
return not self.inflight and eval_drained and self.out_q.empty()
|
||||
"""True once nothing is in flight, no eval work remains (queued *or* a partly-scheduled eval
|
||||
group), and ``out_q`` is empty — the pipeline has fully drained."""
|
||||
return not self.inflight and not self.eval_has_work and self.out_q.empty()
|
||||
|
||||
def disable_train_scheduling(self) -> None:
|
||||
"""Stop scheduling new train rollouts; in-flight train + any
|
||||
@@ -307,10 +316,7 @@ class RolloutDispatcher:
|
||||
# PREFER_EVAL is only entered when the orchestrator triggers
|
||||
# eval, which requires ``eval_source`` to be configured
|
||||
assert self.eval_source is not None
|
||||
eval_has_work = bool(self.eval_source) or any(
|
||||
g.kind == "eval" and g.rollouts_to_schedule > 0 for g in self.groups.values()
|
||||
)
|
||||
if not eval_has_work:
|
||||
if not self.eval_has_work:
|
||||
# Eval source + all eval groups fully dispatched. Flip
|
||||
# to PREFER_TRAIN so any remaining permits go to train
|
||||
# while the in-flight eval tail completes naturally
|
||||
|
||||
@@ -5,8 +5,8 @@ Same shape as ``TrainSink``, but no tokenization / advantages / filters:
|
||||
1. ``process_rollout`` — no-op.
|
||||
2. ``process_group`` — at ``group_size`` arrivals, move the rollouts
|
||||
(errored ones included) into the ``(env, eval_step)`` bucket.
|
||||
3. ``process_batch`` — at ``num_examples × group_size`` arrivals, build
|
||||
the ``EvalBatchMetrics`` and return an ``EvalBatch``.
|
||||
3. ``process_batch`` — at ``num_examples × group_size`` arrivals, return an
|
||||
``EvalBatch`` with the full returned cohort (metrics are computed downstream).
|
||||
|
||||
``add()`` returns ``EvalBatch | None``.
|
||||
"""
|
||||
@@ -17,8 +17,8 @@ import uuid
|
||||
from collections import defaultdict
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.eval_utils import compute_pass_at_k
|
||||
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, Rollout
|
||||
from prime_rl.orchestrator.metrics import EvalRollouts
|
||||
from prime_rl.orchestrator.types import EvalBatch, Rollout
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -111,50 +111,10 @@ class EvalSink:
|
||||
)
|
||||
|
||||
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
|
||||
"""Build ``EvalBatchMetrics`` and return the finalized ``EvalBatch``.
|
||||
Errored rollouts (env failures, cancellations, task exceptions) are
|
||||
excluded from reward / pass@k / seq_len aggregation (including them
|
||||
at reward=0 would bias the score down) and surfaced separately as
|
||||
``n_cancelled`` / ``n_errored``."""
|
||||
"""Pop the finished ``(env, eval_step)`` epoch and return the ``EvalBatch`` with its full
|
||||
returned cohort (errored rollouts included — the ``all`` set). Metrics are computed
|
||||
downstream via ``EvalBatch.rollouts.metrics`` over the all/effective subsets, so the sink
|
||||
does no aggregation."""
|
||||
env_name, step = key
|
||||
rollouts = self.pending_batches.pop(key, [])
|
||||
|
||||
n_total = len(rollouts)
|
||||
n_cancelled = sum(1 for r in rollouts if r.has_error and r.error.type == "Cancelled")
|
||||
n_errored = sum(1 for r in rollouts if r.has_error) - n_cancelled
|
||||
valid = [r for r in rollouts if not r.has_error]
|
||||
metrics = EvalBatchMetrics(
|
||||
n_rollouts=n_total,
|
||||
n_cancelled=n_cancelled,
|
||||
n_errored=n_errored,
|
||||
)
|
||||
|
||||
if valid:
|
||||
rewards = [r.reward for r in valid]
|
||||
lens = [sum(b.output_len for b in r.branches) for r in valid]
|
||||
metrics.group_size = self.group_size_for(env_name)
|
||||
metrics.reward_mean = float(sum(rewards) / len(rewards))
|
||||
metrics.completion_len_mean = float(sum(lens) / len(lens))
|
||||
metrics.completion_len_max = float(max(lens))
|
||||
metrics.completion_len_min = float(min(lens))
|
||||
metrics.truncation_rate = float(sum(1 for r in valid if r.is_truncated) / len(valid))
|
||||
metrics.no_response_rate = float(sum(1 for r in valid if not r.has_response) / len(valid))
|
||||
num_turns = [r.num_turns for r in valid]
|
||||
metrics.num_turns_mean = float(sum(num_turns) / len(num_turns))
|
||||
metrics.num_turns_min = float(min(num_turns))
|
||||
metrics.num_turns_max = float(max(num_turns))
|
||||
|
||||
# pass@k: errored attempts don't count toward k tries
|
||||
by_example: dict[int, list[float]] = {}
|
||||
for r in valid:
|
||||
by_example.setdefault(r.task.idx, []).append(r.reward)
|
||||
metrics.n_examples = len(by_example)
|
||||
unique_rewards = {float(r) for r in rewards}
|
||||
if unique_rewards.issubset({0.0, 1.0}) and by_example:
|
||||
pass_at_k_per_example = [compute_pass_at_k(rs) for rs in by_example.values()]
|
||||
keys = set().union(*(d.keys() for d in pass_at_k_per_example))
|
||||
for k in keys:
|
||||
values = [d[k] for d in pass_at_k_per_example if k in d]
|
||||
metrics.pass_at_k[k] = float(sum(values) / len(values))
|
||||
|
||||
return EvalBatch(env_name=env_name, step=step, rollouts=rollouts, metrics=metrics)
|
||||
return EvalBatch(env_name=env_name, step=step, rollouts=EvalRollouts(rollouts))
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import numpy as np
|
||||
|
||||
|
||||
def _pass_at_k(n: int, c: int, k: int) -> float:
|
||||
"""Unbiased estimator of pass@k (Chen et al., 2021).
|
||||
|
||||
Computes 1 - C(n-c, k) / C(n, k) in a numerically stable way.
|
||||
"""
|
||||
if n - c < k:
|
||||
return 1.0
|
||||
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
|
||||
|
||||
|
||||
def compute_pass_at_k(rewards: list[float]) -> dict[str, float]:
|
||||
n = len(rewards)
|
||||
c = sum(r == 1.0 for r in rewards)
|
||||
ks = [2**i for i in range(n.bit_length())]
|
||||
return {f"pass@{k}": _pass_at_k(n, c, k) for k in ks}
|
||||
@@ -1,185 +1,386 @@
|
||||
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
|
||||
"""Train and eval rollout metrics.
|
||||
|
||||
A rollout container (``TrainRollouts`` / ``EvalRollouts``) owns the rollout list and exposes
|
||||
``.effective`` (the clean subset, as the same container type) and ``.metrics`` (``TrainMetrics`` /
|
||||
``EvalMetrics``). The metrics object exposes each distributional / rate metric as a ``Stat`` — so
|
||||
``rollouts.metrics.num_input_tokens.mean()`` works — and assembles the full
|
||||
``{prefix}/{subset}/<metric>/<stat>`` wandb dict via ``.to_wandb(...)``.
|
||||
|
||||
No I/O, no pandas — plain Python over the ``vf.Trace`` properties each rollout exposes. Aggregation
|
||||
is flat over the rollout list except the solve rates, which group by ``group_id``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Iterator, Literal
|
||||
|
||||
import pandas as pd
|
||||
from prime_rl.orchestrator.utils import compute_pass_metrics
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.types import Progress, Rollout, TrainBatchMetrics
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
Subset = Literal["all", "effective"]
|
||||
|
||||
|
||||
class MetricsBuilder:
|
||||
def __init__(self, config: OrchestratorConfig) -> None:
|
||||
self.config = config
|
||||
class Stat:
|
||||
"""A distribution of per-rollout values with mean/max/min and p10/p90 accessors."""
|
||||
|
||||
def build(
|
||||
self,
|
||||
*,
|
||||
step: int,
|
||||
rollouts: list[Rollout],
|
||||
metrics: TrainBatchMetrics,
|
||||
progress: Progress,
|
||||
step_time: float,
|
||||
save_ckpt_time: float,
|
||||
pre_filter_seen: int,
|
||||
pre_filter_dropped: int,
|
||||
pre_filter_dropped_by_name: dict[str, int],
|
||||
) -> dict[str, Any]:
|
||||
"""Builds the per-step W&B dict. Stable metric names so
|
||||
existing dashboards / alerts keep working."""
|
||||
num_rollouts = len(rollouts)
|
||||
num_unique_examples = len({r.group_id for r in rollouts})
|
||||
num_tokens = sum(r.total_tokens for r in rollouts)
|
||||
def __init__(self, values: list[float]) -> None:
|
||||
self.values = values
|
||||
|
||||
results_df = pd.DataFrame(
|
||||
{
|
||||
"group_id": [r.group_id for r in rollouts],
|
||||
"task_idx": [r.task.idx for r in rollouts],
|
||||
"env_name": [r.env_name for r in rollouts],
|
||||
"reward": [r.reward for r in rollouts],
|
||||
"is_truncated": [r.is_truncated for r in rollouts],
|
||||
"is_filtered": [r.is_filtered for r in rollouts],
|
||||
"stop_condition": [r.stop_condition for r in rollouts],
|
||||
"seq_len": [r.total_tokens for r in rollouts],
|
||||
"prefill_len": metrics.rollout_prefill_lens,
|
||||
"decode_len": metrics.rollout_decode_lens,
|
||||
"samples_per_rollout": metrics.samples_per_rollout,
|
||||
"num_turns": [r.num_turns for r in rollouts],
|
||||
}
|
||||
)
|
||||
metrics_df = pd.DataFrame([r.metrics for r in rollouts])
|
||||
filter_df = pd.DataFrame([r.filter_results for r in rollouts])
|
||||
timing_df = self.timing_df(rollouts)
|
||||
def mean(self) -> float:
|
||||
return sum(self.values) / len(self.values) if self.values else 0.0
|
||||
|
||||
# Each group's full-solve threshold is its own env's group_size (envs
|
||||
# can override the top-level group_size).
|
||||
env_group_size = {env.resolved_name: env.group_size for env in self.config.train.env}
|
||||
def max(self) -> float:
|
||||
return float(max(self.values)) if self.values else 0.0
|
||||
|
||||
def compute_solve_rates(df):
|
||||
grouped = df.groupby("group_id")
|
||||
reward_per_problem = grouped.reward.sum()
|
||||
solve_none = (reward_per_problem == 0).mean()
|
||||
expected = grouped.env_name.first().map(env_group_size)
|
||||
solve_all = (reward_per_problem == expected).mean()
|
||||
return solve_none, solve_all, 1 - solve_none - solve_all
|
||||
def min(self) -> float:
|
||||
return float(min(self.values)) if self.values else 0.0
|
||||
|
||||
by_example = results_df.groupby("group_id")
|
||||
solve_none, solve_all, effective_batch_size = compute_solve_rates(results_df)
|
||||
def percentile(self, q: float) -> float:
|
||||
"""Linear-interpolated ``q``-th percentile (numpy's default method); 0.0 if empty."""
|
||||
if not self.values:
|
||||
return 0.0
|
||||
s = sorted(self.values)
|
||||
rank = q / 100 * (len(s) - 1)
|
||||
lo = int(rank)
|
||||
hi = min(lo + 1, len(s) - 1)
|
||||
return float(s[lo] + (s[hi] - s[lo]) * (rank - lo))
|
||||
|
||||
to_log: dict[str, Any] = {
|
||||
"progress/tokens": num_tokens,
|
||||
"progress/prefill_tokens": metrics.num_prefill_tokens,
|
||||
"progress/decode_tokens": metrics.num_decode_tokens,
|
||||
"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,
|
||||
"seq_len/all/mean": by_example.seq_len.mean().mean(),
|
||||
"seq_len/all/max": by_example.seq_len.mean().max(),
|
||||
"seq_len/all/min": by_example.seq_len.mean().min(),
|
||||
"prefill_len/all/mean": by_example.prefill_len.mean().mean(),
|
||||
"prefill_len/all/max": by_example.prefill_len.mean().max(),
|
||||
"prefill_len/all/min": by_example.prefill_len.mean().min(),
|
||||
"decode_len/all/mean": by_example.decode_len.mean().mean(),
|
||||
"decode_len/all/max": by_example.decode_len.mean().max(),
|
||||
"decode_len/all/min": by_example.decode_len.mean().min(),
|
||||
"is_truncated/all/mean": by_example.is_truncated.mean().mean(),
|
||||
"is_truncated/all/max": by_example.is_truncated.mean().max(),
|
||||
"stop_condition/all/generation_truncated": (
|
||||
results_df.is_truncated & (results_df.stop_condition != "prompt_too_long")
|
||||
).mean(),
|
||||
**{
|
||||
f"stop_condition/all/{sc}": rate
|
||||
for sc, rate in results_df.stop_condition.dropna().value_counts(normalize=True).items()
|
||||
},
|
||||
"samples_per_rollout/all/mean": by_example.samples_per_rollout.mean().mean(),
|
||||
"samples_per_rollout/all/max": by_example.samples_per_rollout.mean().max(),
|
||||
"samples_per_rollout/all/min": by_example.samples_per_rollout.mean().min(),
|
||||
"num_turns/all/mean": by_example.num_turns.mean().mean(),
|
||||
"num_turns/all/max": by_example.num_turns.mean().max(),
|
||||
"num_turns/all/min": by_example.num_turns.mean().min(),
|
||||
**{
|
||||
f"timing/all/{key}/{stat}": getattr(
|
||||
timing_df[key].groupby(results_df.group_id).mean(),
|
||||
stat,
|
||||
)()
|
||||
for key in timing_df.columns
|
||||
for stat in ("mean", "max", "min")
|
||||
},
|
||||
"reward/all/mean": by_example.reward.mean().mean(),
|
||||
"reward/all/max": by_example.reward.mean().max(),
|
||||
"reward/all/min": by_example.reward.mean().min(),
|
||||
"solve_none/all": solve_none,
|
||||
"solve_all/all": solve_all,
|
||||
"effective_batch_size/all": effective_batch_size,
|
||||
**{f"batch/{env}": r for env, r in results_df.env_name.value_counts(normalize=True).items()},
|
||||
"time/step": step_time,
|
||||
"time/save_ckpt": save_ckpt_time,
|
||||
"filters/all/is_filtered": results_df.is_filtered.astype(float).mean(),
|
||||
**{f"filters/all/{name}": filter_df[name].astype(float).mean() for name in filter_df.columns},
|
||||
"step": step,
|
||||
def p10(self) -> float:
|
||||
return self.percentile(10)
|
||||
|
||||
def p90(self) -> float:
|
||||
return self.percentile(90)
|
||||
|
||||
def to_dict(self, prefix: str) -> dict[str, float]:
|
||||
"""``{prefix}/mean,max,min,p10,p90``; ``{}`` for an empty distribution."""
|
||||
if not self.values:
|
||||
return {}
|
||||
return {
|
||||
f"{prefix}/mean": self.mean(),
|
||||
f"{prefix}/max": self.max(),
|
||||
f"{prefix}/min": self.min(),
|
||||
f"{prefix}/p10": self.p10(),
|
||||
f"{prefix}/p90": self.p90(),
|
||||
}
|
||||
|
||||
# Per-env metrics
|
||||
per_env_columns = [
|
||||
"seq_len",
|
||||
"prefill_len",
|
||||
"decode_len",
|
||||
"is_truncated",
|
||||
"samples_per_rollout",
|
||||
"num_turns",
|
||||
]
|
||||
for env, env_df in results_df.groupby("env_name"):
|
||||
env_by_example = env_df.groupby("group_id")
|
||||
for col in per_env_columns:
|
||||
to_log[f"{col}/{env}/mean"] = env_by_example[col].mean().mean()
|
||||
to_log[f"{col}/{env}/max"] = env_by_example[col].mean().max()
|
||||
if col != "is_truncated":
|
||||
to_log[f"{col}/{env}/min"] = env_by_example[col].mean().min()
|
||||
env_timing_df = timing_df.loc[env_df.index]
|
||||
for key in timing_df.columns:
|
||||
per_example = env_timing_df.groupby(env_df["group_id"])[key].mean()
|
||||
to_log[f"timing/{env}/{key}/mean"] = per_example.mean()
|
||||
to_log[f"timing/{env}/{key}/max"] = per_example.max()
|
||||
to_log[f"timing/{env}/{key}/min"] = per_example.min()
|
||||
to_log[f"reward/{env}/mean"] = env_by_example.reward.mean().mean()
|
||||
to_log[f"reward/{env}/max"] = env_by_example.reward.mean().max()
|
||||
to_log[f"reward/{env}/min"] = env_by_example.reward.mean().min()
|
||||
sn, sa, eb = compute_solve_rates(env_df)
|
||||
to_log[f"solve_none/{env}"] = sn
|
||||
to_log[f"solve_all/{env}"] = sa
|
||||
to_log[f"effective_batch_size/{env}"] = eb
|
||||
to_log[f"stop_condition/{env}/generation_truncated"] = (
|
||||
env_df.is_truncated & (env_df.stop_condition != "prompt_too_long")
|
||||
).mean()
|
||||
for sc, rate in env_df.stop_condition.dropna().value_counts(normalize=True).items():
|
||||
to_log[f"stop_condition/{env}/{sc}"] = rate
|
||||
env_metrics_df = metrics_df.loc[env_df.index] if not metrics_df.empty else metrics_df
|
||||
for metric in metrics_df.columns:
|
||||
to_log[f"metrics/{env}/{metric}"] = env_metrics_df.groupby(env_df["group_id"])[metric].mean().mean()
|
||||
to_log[f"filters/{env}/is_filtered"] = env_df.is_filtered.astype(float).mean()
|
||||
env_filter_df = filter_df.loc[env_df.index] if not filter_df.empty else filter_df
|
||||
for name in filter_df.columns:
|
||||
to_log[f"filters/{env}/{name}"] = env_filter_df[name].astype(float).mean()
|
||||
|
||||
# Dispatcher / watcher gauges live on the ``_timestamp`` axis via
|
||||
# the periodic logger — keep this dict step-axis only
|
||||
if pre_filter_seen > 0:
|
||||
to_log["pre_filters/all/dropped_rate"] = pre_filter_dropped / pre_filter_seen
|
||||
for name, count in pre_filter_dropped_by_name.items():
|
||||
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
|
||||
class StatGroup:
|
||||
"""A nested group of named ``Stat``s. ``to_dict`` emits ``{prefix}/<name>/<stat>`` for each
|
||||
distribution and ``group[name]`` returns one; subclasses supply the names via ``stats()``."""
|
||||
|
||||
return to_log
|
||||
def __init__(self, rollouts: list[Rollout]) -> None:
|
||||
self.rollouts = rollouts
|
||||
|
||||
@staticmethod
|
||||
def timing_df(rollouts: list[Rollout]) -> pd.DataFrame:
|
||||
"""Per-rollout timing from the v1 Trace (`generation`/`scoring` spans)."""
|
||||
rows = []
|
||||
for r in rollouts:
|
||||
timing = r.timing
|
||||
generation, scoring = timing.generation.duration, timing.scoring.duration
|
||||
rows.append({"total": generation + scoring, "generation": generation, "scoring": scoring})
|
||||
return pd.DataFrame(rows)
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
raise NotImplementedError
|
||||
|
||||
def __getitem__(self, name: str) -> Stat:
|
||||
return self.stats()[name]
|
||||
|
||||
def to_dict(self, prefix: str) -> dict[str, float]:
|
||||
out: dict[str, float] = {}
|
||||
for name, stat in self.stats().items():
|
||||
out |= stat.to_dict(f"{prefix}/{name}")
|
||||
return out
|
||||
|
||||
|
||||
class TimingMetrics(StatGroup):
|
||||
"""Per-phase rollout durations, nested so ``metrics.timing.setup.mean()`` reads naturally.
|
||||
``total`` is the per-rollout sum across all phases."""
|
||||
|
||||
PHASES = ("setup", "generation", "finalize", "scoring")
|
||||
|
||||
@property
|
||||
def setup(self) -> Stat:
|
||||
return Stat([r.timing.setup.duration for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def generation(self) -> Stat:
|
||||
return Stat([r.timing.generation.duration for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def finalize(self) -> Stat:
|
||||
return Stat([r.timing.finalize.duration for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def scoring(self) -> Stat:
|
||||
return Stat([r.timing.scoring.duration for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def total(self) -> Stat:
|
||||
return Stat([sum(getattr(r.timing, p).duration for p in self.PHASES) for r in self.rollouts])
|
||||
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
return {**{phase: getattr(self, phase) for phase in self.PHASES}, "total": self.total}
|
||||
|
||||
|
||||
class CustomMetrics(StatGroup):
|
||||
"""Per-key ``Stat``s over a dynamic per-rollout dict attribute (env ``@metric``s or reward
|
||||
components), each averaged over the rollouts that report the key."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout], attr: str) -> None:
|
||||
super().__init__(rollouts)
|
||||
self.attr = attr
|
||||
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
names = sorted({name for r in self.rollouts for name in getattr(r, self.attr)})
|
||||
return {
|
||||
name: Stat([getattr(r, self.attr)[name] for r in self.rollouts if name in getattr(r, self.attr)])
|
||||
for name in names
|
||||
}
|
||||
|
||||
|
||||
class RolloutMetrics:
|
||||
"""Metrics shared by train and eval over a rollout list. Distributional metrics are ``Stat``s
|
||||
(mean/max/min); boolean metrics are ``Stat``s of 0/1 (use ``.mean()`` for the rate). ``to_wandb``
|
||||
assembles the full ``{prefix}/{subset}/...`` dict; ``TrainMetrics`` / ``EvalMetrics`` extend it."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout]) -> None:
|
||||
self.rollouts = rollouts
|
||||
|
||||
# Distributional metrics
|
||||
@property
|
||||
def num_total_tokens(self) -> Stat:
|
||||
return Stat([float(r.num_total_tokens) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def num_input_tokens(self) -> Stat:
|
||||
return Stat([float(r.num_input_tokens) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def num_output_tokens(self) -> Stat:
|
||||
return Stat([float(r.num_output_tokens) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def num_turns(self) -> Stat:
|
||||
return Stat([float(r.num_turns) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def num_branches(self) -> Stat:
|
||||
return Stat([float(r.num_branches) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def timing(self) -> TimingMetrics:
|
||||
return TimingMetrics(self.rollouts)
|
||||
|
||||
@property
|
||||
def metrics(self) -> CustomMetrics:
|
||||
"""Env custom ``@metric`` outputs, keyed by name (``metrics.metrics["acc"].mean()``)."""
|
||||
return CustomMetrics(self.rollouts, "metrics")
|
||||
|
||||
@property
|
||||
def rewards(self) -> CustomMetrics:
|
||||
"""Per-component reward breakdown, keyed by name (summed into the scalar ``reward``)."""
|
||||
return CustomMetrics(self.rollouts, "rewards")
|
||||
|
||||
# Boolean rate metrics (0/1 distributions — ``.mean()`` is the rate)
|
||||
@property
|
||||
def is_truncated(self) -> Stat:
|
||||
return Stat([float(r.is_truncated) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def is_completed(self) -> Stat:
|
||||
return Stat([float(r.is_completed) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def has_error(self) -> Stat:
|
||||
return Stat([float(r.has_error) for r in self.rollouts])
|
||||
|
||||
def stop_conditions(self) -> dict[str, float]:
|
||||
"""``generation_truncated`` over all rollouts, then each recorded ``stop_condition``'s rate
|
||||
over the rollouts that recorded one."""
|
||||
out = {
|
||||
"generation_truncated": sum(
|
||||
1 for r in self.rollouts if r.is_truncated and r.stop_condition != "prompt_too_long"
|
||||
)
|
||||
/ len(self.rollouts)
|
||||
}
|
||||
conditions = [r.stop_condition for r in self.rollouts if r.stop_condition is not None]
|
||||
for condition in sorted(set(conditions)):
|
||||
out[condition] = conditions.count(condition) / len(conditions)
|
||||
return out
|
||||
|
||||
def error_types(self) -> dict[str, int]:
|
||||
"""Count of errored rollouts by error type (the rollout's last error — e.g. ``Cancelled``,
|
||||
``ProviderError``)."""
|
||||
types = [r.error.type for r in self.rollouts if r.has_error]
|
||||
return {t: types.count(t) for t in sorted(set(types))}
|
||||
|
||||
def solve_rates(self) -> dict[str, float]:
|
||||
"""Per-group solve rates, assuming binary 0/1 rewards (unspecified for other reward ranges):
|
||||
``solved_none`` (the group earned no reward), ``solved_all`` (every rollout scored 1.0), and
|
||||
``solved_some`` (the mixed remainder — the GRPO-signal groups)."""
|
||||
groups: dict = {}
|
||||
for r in self.rollouts:
|
||||
groups.setdefault(r.group_id, []).append(r)
|
||||
n_groups = len(groups)
|
||||
solved_none = sum(1 for g in groups.values() if sum(r.reward for r in g) == 0)
|
||||
solved_all = sum(1 for g in groups.values() if all(r.reward == 1.0 for r in g))
|
||||
return {
|
||||
"solved_none": solved_none / n_groups,
|
||||
"solved_all": solved_all / n_groups,
|
||||
"solved_some": 1 - (solved_none + solved_all) / n_groups,
|
||||
}
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
"""The common metric dict for one ``{prefix}/{subset}`` slice. Empty input → ``{}``."""
|
||||
if not self.rollouts:
|
||||
return {}
|
||||
p = f"{prefix}/{subset}"
|
||||
out: dict[str, float] = {}
|
||||
out |= self.num_total_tokens.to_dict(f"{p}/num_total_tokens")
|
||||
out |= self.num_input_tokens.to_dict(f"{p}/num_input_tokens")
|
||||
out |= self.num_output_tokens.to_dict(f"{p}/num_output_tokens")
|
||||
out |= self.num_turns.to_dict(f"{p}/num_turns")
|
||||
out |= self.num_branches.to_dict(f"{p}/num_branches")
|
||||
out |= self.timing.to_dict(f"{p}/timing")
|
||||
out |= self.metrics.to_dict(f"{p}/metrics")
|
||||
out |= self.rewards.to_dict(f"{p}/rewards")
|
||||
out[f"{p}/is_truncated/mean"] = self.is_truncated.mean()
|
||||
out[f"{p}/is_completed/mean"] = self.is_completed.mean()
|
||||
# errors live only on the `all` subset (effective drops them), so emit the rate + the
|
||||
# per-type counts there only
|
||||
if subset == "all":
|
||||
out[f"{p}/has_error/mean"] = self.has_error.mean()
|
||||
out |= {f"{p}/error/{t}": float(count) for t, count in self.error_types().items()}
|
||||
out |= {f"{p}/stop_condition/{k}": v for k, v in self.stop_conditions().items()}
|
||||
out |= {f"{p}/{k}": v for k, v in self.solve_rates().items()}
|
||||
return out
|
||||
|
||||
|
||||
class TrainMetrics(RolloutMetrics):
|
||||
"""Common metrics plus the reward distribution and filter-pipeline rates."""
|
||||
|
||||
@property
|
||||
def reward(self) -> Stat:
|
||||
return Stat([float(r.reward) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def is_trainable(self) -> Stat:
|
||||
return Stat([float(r.is_trainable) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def is_filtered(self) -> Stat:
|
||||
return Stat([float(r.is_filtered) for r in self.rollouts])
|
||||
|
||||
def filter_rates(self) -> dict[str, float]:
|
||||
"""Per-filter detection rate over all rollouts."""
|
||||
names = sorted({name for r in self.rollouts for name in r.filter_results})
|
||||
return {
|
||||
name: sum(1 for r in self.rollouts if r.filter_results.get(name)) / len(self.rollouts) for name in names
|
||||
}
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
out = super().to_wandb(prefix=prefix, subset=subset)
|
||||
if not self.rollouts:
|
||||
return out
|
||||
p = f"{prefix}/{subset}"
|
||||
out |= self.reward.to_dict(f"{p}/reward")
|
||||
out[f"{p}/is_trainable/mean"] = self.is_trainable.mean()
|
||||
out[f"{p}/is_filtered/mean"] = self.is_filtered.mean()
|
||||
out |= {f"{p}/filters/{k}/mean": v for k, v in self.filter_rates().items()}
|
||||
return out
|
||||
|
||||
|
||||
class EvalMetrics(RolloutMetrics):
|
||||
"""Common metrics plus the ``avg@<group_size>`` score and (on the effective subset, for
|
||||
binary-reward tasks) pass@k / pass^k. ``group_size`` (the ``avg@k`` k) is supplied by the
|
||||
container so the ``all`` and ``effective`` subsets share one stable key."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout], group_size: int) -> None:
|
||||
super().__init__(rollouts)
|
||||
self.group_size = group_size
|
||||
|
||||
@property
|
||||
def reward(self) -> Stat:
|
||||
return Stat([float(r.reward) for r in self.rollouts])
|
||||
|
||||
def pass_at_k(self) -> dict[str, float]:
|
||||
"""pass@k / pass^k averaged over examples; ``{}`` for non-binary rewards."""
|
||||
rewards = [r.reward for r in self.rollouts]
|
||||
if not set(rewards).issubset({0.0, 1.0}):
|
||||
return {}
|
||||
by_example: dict = {}
|
||||
for r in self.rollouts:
|
||||
by_example.setdefault(r.group_id, []).append(r.reward)
|
||||
per_example = [compute_pass_metrics(rs) for rs in by_example.values()]
|
||||
keys = sorted({k for d in per_example for k in d})
|
||||
return {k: sum(d[k] for d in per_example if k in d) / sum(1 for d in per_example if k in d) for k in keys}
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
out = super().to_wandb(prefix=prefix, subset=subset)
|
||||
if not self.rollouts:
|
||||
return out
|
||||
p = f"{prefix}/{subset}"
|
||||
out[f"{p}/avg@{self.group_size}"] = self.reward.mean()
|
||||
if subset == "effective":
|
||||
out |= {f"{p}/{k}": v for k, v in self.pass_at_k().items()}
|
||||
return out
|
||||
|
||||
|
||||
class TrainRollouts:
|
||||
"""A list of train rollouts (everything that came back, errored + filtered included). ``effective``
|
||||
is the clean subset (a view of the same traces); ``metrics`` builds ``TrainMetrics`` over them."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout] | None = None) -> None:
|
||||
self.rollouts = rollouts if rollouts is not None else []
|
||||
|
||||
def append(self, rollout: Rollout) -> None:
|
||||
self.rollouts.append(rollout)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.rollouts)
|
||||
|
||||
def __iter__(self) -> Iterator[Rollout]:
|
||||
return iter(self.rollouts)
|
||||
|
||||
@property
|
||||
def effective(self) -> TrainRollouts:
|
||||
return TrainRollouts([r for r in self.rollouts if not r.has_error and not r.is_filtered])
|
||||
|
||||
def by_env(self) -> dict[str, TrainRollouts]:
|
||||
grouped: dict[str, list[Rollout]] = {}
|
||||
for r in self.rollouts:
|
||||
grouped.setdefault(r.env_name, []).append(r)
|
||||
return {env: TrainRollouts(rs) for env, rs in grouped.items()}
|
||||
|
||||
@property
|
||||
def metrics(self) -> TrainMetrics:
|
||||
return TrainMetrics(self.rollouts)
|
||||
|
||||
|
||||
class EvalRollouts:
|
||||
"""A list of eval rollouts (errored included). ``effective`` is the non-errored subset (a view).
|
||||
``group_size`` (rollouts per example, the ``avg@k`` k) is derived from the full epoch and carried
|
||||
onto ``effective`` so both subsets share one stable key; ``metrics`` builds ``EvalMetrics``."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout] | None = None, group_size: int | None = None) -> None:
|
||||
self.rollouts = rollouts if rollouts is not None else []
|
||||
self._group_size = group_size
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.rollouts)
|
||||
|
||||
def __iter__(self) -> Iterator[Rollout]:
|
||||
return iter(self.rollouts)
|
||||
|
||||
@property
|
||||
def group_size(self) -> int:
|
||||
"""The largest group (equals the configured group size whenever one example kept all its
|
||||
rollouts); a subview carries its parent's value so ``avg@k`` doesn't drift across subsets."""
|
||||
if self._group_size is not None:
|
||||
return self._group_size
|
||||
counts: dict = {}
|
||||
for r in self.rollouts:
|
||||
counts[r.group_id] = counts.get(r.group_id, 0) + 1
|
||||
return max(counts.values(), default=0)
|
||||
|
||||
@property
|
||||
def effective(self) -> EvalRollouts:
|
||||
return EvalRollouts([r for r in self.rollouts if not r.has_error], group_size=self.group_size)
|
||||
|
||||
@property
|
||||
def metrics(self) -> EvalMetrics:
|
||||
return EvalMetrics(self.rollouts, self.group_size)
|
||||
|
||||
@@ -7,9 +7,10 @@ and drives the pipeline. Components are single-purpose:
|
||||
discriminated by ``kind``) on its queue.
|
||||
- ``TrainSink`` ingests train rollouts (tokenize → advantages → filters)
|
||||
and returns a ``TrainBatch`` when the threshold is met.
|
||||
- ``EvalSink`` ingests eval rollouts and returns an ``EvalBatch`` (with
|
||||
per-env metrics) on epoch completion.
|
||||
- ``MetricsBuilder`` builds the per-step train W&B dict.
|
||||
- ``EvalSink`` ingests eval rollouts and returns an ``EvalBatch`` (the full
|
||||
returned cohort) on epoch completion.
|
||||
- ``TrainRollouts`` / ``EvalRollouts`` carry the rollouts and build the per-step W&B metrics
|
||||
(``batch.rollouts.metrics`` / ``.effective.metrics``).
|
||||
- ``WeightWatcher`` advances ``Policy`` and notifies observers.
|
||||
- ``PeriodicLogger`` polls the components on a shared interval for the
|
||||
``_timestamp``-axis pipeline log.
|
||||
@@ -44,7 +45,6 @@ from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.filters import setup_filters
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.metrics import MetricsBuilder
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
@@ -124,7 +124,6 @@ class Orchestrator:
|
||||
train_sink: TrainSink
|
||||
dispatcher: RolloutDispatcher
|
||||
watcher: WeightWatcher
|
||||
metrics: MetricsBuilder
|
||||
lag_monitor: EventLoopLagMonitor
|
||||
periodic_logger: PeriodicLogger
|
||||
|
||||
@@ -345,7 +344,6 @@ class Orchestrator:
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
)
|
||||
self.metrics = MetricsBuilder(config)
|
||||
self.train_sink = TrainSink(
|
||||
config,
|
||||
tokenizer=self.tokenizer,
|
||||
@@ -495,23 +493,25 @@ class Orchestrator:
|
||||
)
|
||||
return
|
||||
|
||||
if batch.metrics.n_trainable == 0:
|
||||
if not batch.samples:
|
||||
self.consecutive_empty_batches += 1
|
||||
get_logger().warning(
|
||||
f"Step {step}: post-batch filters dropped all {len(batch.rollouts)} rollouts "
|
||||
f"Step {step}: empty train batch (0 of {len(batch.rollouts)} generated rollouts shipped — "
|
||||
f"all errored or filtered out) "
|
||||
f"(consecutive empty batches: {self.consecutive_empty_batches}/{MAX_CONSECUTIVE_EMPTY_BATCHES})"
|
||||
)
|
||||
if self.consecutive_empty_batches >= MAX_CONSECUTIVE_EMPTY_BATCHES:
|
||||
raise RuntimeError(
|
||||
f"{self.consecutive_empty_batches} consecutive zero-trainable batches — "
|
||||
f"{self.consecutive_empty_batches} consecutive empty train batches — "
|
||||
"check filter config (pre_batch_filters / post_batch_filters) or task difficulty."
|
||||
)
|
||||
return
|
||||
self.consecutive_empty_batches = 0
|
||||
if batch.metrics.n_trainable / len(batch.rollouts) <= 0.1:
|
||||
n_trainable = sum(1 for r in batch.rollouts if r.is_trainable)
|
||||
if n_trainable / len(batch.rollouts) <= 0.1:
|
||||
get_logger().warning(
|
||||
f"Only {batch.metrics.n_trainable}/{len(batch.rollouts)} rollouts in the batch are trainable "
|
||||
f"({batch.metrics.n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
|
||||
f"Only {n_trainable}/{len(batch.rollouts)} generated rollouts are trainable "
|
||||
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
|
||||
)
|
||||
|
||||
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); to_record
|
||||
@@ -525,23 +525,51 @@ class Orchestrator:
|
||||
self.update_dispatch_gate()
|
||||
trim_process_memory()
|
||||
|
||||
metrics = self.metrics.build(
|
||||
step=step,
|
||||
rollouts=batch.rollouts,
|
||||
metrics=batch.metrics,
|
||||
progress=self.progress,
|
||||
step_time=step_time,
|
||||
save_ckpt_time=save_ckpt_time,
|
||||
pre_filter_seen=self.train_sink.pre_filter_seen,
|
||||
pre_filter_dropped=self.train_sink.pre_filter_dropped,
|
||||
pre_filter_dropped_by_name=dict(self.train_sink.pre_filter_dropped_by_name),
|
||||
)
|
||||
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
|
||||
# full arrival window (errored + filtered included); ``.effective`` is the clean subset.
|
||||
effective = batch.rollouts.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
|
||||
for env_name, env_pool in pool.by_env().items():
|
||||
metrics |= env_pool.metrics.to_wandb(prefix=f"train/{env_name}", subset=subset)
|
||||
|
||||
# Progress / timing / env-share / pre-filter accounting (assembled here, not in the metrics
|
||||
# objects). ``num_tokens`` is over the full arrival window; the input/output breakdown is over
|
||||
# the effective (shipped) subset, summing the same ``vf.Trace`` token properties the metric
|
||||
# matrix reports.
|
||||
num_tokens = sum(r.num_total_tokens for r in batch.rollouts)
|
||||
num_input = sum(r.num_input_tokens for r in effective)
|
||||
num_output = sum(r.num_output_tokens for r in effective)
|
||||
num_rollouts = len(batch.rollouts)
|
||||
num_unique_examples = len({r.group_id for r in batch.rollouts})
|
||||
metrics |= {
|
||||
"progress/tokens": num_tokens,
|
||||
"progress/input_tokens": num_input,
|
||||
"progress/output_tokens": num_output,
|
||||
"progress/rollouts": num_rollouts,
|
||||
"progress/tasks": num_unique_examples,
|
||||
"progress/total_tokens": self.progress.total_tokens,
|
||||
"progress/total_rollouts": self.progress.total_samples,
|
||||
"progress/total_tasks": self.progress.total_problems,
|
||||
"time/step": step_time,
|
||||
"time/save_ckpt": save_ckpt_time,
|
||||
"step": step,
|
||||
}
|
||||
for env_name, env_pool in batch.rollouts.by_env().items():
|
||||
metrics[f"batch/{env_name}"] = len(env_pool) / len(batch.rollouts)
|
||||
if self.train_sink.pre_filter_seen > 0:
|
||||
metrics["pre_filters/all/dropped_rate"] = (
|
||||
self.train_sink.pre_filter_dropped / self.train_sink.pre_filter_seen
|
||||
)
|
||||
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
|
||||
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
|
||||
self.monitor.log(metrics, step=step)
|
||||
self.monitor.log_samples(batch.rollouts, step=step)
|
||||
self.monitor.log_samples(effective.rollouts, step=step)
|
||||
self.monitor.log_distributions(
|
||||
distributions={
|
||||
"rewards": [r.reward for r in batch.rollouts],
|
||||
"advantages": [a for r in batch.rollouts if (a := r.scalar_advantage()) is not None],
|
||||
"rewards": [r.reward for r in effective],
|
||||
"advantages": [a for r in effective if (a := r.scalar_advantage()) is not None],
|
||||
},
|
||||
step=step,
|
||||
)
|
||||
@@ -552,14 +580,11 @@ class Orchestrator:
|
||||
self.usage_reporter.report_training_usage(
|
||||
run_id=run_id,
|
||||
step=step,
|
||||
tokens=batch.metrics.num_prefill_tokens + batch.metrics.num_decode_tokens,
|
||||
tokens=num_input + num_output,
|
||||
)
|
||||
if self.heart is not None:
|
||||
self.heart.beat()
|
||||
|
||||
num_rollouts = len(batch.rollouts)
|
||||
num_unique_examples = len({r.group_id for r in batch.rollouts})
|
||||
num_tokens = sum(r.total_tokens for r in batch.rollouts)
|
||||
self.progress.total_tokens += num_tokens
|
||||
self.progress.total_samples += num_rollouts
|
||||
self.progress.total_problems += num_unique_examples
|
||||
@@ -655,50 +680,42 @@ class Orchestrator:
|
||||
return body, payload
|
||||
|
||||
def log_train_batch(self, batch: TrainBatch, *, step: int, step_time: float) -> None:
|
||||
"""Per-step ``Step …`` success line. Multi-env runs append an
|
||||
indented ``╰─`` line per env. ``Error`` is relative to arrivals at
|
||||
the sink (errored rollouts may have been group-dropped before
|
||||
reaching ``batch.rollouts``)."""
|
||||
n_arrivals_total = sum(batch.metrics.arrivals_by_env.values())
|
||||
n_errors_total = sum(batch.metrics.errors_by_env.values())
|
||||
n_survivors = len(batch.rollouts)
|
||||
n_trainable = batch.metrics.n_trainable
|
||||
error_rate = (n_errors_total / n_arrivals_total) if n_arrivals_total else 0.0
|
||||
trainable_rate = (n_trainable / n_survivors) if n_survivors else 0.0
|
||||
reward_mean = sum(r.reward for r in batch.rollouts) / max(n_survivors, 1)
|
||||
max_off_policy = max((r.off_policy_steps for r in batch.rollouts), default=0)
|
||||
turns_mean = sum(r.num_turns for r in batch.rollouts) / max(n_survivors, 1)
|
||||
branches_mean = sum(r.num_branches for r in batch.rollouts) / max(n_survivors, 1)
|
||||
truncation_rate = sum(1 for r in batch.rollouts if r.is_truncated) / max(n_survivors, 1)
|
||||
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
|
||||
``Error`` is the sink-level rate (errored arrivals / total arrivals, over the full window);
|
||||
the quality metrics are over the effective (clean, trained-on) subset; ``Trainable`` is
|
||||
relative to all generated rollouts."""
|
||||
rollouts = batch.rollouts
|
||||
effective = rollouts.effective
|
||||
eff = effective.metrics
|
||||
n_generated = len(rollouts)
|
||||
n_trainable = sum(1 for r in rollouts if r.is_trainable)
|
||||
trainable_rate = (n_trainable / n_generated) if n_generated else 0.0
|
||||
max_off_policy = max((r.off_policy_steps for r in effective), default=0)
|
||||
|
||||
head = (
|
||||
f"Step {step} | {format_time(step_time):>7} | Reward {reward_mean:.4f} | "
|
||||
f"Trainable {n_trainable}/{n_survivors} ({trainable_rate:.1%}) | "
|
||||
f"Turns {turns_mean:.1f} | Branches {branches_mean:.1f} | Max Off-Policy {max_off_policy} | "
|
||||
f"Error {error_rate:.1%} | Truncation {truncation_rate:.1%}"
|
||||
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Trainable {n_trainable}/{n_generated} ({trainable_rate:.1%}) | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max_off_policy} | "
|
||||
f"Error {rollouts.metrics.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
if len(self.train_envs) <= 1:
|
||||
get_logger().success(head)
|
||||
return
|
||||
|
||||
env_names = sorted(set(batch.metrics.arrivals_by_env) | {r.env_name for r in batch.rollouts})
|
||||
name_width = max(len(n) for n in env_names) if env_names else 0
|
||||
by_env = rollouts.by_env()
|
||||
name_width = max((len(n) for n in by_env), default=0)
|
||||
lines = [head]
|
||||
for env_name in env_names:
|
||||
env_rollouts = [r for r in batch.rollouts if r.env_name == env_name]
|
||||
n_env_arrivals = batch.metrics.arrivals_by_env.get(env_name, 0)
|
||||
n_env_errors = batch.metrics.errors_by_env.get(env_name, 0)
|
||||
ratio = (n_env_arrivals / n_arrivals_total) if n_arrivals_total else 0.0
|
||||
env_error_rate = (n_env_errors / n_env_arrivals) if n_env_arrivals else 0.0
|
||||
env_reward = (sum(r.reward for r in env_rollouts) / len(env_rollouts)) if env_rollouts else 0.0
|
||||
env_max_off_policy = max((r.off_policy_steps for r in env_rollouts), default=0)
|
||||
env_turns = sum(r.num_turns for r in env_rollouts) / len(env_rollouts) if env_rollouts else 0.0
|
||||
env_branches = sum(r.num_branches for r in env_rollouts) / len(env_rollouts) if env_rollouts else 0.0
|
||||
env_truncation = sum(1 for r in env_rollouts if r.is_truncated) / len(env_rollouts) if env_rollouts else 0.0
|
||||
for env_name in sorted(by_env):
|
||||
pool = by_env[env_name]
|
||||
env_eff_pool = pool.effective
|
||||
env_eff = env_eff_pool.metrics
|
||||
ratio = (len(pool) / n_generated) if n_generated else 0.0
|
||||
lines.append(
|
||||
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_reward:.4f} | "
|
||||
f"Turns {env_turns:.1f} | Branches {env_branches:.1f} | Max Off-Policy {env_max_off_policy} | "
|
||||
f"Error {env_error_rate:.1%} | Truncation {env_truncation:.1%}"
|
||||
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
|
||||
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max((r.off_policy_steps for r in env_eff_pool), default=0)} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Truncation {env_eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
|
||||
@@ -706,7 +723,7 @@ class Orchestrator:
|
||||
"""Persist + log one completed eval epoch (save_rollouts,
|
||||
monitor.log_eval_samples, monitor.log)."""
|
||||
if not batch.rollouts:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no surviving rollouts, skipping log")
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
|
||||
return
|
||||
|
||||
rollout_dicts = [r.to_record() for r in batch.rollouts]
|
||||
@@ -723,21 +740,27 @@ class Orchestrator:
|
||||
get_logger().warning(
|
||||
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
|
||||
)
|
||||
metrics = batch.metrics.to_wandb_dict(env_name=batch.env_name, step=batch.step)
|
||||
# Rollout metrics over {all,effective} (eval batches are per-env, so no `agg` axis).
|
||||
# ``effective`` = non-errored; pass@k / pass^k only over the effective set.
|
||||
rollouts = batch.rollouts
|
||||
effective = rollouts.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", rollouts), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
|
||||
metrics["step"] = float(batch.step)
|
||||
self.monitor.log(metrics, step=batch.step)
|
||||
|
||||
n_total = batch.metrics.n_rollouts
|
||||
error_rate = ((batch.metrics.n_cancelled + batch.metrics.n_errored) / n_total) if n_total else 0.0
|
||||
# Success line — reward / turns / truncation over the effective set, error rate + branches
|
||||
# over the full returned cohort. ``Stat.mean()`` is 0.0 for an empty set.
|
||||
eff, full = effective.metrics, rollouts.metrics
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
branches_mean = sum(r.num_branches for r in batch.rollouts) / len(batch.rollouts)
|
||||
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
|
||||
f"Turns {batch.metrics.num_turns_mean:.1f} | Branches {branches_mean:.1f} | "
|
||||
f"Error {error_rate:.1%} | Truncation {batch.metrics.truncation_rate:.1%}"
|
||||
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {full.num_branches.mean():.1f} | "
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
|
||||
async def maybe_save_ckpt(self, step: int) -> float:
|
||||
|
||||
@@ -23,8 +23,9 @@ from collections import defaultdict
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.filters import RolloutFilter, apply_filters
|
||||
from prime_rl.orchestrator.metrics import TrainRollouts
|
||||
from prime_rl.orchestrator.trajectories import trace_to_samples
|
||||
from prime_rl.orchestrator.types import Rollout, TrainBatch, TrainBatchMetrics
|
||||
from prime_rl.orchestrator.types import Rollout, TrainBatch
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -59,11 +60,12 @@ class TrainSink:
|
||||
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
|
||||
# isn't unique — the same task can be re-sampled while an
|
||||
# earlier group is still in flight
|
||||
self.pending_rollouts: TrainRollouts = TrainRollouts()
|
||||
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
|
||||
self.pending_batch: list[Rollout] = []
|
||||
# Running token total of ``pending_batch`` (token-batched runs), kept in
|
||||
# sync on append/pop so the readiness check never re-walks the uncached
|
||||
# ``Trace.total_tokens`` graph property per arrival.
|
||||
# ``Trace.num_total_tokens`` graph property per arrival.
|
||||
self.pending_tokens: int = 0
|
||||
|
||||
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
|
||||
@@ -71,11 +73,6 @@ class TrainSink:
|
||||
self.pre_filter_dropped = 0
|
||||
self.pre_filter_dropped_by_name: dict[str, int] = {}
|
||||
|
||||
# Per-env arrival / error counters since the last ship; reset in
|
||||
# ``process_batch``. Fuel for the per-env success log breakdown
|
||||
self.arrivals_by_env: dict[str, int] = defaultdict(int)
|
||||
self.errors_by_env: dict[str, int] = defaultdict(int)
|
||||
|
||||
def group_size_for(self, env_name: str) -> int:
|
||||
return self.train_envs.get(env_name).config.group_size
|
||||
|
||||
@@ -123,9 +120,7 @@ class TrainSink:
|
||||
arrival; return a ``TrainBatch`` if the batch threshold is met."""
|
||||
await self.process_rollout(rollout)
|
||||
env_name = rollout.env_name
|
||||
self.arrivals_by_env[env_name] += 1
|
||||
if rollout.has_error:
|
||||
self.errors_by_env[env_name] += 1
|
||||
self.pending_rollouts.append(rollout)
|
||||
self.pending_groups[rollout.group_id].append(rollout)
|
||||
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
|
||||
await self.process_group(rollout.group_id)
|
||||
@@ -216,7 +211,7 @@ class TrainSink:
|
||||
r.is_filtered = False
|
||||
self.pending_batch.append(r)
|
||||
if self.token_batch_size is not None:
|
||||
self.pending_tokens += r.total_tokens
|
||||
self.pending_tokens += r.num_total_tokens
|
||||
|
||||
# Per-group summary. One line per finalized group; per-filter
|
||||
# detection breakdown lives at debug level in ``apply_filters``
|
||||
@@ -243,7 +238,7 @@ class TrainSink:
|
||||
cut = 0
|
||||
running = 0
|
||||
for i, r in enumerate(self.pending_batch):
|
||||
running += r.total_tokens
|
||||
running += r.num_total_tokens
|
||||
cut = i + 1
|
||||
if running >= self.token_batch_size:
|
||||
break
|
||||
@@ -254,46 +249,19 @@ class TrainSink:
|
||||
if self.post_filters:
|
||||
apply_filters(self.post_filters, cohort)
|
||||
|
||||
# Samples are pre-built by ``process_rollout``; ``process_group``
|
||||
# already stamped the advantage stream and loss routing on each sample
|
||||
samples: list[TrainingSample] = []
|
||||
prefill_lens: list[int] = []
|
||||
decode_lens: list[int] = []
|
||||
samples_per_rollout: list[int] = []
|
||||
num_prefill = 0
|
||||
num_decode = 0
|
||||
for r in cohort:
|
||||
samples_per_rollout.append(len(r.samples))
|
||||
prefill = 0
|
||||
decode = 0
|
||||
for sample in r.samples:
|
||||
sample_decode = sum(sample.mask)
|
||||
sample_prefill = len(sample.token_ids) - sample_decode
|
||||
decode += sample_decode
|
||||
prefill += sample_prefill
|
||||
if not r.is_filtered:
|
||||
samples.append(sample)
|
||||
prefill_lens.append(prefill)
|
||||
decode_lens.append(decode)
|
||||
num_prefill += prefill
|
||||
num_decode += decode
|
||||
# Samples are pre-built by ``process_rollout``; ``process_group`` already stamped the
|
||||
# advantage stream and loss routing on each sample. Filtered rollouts don't ship.
|
||||
samples: list[TrainingSample] = [sample for r in cohort if not r.is_filtered for sample in r.samples]
|
||||
|
||||
n_trainable = sum(1 for r in cohort if not r.is_filtered)
|
||||
|
||||
metrics = TrainBatchMetrics(
|
||||
n_trainable=n_trainable,
|
||||
num_prefill_tokens=num_prefill,
|
||||
num_decode_tokens=num_decode,
|
||||
rollout_prefill_lens=prefill_lens,
|
||||
rollout_decode_lens=decode_lens,
|
||||
samples_per_rollout=samples_per_rollout,
|
||||
samples_shipped=len(samples),
|
||||
arrivals_by_env=dict(self.arrivals_by_env),
|
||||
errors_by_env=dict(self.errors_by_env),
|
||||
)
|
||||
self.arrivals_by_env.clear()
|
||||
self.errors_by_env.clear()
|
||||
return TrainBatch(rollouts=cohort, samples=samples, metrics=metrics)
|
||||
# ``rollouts`` is the whole arrival window (errored + filtered + survivors); ``samples`` is
|
||||
# the shipped cohort's trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive
|
||||
# the clean subset + metric views on demand. Reset the window only when the batch actually
|
||||
# ships (non-empty samples) — an empty batch is dropped unlogged by the orchestrator, so keep
|
||||
# accumulating its arrivals (and any overflow) into the next shipped batch's window.
|
||||
rollouts = self.pending_rollouts
|
||||
if samples:
|
||||
self.pending_rollouts = TrainRollouts()
|
||||
return TrainBatch(rollouts=rollouts, samples=samples)
|
||||
|
||||
def reset_pre_filter_stats(self) -> None:
|
||||
self.pre_filter_seen = 0
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""TrainSource: weighted round-robin across train envs, infinite pull.
|
||||
|
||||
Weights default to configured ``ratio`` (when every env sets one) or to
|
||||
per-env dataset size. ``next_example`` reshuffles on cursor exhaustion."""
|
||||
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
|
||||
per env). ``next_example`` reshuffles on cursor exhaustion."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -37,11 +37,7 @@ class TrainSource:
|
||||
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
|
||||
|
||||
self.env_names = [e.name for e in self.envs]
|
||||
configured_ratios = [e.config.ratio for e in self.envs]
|
||||
if all(r is not None for r in configured_ratios):
|
||||
self.weights: list[float] = [float(r) for r in configured_ratios] # type: ignore[arg-type]
|
||||
else:
|
||||
self.weights = [float(len(self.examples[name])) for name in self.env_names]
|
||||
self.weights: list[float] = [float(e.config.ratio) for e in self.envs]
|
||||
|
||||
def next_example(self, available_permits: int) -> dict | None:
|
||||
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
|
||||
|
||||
@@ -75,12 +75,12 @@ def trace_to_samples(
|
||||
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
|
||||
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
|
||||
the trainable (model-sampled) tokens, the context tokens between completions stay masked
|
||||
out. On a rollout error the whole completion is masked out. A branch carrying images also
|
||||
gets `mm_kwargs` (the concatenated pixel tensors) and `mm_token_type_ids` (the renderer's
|
||||
`mm_token_type_id_map` applied to the branch tokens). Branches with no sampled tokens
|
||||
(e.g. an openai client carrying none) yield nothing.
|
||||
out. Errored rollouts are dropped upstream (`TrainSink.process_rollout`), so no error
|
||||
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
|
||||
pixel tensors) and `mm_token_type_ids` (the renderer's `mm_token_type_id_map` applied to
|
||||
the branch tokens). Branches with no sampled tokens (e.g. an openai client carrying none)
|
||||
yield nothing.
|
||||
"""
|
||||
has_error = trace.has_error
|
||||
samples: list[TrainingSample] = []
|
||||
for branch in trace.branches:
|
||||
mask = branch.sampled_mask
|
||||
@@ -97,7 +97,7 @@ def trace_to_samples(
|
||||
samples.append(
|
||||
TrainingSample(
|
||||
token_ids=token_ids,
|
||||
mask=[m and not has_error for m in mask],
|
||||
mask=mask,
|
||||
logprobs=branch.logprobs,
|
||||
temperatures=[], # filled by TrainSink.process_group
|
||||
env_name=env_name,
|
||||
@@ -108,6 +108,6 @@ def trace_to_samples(
|
||||
)
|
||||
if not samples:
|
||||
get_logger().warning(
|
||||
f"No trainable samples (error={has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
|
||||
f"No trainable samples (error={trace.has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
|
||||
)
|
||||
return samples
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Generic, Literal, Protocol
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Generic, Literal, Protocol
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import ConfigDict, Field
|
||||
@@ -12,6 +12,9 @@ from verifiers.v1.task import TaskT
|
||||
|
||||
from prime_rl.transport import TrainingSample
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.metrics import EvalRollouts, TrainRollouts
|
||||
|
||||
|
||||
@dataclass
|
||||
class Policy:
|
||||
@@ -122,86 +125,33 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
nonzero = [a for a in self.advantages if a != 0.0]
|
||||
return sum(nonzero) / len(nonzero) if nonzero else 0.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrainBatchMetrics:
|
||||
"""Per-batch aggregates from ``TrainSink.process_batch``; consumed by
|
||||
``MetricsBuilder.build``. ``arrivals_by_env`` / ``errors_by_env`` count
|
||||
rollouts at the sink."""
|
||||
|
||||
n_trainable: int
|
||||
num_prefill_tokens: int
|
||||
num_decode_tokens: int
|
||||
rollout_prefill_lens: list[int]
|
||||
rollout_decode_lens: list[int]
|
||||
samples_per_rollout: list[int]
|
||||
samples_shipped: int
|
||||
arrivals_by_env: dict[str, int] = field(default_factory=dict)
|
||||
errors_by_env: dict[str, int] = field(default_factory=dict)
|
||||
@property
|
||||
def is_trainable(self) -> bool:
|
||||
"""Whether the rollout carries a training signal — a nonzero advantage on some token. A
|
||||
uniform-reward GRPO group (all-zero advantages) or an unscored rollout has no gradient."""
|
||||
return bool(self.advantages) and any(a != 0.0 for a in self.advantages)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrainBatch:
|
||||
"""``samples`` is the trainer-bound payload (post-filter survivors);
|
||||
``rollouts`` is the full cohort kept for orchestrator-side I/O."""
|
||||
"""``rollouts`` is the full arrival window since the last ship (errored + filtered included; its
|
||||
``.effective`` / ``.metrics`` views drive logging). ``samples`` is the trainer-bound payload (the
|
||||
shipped cohort's post-filter survivors) — an empty list means nothing ships, which would stall the
|
||||
trainer. Trainable counts derive from ``rollouts`` (``r.is_trainable``) and token totals from
|
||||
``samples``, so neither is carried as a field."""
|
||||
|
||||
rollouts: list[Rollout]
|
||||
rollouts: TrainRollouts
|
||||
samples: list[TrainingSample]
|
||||
metrics: TrainBatchMetrics
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvalBatchMetrics:
|
||||
"""Typed per-batch metrics from ``EvalSink.process_batch``. Final wandb
|
||||
dict derived via ``to_wandb_dict`` at log time."""
|
||||
|
||||
n_rollouts: int
|
||||
n_cancelled: int
|
||||
n_errored: int
|
||||
n_examples: int = 0
|
||||
group_size: int = 1
|
||||
reward_mean: float = 0.0
|
||||
completion_len_mean: float = 0.0
|
||||
completion_len_max: float = 0.0
|
||||
completion_len_min: float = 0.0
|
||||
truncation_rate: float = 0.0
|
||||
no_response_rate: float = 0.0
|
||||
num_turns_mean: float = 0.0
|
||||
num_turns_min: float = 0.0
|
||||
num_turns_max: float = 0.0
|
||||
pass_at_k: dict[str, float] = field(default_factory=dict)
|
||||
|
||||
def to_wandb_dict(self, *, env_name: str, step: int) -> dict[str, float]:
|
||||
prefix = f"eval/{env_name}"
|
||||
out: dict[str, float] = {
|
||||
"step": float(step),
|
||||
f"{prefix}/cancelled_count": float(self.n_cancelled),
|
||||
f"{prefix}/errored_count": float(self.n_errored),
|
||||
}
|
||||
if self.n_examples > 0:
|
||||
out[f"{prefix}/avg@{self.group_size}"] = self.reward_mean
|
||||
out[f"{prefix}/completion_len/mean"] = self.completion_len_mean
|
||||
out[f"{prefix}/completion_len/max"] = self.completion_len_max
|
||||
out[f"{prefix}/completion_len/min"] = self.completion_len_min
|
||||
out[f"{prefix}/is_truncated/mean"] = self.truncation_rate
|
||||
out[f"{prefix}/no_response/mean"] = self.no_response_rate
|
||||
out[f"{prefix}/num_turns/mean"] = self.num_turns_mean
|
||||
out[f"{prefix}/num_turns/min"] = self.num_turns_min
|
||||
out[f"{prefix}/num_turns/max"] = self.num_turns_max
|
||||
for k, v in self.pass_at_k.items():
|
||||
out[f"{prefix}/{k}"] = v
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvalBatch:
|
||||
"""One env's eval epoch. ``metrics`` is the typed view from
|
||||
``EvalSink.process_batch``."""
|
||||
"""One env's eval epoch. ``rollouts`` is the full returned cohort (errored included); its
|
||||
``.effective`` / ``.metrics`` views drive logging."""
|
||||
|
||||
env_name: str
|
||||
step: int
|
||||
rollouts: list[Rollout]
|
||||
metrics: EvalBatchMetrics
|
||||
rollouts: EvalRollouts
|
||||
|
||||
|
||||
class VersionObserver(Protocol):
|
||||
|
||||
@@ -2,12 +2,12 @@ import asyncio
|
||||
import ctypes
|
||||
import gc
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import orjson
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.utils.client import setup_inference_pool
|
||||
@@ -50,14 +50,13 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
return renderer, inference_pool
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[dict], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
def save_rollouts(rollouts: list[dict], path: Path) -> None:
|
||||
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "wb") as f:
|
||||
for rollout in rollouts:
|
||||
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
|
||||
f.write(orjson.dumps(row, default=str, option=opts))
|
||||
f.write(orjson.dumps(rollout, default=str, option=opts))
|
||||
|
||||
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
@@ -93,16 +92,6 @@ def trim_process_memory() -> None:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
|
||||
|
||||
|
||||
def get_tool_response_len(trace: vf.Trace) -> int:
|
||||
"""Total tool-response tokens consumed across the whole rollout, read from a
|
||||
harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`, deduped
|
||||
across turns/branches/sub-RLMs). Returns 0 when no such metric is present."""
|
||||
for key, value in (trace.metrics or {}).items():
|
||||
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
return 0
|
||||
|
||||
|
||||
def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_timeout: int | None = None) -> Path:
|
||||
"""Get the weight directory for a given checkpoint step.
|
||||
|
||||
@@ -146,3 +135,25 @@ def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_
|
||||
return broadcast_weight_dir
|
||||
|
||||
raise FileNotFoundError(f"No weight directory found for checkpoint step {step}")
|
||||
|
||||
|
||||
def compute_pass_metrics(rewards: list[float]) -> dict[str, float]:
|
||||
"""Unbiased pass@k and pass^k for one example's binary (0/1) rewards.
|
||||
|
||||
pass@k = 1 - C(n-c, k) / C(n, k) (at least one of k samples correct)
|
||||
pass^k = C(c, k) / C(n, k) (all k samples correct)
|
||||
|
||||
``n`` = number of rewards, ``c`` = number correct, ``k`` = powers of 2 in [1, n].
|
||||
``math.comb`` returns 0 when ``k`` exceeds its first argument, so the edge cases
|
||||
(``n - c < k`` → pass@k = 1; ``c < k`` → pass^k = 0) fall out without branching.
|
||||
"""
|
||||
n = len(rewards)
|
||||
c = sum(1 for r in rewards if r == 1.0)
|
||||
out: dict[str, float] = {}
|
||||
k = 1
|
||||
while k <= n:
|
||||
n_choose_k = math.comb(n, k)
|
||||
out[f"pass@{k}"] = 1.0 - math.comb(n - c, k) / n_choose_k
|
||||
out[f"pass^{k}"] = math.comb(c, k) / n_choose_k
|
||||
k *= 2
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
max_num = -1
|
||||
for key in state_dict:
|
||||
if not key.startswith(layer_prefix):
|
||||
continue
|
||||
layer_num_str = key[len(layer_prefix) :].split(".")[0]
|
||||
if layer_num_str.isdigit():
|
||||
max_num = max(max_num, int(layer_num_str))
|
||||
return max_num + 1
|
||||
@@ -3,6 +3,8 @@ import re
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def get_num_experts_from_state_dict(state_dict: dict[str, Tensor], layer_idx: int) -> int:
|
||||
"""Get the number of experts from the HF state dict for a given layer."""
|
||||
@@ -122,26 +124,15 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> Non
|
||||
del state_dict[key]
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum layer number from the state dict."""
|
||||
max_layer = -1
|
||||
for key in state_dict.keys():
|
||||
match = re.search(r"model\.layers\.(\d+)\.", key)
|
||||
if match:
|
||||
layer_idx = int(match.group(1))
|
||||
max_layer = max(max_layer, layer_idx)
|
||||
return max_layer
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]) -> None:
|
||||
"""Convert all MoE layers from HF format to TT format in-place."""
|
||||
max_layer = get_max_layer_num(state_dict)
|
||||
for layer_idx in range(max_layer + 1):
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for layer_idx in range(num_layers):
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]) -> None:
|
||||
"""Convert all MoE layers from TT format to HF format in-place."""
|
||||
max_layer = get_max_layer_num(state_dict)
|
||||
for layer_idx in range(max_layer + 1):
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for layer_idx in range(num_layers):
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
|
||||
@@ -19,6 +19,11 @@ from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
@@ -30,21 +35,6 @@ from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_varlen_func = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_3_varlen_func = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_4_varlen_func = None # type: ignore
|
||||
|
||||
from .configuration_afmoe import AfmoeConfig
|
||||
from .converting_afmoe import (
|
||||
convert_hf_layer_to_tt,
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
|
||||
|
||||
def _is_moe_layer(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
|
||||
"""Check if a layer is an MoE layer by looking for the router gate weight."""
|
||||
return f"model.layers.{layer_idx}.mlp.gate.weight" in state_dict
|
||||
|
||||
@@ -185,7 +185,6 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
|
||||
"""
|
||||
# NOTE: We don't use weight scale in this kernel as it produces higher KL mismatch for some reason
|
||||
# This is not a problem result-wise, as it is a constant multiplier
|
||||
_weight_scale = weight_scale
|
||||
S_q, H, D = q.shape
|
||||
S_k = k.shape[0]
|
||||
device = q.device
|
||||
|
||||
@@ -15,10 +15,6 @@ def ceil_div(x: int, y: int) -> int:
|
||||
return (x + y - 1) // y
|
||||
|
||||
|
||||
def align(x: int, y: int) -> int:
|
||||
return ceil_div(x, y) * y
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Layout building
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
return max(int(key.split(".")[2]) for key in state_dict if key.startswith("model.layers.")) + 1
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def _pop_first(state_dict: dict[str, Tensor], keys: tuple[str, ...]) -> Tensor | None:
|
||||
|
||||
@@ -77,7 +77,6 @@ class BCFeedForward(nn.Module):
|
||||
self.w3 = nn.Parameter(torch.empty(hidden_dim, dim))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
# return torch.matmul(self.w2, F.silu(torch.matmul(self.w1, x.T)) * torch.matmul(self.w3, x.T))
|
||||
return torch.matmul(F.silu(torch.matmul(x, self.w1.T)) * torch.matmul(x, self.w3.T), self.w2.T)
|
||||
|
||||
def init_weights(self, init_std: float):
|
||||
|
||||
@@ -115,34 +115,3 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
||||
q_embed = torch.cat([q_embed, q_pass], dim=-1)
|
||||
k_embed = torch.cat([k_embed, k_pass], dim=-1)
|
||||
return q_embed, k_embed
|
||||
|
||||
|
||||
def apply_rotary_pos_emb_interleave(q, k, cos, sin, unsqueeze_dim=1):
|
||||
"""Interleaved RoPE: converts from [r0, i0, r1, i1, ...] layout before applying rotation.
|
||||
|
||||
Args:
|
||||
q (`torch.Tensor`): The query tensor.
|
||||
k (`torch.Tensor`): The key tensor.
|
||||
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
||||
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
||||
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
||||
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
||||
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
||||
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
||||
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
||||
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
||||
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
||||
Returns:
|
||||
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
||||
"""
|
||||
cos = cos.unsqueeze(unsqueeze_dim)
|
||||
sin = sin.unsqueeze(unsqueeze_dim)
|
||||
|
||||
b, h, s, d = q.shape
|
||||
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
||||
b, h, s, d = k.shape
|
||||
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
||||
|
||||
q_embed = (q * cos) + (rotate_half(q) * sin)
|
||||
k_embed = (k * cos) + (rotate_half(k) * sin)
|
||||
return q_embed, k_embed
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
|
||||
@@ -16,6 +16,11 @@ from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, logging
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
|
||||
@@ -30,22 +35,6 @@ from .converting_qwen3_5_moe import (
|
||||
)
|
||||
from .mrope import build_qwen3_5_mrope_position_ids
|
||||
|
||||
# Flash attention imports
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_varlen_func = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_3_varlen_func = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_4_varlen_func = None # type: ignore
|
||||
|
||||
# Flash linear attention imports (for GatedDeltaNet fast path)
|
||||
try:
|
||||
from causal_conv1d import causal_conv1d_fn
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
|
||||
@@ -242,88 +242,6 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
|
||||
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
def load_balancing_loss_func(
|
||||
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
|
||||
num_experts: Optional[int] = None,
|
||||
top_k=2,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
) -> Union[torch.Tensor, int]:
|
||||
r"""
|
||||
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
||||
|
||||
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
|
||||
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
||||
experts is too unbalanced.
|
||||
|
||||
Args:
|
||||
gate_logits:
|
||||
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
||||
shape [batch_size X sequence_length, num_experts].
|
||||
num_experts:
|
||||
Number of experts
|
||||
top_k:
|
||||
The number of experts to route per-token, can be also interpreted as the `top-k` routing
|
||||
parameter.
|
||||
attention_mask (`torch.Tensor`, *optional*):
|
||||
The attention_mask used in forward function
|
||||
shape [batch_size X sequence_length] if not None.
|
||||
|
||||
Returns:
|
||||
The auxiliary loss.
|
||||
"""
|
||||
if gate_logits is None or not isinstance(gate_logits, tuple):
|
||||
return 0
|
||||
|
||||
if isinstance(gate_logits, tuple):
|
||||
compute_device = gate_logits[0].device
|
||||
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
|
||||
|
||||
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
|
||||
|
||||
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
|
||||
|
||||
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
|
||||
|
||||
if attention_mask is None:
|
||||
# Compute the percentage of tokens routed to each experts
|
||||
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
|
||||
|
||||
# Compute the average probability of routing to these experts
|
||||
router_prob_per_expert = torch.mean(routing_weights, dim=0)
|
||||
else:
|
||||
batch_size, sequence_length = attention_mask.shape
|
||||
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
|
||||
|
||||
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
|
||||
expert_attention_mask = (
|
||||
attention_mask[None, :, :, None, None]
|
||||
.expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
|
||||
.reshape(-1, top_k, num_experts)
|
||||
.to(compute_device)
|
||||
)
|
||||
|
||||
# Compute the percentage of tokens routed to each experts
|
||||
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
|
||||
expert_attention_mask, dim=0
|
||||
)
|
||||
|
||||
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
|
||||
router_per_expert_attention_mask = (
|
||||
attention_mask[None, :, :, None]
|
||||
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
|
||||
.reshape(-1, num_experts)
|
||||
.to(compute_device)
|
||||
)
|
||||
|
||||
# Compute the average probability of routing to these experts
|
||||
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
|
||||
router_per_expert_attention_mask, dim=0
|
||||
)
|
||||
|
||||
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
|
||||
return overall_loss * num_experts
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
|
||||
@@ -37,9 +37,6 @@ class PerfCounter:
|
||||
self.gpu_peak_flops = self._get_peak_flops(torch.cuda.get_device_name(torch.device("cuda")))
|
||||
else:
|
||||
self.gpu_peak_flops = 0
|
||||
# If not tie_word_embeddings, we exclude the embedding parameters from the total number of parameters
|
||||
# If tie_word_embeddings, the embedding parameters are already excluded (shared with the LM head)
|
||||
self.num_params = self._get_num_params(model, exclude_embedding=not model.config.tie_word_embeddings)
|
||||
self.num_flop_per_token = self._get_num_flop_per_token(model.config, seq_len=seq_len)
|
||||
|
||||
def count_tokens(self, tokens: int) -> None:
|
||||
@@ -209,23 +206,6 @@ class PerfCounter:
|
||||
|
||||
return flop_per_token
|
||||
|
||||
def _get_num_params(self, model: nn.Module, exclude_embedding: bool = False) -> int:
|
||||
num_params = sum(p.numel() for p in model.parameters())
|
||||
if exclude_embedding:
|
||||
if hasattr(model.lm_head, "weight"):
|
||||
num_params -= model.lm_head.weight.numel()
|
||||
elif hasattr(model.lm_head, "base_layer"): # MultiLoRAModule
|
||||
num_params -= model.lm_head.base_layer.weight.numel()
|
||||
return num_params
|
||||
|
||||
def _count_trainable_params(self) -> int:
|
||||
"""Count trainable parameters (LoRA adapters + modules_to_save)."""
|
||||
trainable_params = 0
|
||||
for param in self.model.parameters():
|
||||
if param.requires_grad:
|
||||
trainable_params += param.numel()
|
||||
return trainable_params
|
||||
|
||||
def _count_lora_adapter_params(self) -> int:
|
||||
"""Count LoRA adapter parameters (sum of lora_A and lora_B across all MultiLoRAModules)."""
|
||||
params = 0
|
||||
|
||||
@@ -11,19 +11,18 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
from vllm.distributed.utils import StatelessProcessGroup
|
||||
|
||||
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.utils import get_world
|
||||
from prime_rl.trainer.weights import get_max_layer_num
|
||||
from prime_rl.utils.client import NCCL_READY_MARKER
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
|
||||
from prime_rl.utils.pathing import sync_wait_for_path
|
||||
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
|
||||
from prime_rl.utils.vlm import get_layer_prefix
|
||||
|
||||
NCCL_READY_MARKER = "NCCL_READY"
|
||||
|
||||
|
||||
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
|
||||
"""Broadcast an integer to a process group using NCCL communicator."""
|
||||
|
||||
@@ -5,7 +5,6 @@ from typing import TypedDict
|
||||
import torch
|
||||
from jaxtyping import Bool, Float, Int
|
||||
from torch import Tensor
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.trainer import FakeDataLoaderConfig
|
||||
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
|
||||
@@ -183,7 +182,6 @@ class DataLoader:
|
||||
dp_world_size: int,
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
config: TransportConfig,
|
||||
):
|
||||
@@ -193,7 +191,6 @@ class DataLoader:
|
||||
self.packer: BasePacker = setup_packer(
|
||||
dp_world_size=dp_world_size,
|
||||
seq_len=seq_len,
|
||||
tokenizer=tokenizer,
|
||||
transport_config=config,
|
||||
pad_to_multiple_of=pad_to_multiple_of,
|
||||
bin_cost=bin_cost,
|
||||
|
||||
@@ -63,20 +63,6 @@ def compute_entropy(shifted_logits: Float[Tensor, "batch seq vocab"]) -> Float[T
|
||||
return entropy
|
||||
|
||||
|
||||
@jaxtyped(typechecker=typechecker)
|
||||
def shift_logits(
|
||||
logits: Float[Tensor, "batch seq vocab"], left_pad_logit: Float[Tensor, "batch 1 vocab"] | None = None
|
||||
) -> Float[Tensor, "batch seq vocab"]:
|
||||
"""Removes final token logits and adds a left pad logit for the first token."""
|
||||
# We drop the last logit because it corresponds to the next token that will be sampled but is not here yet
|
||||
batch, seq, vocab = logits.shape
|
||||
logits = logits[:, :-1, :] # (batch, seq-1, vocab)
|
||||
if left_pad_logit is None:
|
||||
left_pad_logit = torch.zeros(batch, 1, vocab, device=logits.device, dtype=logits.dtype) # (batch, 1, vocab)
|
||||
logits = torch.cat([left_pad_logit, logits], dim=1) # (batch, seq, vocab)
|
||||
return logits
|
||||
|
||||
|
||||
def shift_tensor_left(t: Float[Tensor, "batch seq"]) -> Float[Tensor, "batch seq"]:
|
||||
"""Shifts the tensor one token to the left.
|
||||
|
||||
|
||||
@@ -6,8 +6,6 @@ from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Sequence
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.trainer.batch import prepare_batch
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.transport import (
|
||||
@@ -31,7 +29,6 @@ class BasePacker(ABC):
|
||||
dp_world_size: int,
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
@@ -41,7 +38,6 @@ class BasePacker(ABC):
|
||||
self.dp_world_size = dp_world_size
|
||||
self.seq_len = seq_len
|
||||
self.pad_to_multiple_of = pad_to_multiple_of
|
||||
self.tokenizer = tokenizer
|
||||
self.bin_cost = bin_cost
|
||||
self.receiver = setup_training_batch_receiver(config)
|
||||
shutil.rmtree(get_rollout_dir(self.multi_run_manager.output_dir), ignore_errors=True)
|
||||
@@ -85,12 +81,11 @@ class SinglePacker(BasePacker):
|
||||
dp_world_size: int,
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
):
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, config, bin_cost, start_step)
|
||||
assert self.multi_run_manager.max_runs == 1, "SinglePacker only supports one run"
|
||||
|
||||
def pack(self):
|
||||
@@ -132,12 +127,11 @@ class MultiPacker(BasePacker):
|
||||
dp_world_size: int,
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
):
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, config, bin_cost, start_step)
|
||||
# Per-run buffer: stores (TrainingSample, step) tuples
|
||||
self.buffers: list[deque[tuple[TrainingSample, int]]] = [
|
||||
deque() for _ in range(self.multi_run_manager.max_runs)
|
||||
@@ -351,17 +345,12 @@ def setup_packer(
|
||||
dp_world_size: int,
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
transport_config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
) -> BasePacker:
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
if multi_run_manager.max_runs == 1:
|
||||
return SinglePacker(
|
||||
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
|
||||
)
|
||||
return SinglePacker(dp_world_size, seq_len, pad_to_multiple_of, transport_config, bin_cost, start_step)
|
||||
else:
|
||||
return MultiPacker(
|
||||
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
|
||||
)
|
||||
return MultiPacker(dp_world_size, seq_len, pad_to_multiple_of, transport_config, bin_cost, start_step)
|
||||
|
||||
@@ -239,7 +239,6 @@ def train(config: TrainerConfig):
|
||||
parallel_dims.get_mesh("dp").size(),
|
||||
config.model.seq_len,
|
||||
config.model.cp,
|
||||
tokenizer,
|
||||
build_bin_cost(model.config),
|
||||
config.rollout_transport,
|
||||
)
|
||||
|
||||
@@ -24,26 +24,6 @@ from prime_rl.trainer.lora import (
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
PYTORCH_WRAPPER_PREFIXES = ["_fsdp_wrapped_module.", "_orig_module.", "_checkpoint_wrapped_module."]
|
||||
|
||||
|
||||
def _strip_pytorch_wrapper_prefix(key: str) -> str:
|
||||
for prefix in PYTORCH_WRAPPER_PREFIXES:
|
||||
key = key.replace(prefix, "")
|
||||
return key
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
max_num = -1
|
||||
for key in state_dict:
|
||||
if not key.startswith(layer_prefix):
|
||||
continue
|
||||
layer_num_str = key[len(layer_prefix) :].split(".")[0]
|
||||
if layer_num_str.isdigit():
|
||||
max_num = max(max_num, int(layer_num_str))
|
||||
return max_num + 1
|
||||
|
||||
|
||||
def load_state_dict_keys(save_dir: Path) -> list[str]:
|
||||
"""Load only the key names from safetensor files without reading tensor data."""
|
||||
@@ -152,35 +132,3 @@ def gather_weights_on_master(
|
||||
cpu_state = clean_lora_state_dict(cpu_state)
|
||||
|
||||
return cpu_state
|
||||
|
||||
|
||||
def get_adapter_state_dict(model: nn.Module, is_master: bool) -> dict[str, Tensor]:
|
||||
"""Get adapter weights with clean keys for PEFT compatibility."""
|
||||
lora_state = {}
|
||||
|
||||
named_params = {_strip_pytorch_wrapper_prefix(key): value for key, value in model.named_parameters()}
|
||||
for key, value in model.state_dict().items():
|
||||
param = named_params.get(key)
|
||||
if param is None or not param.requires_grad:
|
||||
continue
|
||||
|
||||
if isinstance(value, DTensor):
|
||||
value = value.full_tensor()
|
||||
|
||||
if is_master:
|
||||
clean_key = next(iter(get_fqns(model, key)))
|
||||
clean_key = clean_key.replace(".base_layer.", ".")
|
||||
|
||||
# Add PEFT-expected prefix
|
||||
peft_key = f"base_model.model.{clean_key}"
|
||||
|
||||
# Add .weight suffix for LoRA parameters if missing
|
||||
if ("lora_A" in peft_key or "lora_B" in peft_key) and not peft_key.endswith(".weight"):
|
||||
peft_key = f"{peft_key}.weight"
|
||||
|
||||
lora_state[peft_key] = value.to("cpu", non_blocking=False)
|
||||
|
||||
torch.distributed.barrier()
|
||||
if is_master and len(lora_state) == 0:
|
||||
raise ValueError("The LoRA state dict is empty. Something went wrong.")
|
||||
return lora_state
|
||||
|
||||
@@ -10,14 +10,6 @@ class IncrementalTokenizationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def common_prefix_len(a: list[int], b: list[int]) -> int:
|
||||
max_len = min(len(a), len(b))
|
||||
for idx in range(max_len):
|
||||
if a[idx] != b[idx]:
|
||||
return idx
|
||||
return max_len
|
||||
|
||||
|
||||
def normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
|
||||
if messages is None:
|
||||
return []
|
||||
|
||||
@@ -407,8 +407,9 @@ async def update_weights(
|
||||
weight update, then resumes. This ensures all DP workers are idle and can
|
||||
participate in the collective weight transfer.
|
||||
|
||||
Note: The server-side /update_weights endpoint automatically resets the prefix cache
|
||||
to invalidate any cached KV states computed with the old weights.
|
||||
Note: the prefix cache is intentionally not reset on weight update. The orchestrator
|
||||
salts the prefix cache per weight version (``cache_salt`` in the sampling request, see
|
||||
``orchestrator/envs.py``), so KV computed under old weights is never reused.
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
@@ -470,8 +471,9 @@ LORA_LOAD_TOTAL_TIMEOUT_S = 120.0
|
||||
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
|
||||
"""Make a HTTP post request to the vLLM server to load a LoRA adapter.
|
||||
|
||||
Uses our wrapper endpoint that also resets the prefix cache to invalidate
|
||||
KV states computed with old weights.
|
||||
Uses our wrapper around vLLM's /v1/load_lora_adapter. The prefix cache is not reset
|
||||
here; the orchestrator salts it per weight version (see ``orchestrator/envs.py``) so
|
||||
KV computed under old weights is never reused.
|
||||
|
||||
Retries with exponential backoff if the adapter files are not found,
|
||||
which can happen due to NFS propagation delays.
|
||||
|
||||
@@ -155,34 +155,6 @@ def gather_for_cp_wo_grad(t: torch.Tensor, cp_world_size: int, cp_group: dist.Pr
|
||||
return torch.cat(empty_like_t, dim=1)
|
||||
|
||||
|
||||
def get_padding_logit_from_prev_cp_rank(
|
||||
logits: torch.Tensor, cp_rank: int, cp_world_size: int, cp_group: dist.ProcessGroup
|
||||
) -> torch.Tensor | None:
|
||||
"""
|
||||
Get the padding logit from the previous context parallel rank.
|
||||
Args:
|
||||
logits: The logits tensor.
|
||||
cp_rank: The rank of the current process.
|
||||
cp_world_size: The number of processes in the context parallel group.
|
||||
cp_group: The context parallel group.
|
||||
Returns:
|
||||
The padding logit from the previous context parallel rank.
|
||||
"""
|
||||
last_logit = logits[:, -1, :].unsqueeze(1)
|
||||
|
||||
all_rank_last_logits = [
|
||||
torch.zeros(1, 1, logits.shape[2], dtype=logits.dtype, device=logits.device) for _ in range(cp_world_size)
|
||||
]
|
||||
|
||||
dist.all_gather(all_rank_last_logits, last_logit, group=cp_group)
|
||||
|
||||
prev_cp_rank = cp_rank - 1
|
||||
if prev_cp_rank >= 0:
|
||||
return all_rank_last_logits[prev_cp_rank]
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def setup_cp_params(
|
||||
input_ids: torch.Tensor,
|
||||
position_ids: torch.Tensor,
|
||||
|
||||
@@ -43,7 +43,7 @@ class Heartbeat:
|
||||
|
||||
Non-blocking guarantee: This method never blocks the training loop. The HTTP
|
||||
request runs in a daemon thread, so even if the server is slow/unresponsive
|
||||
(up to the 2s timeout), training continues uninterrupted. The lock is held only
|
||||
(up to the 1s timeout), training continues uninterrupted. The lock is held only
|
||||
briefly (microseconds) to check/set flags atomically.
|
||||
"""
|
||||
with self._lock:
|
||||
|
||||
@@ -349,8 +349,8 @@ class PrimeMonitor(Monitor):
|
||||
"messages": [m.model_dump(mode="json") for m in branch.messages],
|
||||
"reward": rollout.reward,
|
||||
"advantage": rollout.scalar_advantage(),
|
||||
"num_input_tokens": branch.prompt_len,
|
||||
"num_output_tokens": branch.completion_len,
|
||||
"num_input_tokens": branch.num_input_tokens,
|
||||
"num_output_tokens": branch.num_output_tokens,
|
||||
}
|
||||
for branch in branches
|
||||
]
|
||||
@@ -373,8 +373,8 @@ class PrimeMonitor(Monitor):
|
||||
"advantage": rollout.scalar_advantage(),
|
||||
"metrics": json.dumps(rollout.metrics),
|
||||
"timing": rollout.timing.model_dump_json(),
|
||||
"num_input_tokens": branches[-1].prompt_len,
|
||||
"num_output_tokens": branches[-1].completion_len,
|
||||
"num_input_tokens": branches[-1].num_input_tokens,
|
||||
"num_output_tokens": branches[-1].num_output_tokens,
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import hashlib
|
||||
|
||||
import torch
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.optim.optimizer import Optimizer
|
||||
|
||||
TENSOR_SIG_SAMPLE_SIZE = 1000
|
||||
|
||||
|
||||
def get_tensor_signature(a: torch.Tensor | torch.nn.Parameter) -> str:
|
||||
while isinstance(a, torch.nn.Parameter):
|
||||
a = a.data
|
||||
|
||||
if isinstance(a, DTensor):
|
||||
a = a.to_local()
|
||||
|
||||
if a.device == torch.device("meta"):
|
||||
return f"{a.dtype}{a.shape}<meta>"
|
||||
|
||||
if a.numel() < TENSOR_SIG_SAMPLE_SIZE:
|
||||
b = a.as_strided(size=(a.numel(),), stride=(1,))
|
||||
else:
|
||||
step_size = a.numel() // TENSOR_SIG_SAMPLE_SIZE
|
||||
b = a.as_strided(size=(TENSOR_SIG_SAMPLE_SIZE,), stride=(step_size,))
|
||||
element_str = "".join([f"{x:.3e}" for x in b])
|
||||
element_hash = hashlib.md5(element_str.encode("utf-8")).hexdigest()
|
||||
return f"{a.dtype}{a.shape}{a.stride()}<{element_hash}>"
|
||||
|
||||
|
||||
def get_signature(state_dict, compress: bool = True) -> str:
|
||||
if compress:
|
||||
return hashlib.md5(str(state_dict).encode("utf-8")).hexdigest()
|
||||
else:
|
||||
return "\n".join(f"{name}: {sig}" for name, sig in state_dict.items())
|
||||
|
||||
|
||||
def get_optimizer_signature(optimizer: Optimizer, compress: bool = True) -> str:
|
||||
def unwrap_tensor(state_dict: dict) -> dict:
|
||||
new_dict = {}
|
||||
for key, value in state_dict.items():
|
||||
if isinstance(value, dict):
|
||||
new_dict[key] = unwrap_tensor(value)
|
||||
elif isinstance(value, torch.Tensor):
|
||||
new_dict[key] = get_tensor_signature(value)
|
||||
else:
|
||||
new_dict[key] = str(value)
|
||||
return new_dict
|
||||
|
||||
state_dict_sig = unwrap_tensor(optimizer.state_dict())
|
||||
return get_signature(state_dict_sig, compress)
|
||||
|
||||
|
||||
def get_module_signature(module: torch.nn.Module, compress: bool = True) -> str:
|
||||
param_sig = {name: get_tensor_signature(param) for name, param in module.named_parameters()}
|
||||
buffer_sig = {name: get_tensor_signature(buffer) for name, buffer in module.named_buffers()}
|
||||
state_dict_sig = {**param_sig, **buffer_sig}
|
||||
return get_signature(state_dict_sig, compress)
|
||||
@@ -39,11 +39,6 @@ def import_object(dotted_path: str) -> Any:
|
||||
return getattr(module, name)
|
||||
|
||||
|
||||
def capitalize(s: str) -> str:
|
||||
"""Capitalize the first letter of a string."""
|
||||
return s[0].upper() + s[1:]
|
||||
|
||||
|
||||
def clean_exit(func: Callable) -> Callable:
|
||||
"""
|
||||
A decorator that ensures the a torch.distributed process group is properly
|
||||
@@ -113,26 +108,6 @@ def to_col_format(list_of_dicts: list[dict[str, Any]]) -> dict[str, list[Any]]:
|
||||
return dict(dict_of_lists)
|
||||
|
||||
|
||||
def to_row_format(dict_of_lists: dict[str, list[Any]]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Turns a dict of lists to a list of dicts.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
dict_of_lists = {"a": [1, 3], "b": [2, 4]} # Column format
|
||||
to_row_format(dict_of_lists)
|
||||
```
|
||||
|
||||
Returns:
|
||||
|
||||
```python
|
||||
[{"a": 1, "b": 2}, {"a": 3, "b": 4}] # Row format
|
||||
```
|
||||
"""
|
||||
return [dict(zip(dict_of_lists.keys(), values)) for values in zip(*dict_of_lists.values())]
|
||||
|
||||
|
||||
def format_time(time_s: float) -> str:
|
||||
"""
|
||||
Format a time in seconds to a human-readable format:
|
||||
@@ -188,15 +163,6 @@ def get_free_port() -> int:
|
||||
return port
|
||||
|
||||
|
||||
def get_cuda_visible_devices() -> list[int]:
|
||||
"""Returns the list of availble CUDA devices, taking into account the CUDA_VISIBLE_DEVICES environment variable."""
|
||||
cuda_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
|
||||
if cuda_visible is None:
|
||||
# Default to all devices if the environment variable is not set
|
||||
return list(range(torch.cuda.device_count()))
|
||||
return list(sorted([int(device) for device in cuda_visible.split(",")]))
|
||||
|
||||
|
||||
def get_latest_ckpt_step(weights_dir: Path) -> int | None:
|
||||
step_dirs = list(weights_dir.glob("step_*"))
|
||||
if len(step_dirs) == 0:
|
||||
@@ -208,17 +174,6 @@ def get_latest_ckpt_step(weights_dir: Path) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def mean(values: list[float] | list[int]) -> float:
|
||||
"""Compute the mean of a list of values."""
|
||||
return sum(values) / len(values) if values else 0.0
|
||||
|
||||
|
||||
def mean_normalize(values: list[float] | list[int]) -> list[float]:
|
||||
"""Mean-Normalize a list of values to 0-1."""
|
||||
sum_values = sum(values)
|
||||
return [value / sum_values if sum_values > 0 else 0.0 for value in values]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def default_dtype(dtype):
|
||||
prev = torch.get_default_dtype()
|
||||
|
||||
@@ -1,28 +1,18 @@
|
||||
import asyncio
|
||||
import math
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import (
|
||||
GRPOAlgoConfig,
|
||||
LinearLengthPenaltyConfig,
|
||||
MaxRLAlgoConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.algo.advantage import efficiency_shaping
|
||||
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
from prime_rl.orchestrator.algo.max_rl import MaxRLAlgorithm
|
||||
from prime_rl.orchestrator.trajectories import trace_to_samples
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
# Token-cost penalty over completion tokens only (the harness tool-response
|
||||
# metric is absent on these rollouts, so the tool weight contributes nothing).
|
||||
_TOKENS_COMPLETION = TokensLengthPenaltyConfig(completion_weight=1.0, tool_response_weight=0.0)
|
||||
# Token-cost penalty over tool-response tokens only.
|
||||
_TOKENS_TOOL_ONLY = TokensLengthPenaltyConfig(completion_weight=0.0, tool_response_weight=1.0)
|
||||
|
||||
|
||||
def _build_rollout(
|
||||
reward: float,
|
||||
@@ -131,13 +121,6 @@ def _make_group(rewards, completion_lengths=None, num_turns=None) -> list[Rollou
|
||||
return rollouts
|
||||
|
||||
|
||||
def _shape(rewards: list[float], costs: list[float]) -> list[float]:
|
||||
"""Run ``efficiency_shaping`` directly on reward/cost vectors."""
|
||||
return efficiency_shaping(
|
||||
torch.tensor(rewards, dtype=torch.float32), torch.tensor(costs, dtype=torch.float32)
|
||||
).tolist()
|
||||
|
||||
|
||||
def _scalar(rollout: Rollout) -> float:
|
||||
"""The per-rollout advantage scalar an algorithm assigned — broadcast over
|
||||
the rollout's trainable (mask-True) tokens, so any trainable position holds it."""
|
||||
@@ -185,123 +168,53 @@ def test_max_rl_mean_normalized():
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# efficiency_shaping: the bounded correctness-gated reward transform (pure).
|
||||
# GRPO linear length penalty: pass_rate-scaled penalty before the baseline.
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_efficiency_mixed_group():
|
||||
"""Mixed group: shaping preserves zero-mean, shorter correct gets higher advantage."""
|
||||
# mean_correct_cost = (10+30+20)/3 = 20
|
||||
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
|
||||
# shaped = R * (1 + bonus * correct) = [1.5, 1, 0, 1]; baseline = 0.875
|
||||
advs = _shape([1.0, 1.0, 0.0, 1.0], [10, 30, 20, 20])
|
||||
assert advs == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
|
||||
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_all_correct_group():
|
||||
"""All-correct group: zero-mean, shorter gets higher advantage."""
|
||||
# mean_cost = 70/3; bonus = clamp(1 - [10,20,40]/(70/3), 0, 1) = [4/7, 1/7, 0]
|
||||
advs = _shape([1.0, 1.0, 1.0], [10, 20, 40])
|
||||
shaped = [11.0 / 7, 8.0 / 7, 1.0]
|
||||
mean_shaped = sum(shaped) / len(shaped)
|
||||
assert advs == pytest.approx([s - mean_shaped for s in shaped], abs=1e-6)
|
||||
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
|
||||
assert advs[0] > advs[1] > advs[2]
|
||||
|
||||
|
||||
def test_efficiency_all_zero_rewards():
|
||||
"""When all rewards are 0 there is no correct rollout — no shaping (plain GRPO)."""
|
||||
assert _shape([0.0, 0.0, 0.0], [10, 20, 15]) == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_single_correct():
|
||||
"""A single correct rollout sits at its own mean cost (bonus 0) — plain GRPO."""
|
||||
assert _shape([1.0, 0.0, 0.0, 0.0], [100, 50, 200, 150]) == pytest.approx([0.75, -0.25, -0.25, -0.25], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_shorter_correct_higher_advantage():
|
||||
"""Among correct rollouts, shorter always gets higher advantage."""
|
||||
advs = _shape([1.0, 1.0, 1.0, 0.0, 0.0], [50, 100, 200, 80, 120])
|
||||
assert advs[0] > advs[1] > advs[2]
|
||||
assert all(a > 0 for a in advs[:3])
|
||||
assert all(a < 0 for a in advs[3:])
|
||||
|
||||
|
||||
def test_efficiency_zero_mean_preserved():
|
||||
assert sum(_shape([1.0, 1.0, 0.0, 1.0], [10, 30, 20, 20])) == pytest.approx(0.0, abs=1e-6)
|
||||
assert sum(_shape([1.0, 1.0, 1.0], [10, 20, 40])) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_amplification_bounded():
|
||||
"""Even with extreme length outliers, amplification is capped at 2x (advantage < 1)."""
|
||||
assert _shape([1.0, 1.0, 0.0], [1, 10000, 5000])[0] < 1.0 + 1e-3
|
||||
|
||||
|
||||
def test_efficiency_zero_costs_falls_back_to_plain_grpo():
|
||||
"""All-zero costs would divide by zero — fall back to plain GRPO, no NaNs."""
|
||||
advs = _shape([1.0, 1.0, 0.0], [0.0, 0.0, 0.0])
|
||||
assert not any(math.isnan(a) for a in advs)
|
||||
assert advs == pytest.approx([1.0 / 3, 1.0 / 3, -2.0 / 3], abs=1e-6)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# GRPO length-penalty cost dispatch (rollout fields -> per-rollout cost).
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_grpo_tokens_with_tool_response_weight():
|
||||
"""`tool_response_weight` shifts shaping onto tool-response tokens read from rollout metrics."""
|
||||
|
||||
def group():
|
||||
return [
|
||||
_build_rollout(1.0, sampled_lengths=[10], metrics={"rlm_total_tool_response_tokens": 200}),
|
||||
_build_rollout(1.0, sampled_lengths=[10], metrics={"rlm_total_tool_response_tokens": 0}),
|
||||
_build_rollout(1.0, sampled_lengths=[10], metrics={"rlm_total_tool_response_tokens": 100}),
|
||||
]
|
||||
|
||||
# completion tokens identical (10 each) → completion-only shaping is a no-op
|
||||
assert _grpo(group(), length_penalty=_TOKENS_COMPLETION) == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
|
||||
# tool-response only: costs are [200, 0, 100], so only the below-mean rollout (idx 1) amplifies
|
||||
advs = _grpo(group(), length_penalty=_TOKENS_TOOL_ONLY)
|
||||
assert advs[1] > advs[0]
|
||||
assert advs[1] > advs[2]
|
||||
assert advs[0] == pytest.approx(advs[2], abs=1e-6)
|
||||
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_grpo_fractional_weight_with_int_rewards():
|
||||
"""Fractional weights must not truncate when rollout rewards are emitted as ints."""
|
||||
lengths = [7, 11, 13]
|
||||
rewards_int = [1, 1, 0]
|
||||
fractional = TokensLengthPenaltyConfig(completion_weight=0.3, tool_response_weight=0.0)
|
||||
int_group = [_build_rollout(r, sampled_lengths=[length]) for r, length in zip(rewards_int, lengths)]
|
||||
float_group = [_build_rollout(float(r), sampled_lengths=[length]) for r, length in zip(rewards_int, lengths)]
|
||||
assert _grpo(int_group, length_penalty=fractional) == pytest.approx(
|
||||
_grpo(float_group, length_penalty=fractional), abs=1e-6
|
||||
def test_linear_equal_lengths_reduce_to_plain_grpo():
|
||||
"""Equal completion length and turns → every rollout takes the same penalty
|
||||
fraction, so subtracting it leaves the centered advantages unchanged."""
|
||||
penalized = _grpo(
|
||||
_make_group(rewards=[1.0, 0.0, 1.0], completion_lengths=[10, 10, 10], num_turns=[2, 2, 2]),
|
||||
length_penalty=LinearLengthPenaltyConfig(),
|
||||
)
|
||||
plain = _grpo(_make_group(rewards=[1.0, 0.0, 1.0], completion_lengths=[10, 10, 10], num_turns=[2, 2, 2]))
|
||||
assert penalized == pytest.approx(plain, abs=1e-6)
|
||||
|
||||
|
||||
def test_grpo_tokens_default_weights_match_completion_when_no_metric():
|
||||
"""Default TokensLengthPenaltyConfig (1,1) reduces to completion-only when rollouts lack the metric."""
|
||||
|
||||
def group():
|
||||
return _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
|
||||
|
||||
assert _grpo(group(), length_penalty=TokensLengthPenaltyConfig()) == pytest.approx(
|
||||
_grpo(group(), length_penalty=_TOKENS_COMPLETION), abs=1e-6
|
||||
)
|
||||
def test_linear_completion_term_penalizes_longer():
|
||||
"""With only the completion term, longer completions get a larger penalty and a
|
||||
lower advantage; advantages stay zero-mean."""
|
||||
cfg = LinearLengthPenaltyConfig(num_output_tokens_weight=0.25, num_input_tokens_weight=0.0, num_turns_weight=0.0)
|
||||
advs = _grpo(_make_group(rewards=[1.0, 1.0, 1.0], completion_lengths=[10, 20, 30]), length_penalty=cfg)
|
||||
assert advs[0] > advs[1] > advs[2]
|
||||
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_grpo_turns_penalty():
|
||||
"""`TurnsLengthPenaltyConfig` shapes by trajectory turn count rather than token count."""
|
||||
# token counts identical, turns differ: mean_correct_turns = (1+3+2)/3 = 2
|
||||
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
|
||||
def test_linear_context_term_penalizes_more_context():
|
||||
"""The context term penalizes non-completion (prompt / tool-response) tokens: at
|
||||
equal completion length, more context tokens yields a lower advantage."""
|
||||
cfg = LinearLengthPenaltyConfig(num_output_tokens_weight=0.0, num_input_tokens_weight=0.25, num_turns_weight=0.0)
|
||||
group = [
|
||||
_build_rollout(1.0, sampled_lengths=[10], obs_lengths=[]),
|
||||
_build_rollout(1.0, sampled_lengths=[10], obs_lengths=[100]),
|
||||
]
|
||||
asyncio.run(GRPOAlgorithm(GRPOAlgoConfig(length_penalty=cfg), policy_pool=None).score_group(group))
|
||||
advs = [_scalar(rollout) for rollout in group]
|
||||
assert advs[0] > advs[1]
|
||||
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_linear_turns_term_penalizes_more_turns():
|
||||
"""The turns term penalizes higher turn counts at equal token lengths."""
|
||||
cfg = LinearLengthPenaltyConfig(num_output_tokens_weight=0.0, num_input_tokens_weight=0.0, num_turns_weight=0.25)
|
||||
advs = _grpo(
|
||||
_make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[100, 100, 100, 100], num_turns=[1, 3, 2, 2]),
|
||||
length_penalty=TurnsLengthPenaltyConfig(),
|
||||
_make_group(rewards=[1.0, 1.0], completion_lengths=[100, 100], num_turns=[1, 4]),
|
||||
length_penalty=cfg,
|
||||
)
|
||||
assert advs == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
|
||||
assert advs[0] > advs[1]
|
||||
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from prime_rl.orchestrator.metrics import EvalRollouts, Stat, TrainRollouts
|
||||
from prime_rl.orchestrator.utils import compute_pass_metrics
|
||||
|
||||
|
||||
def mk(
|
||||
reward: float = 0.0,
|
||||
*,
|
||||
num_total_tokens: int = 10,
|
||||
num_input_tokens: int = 4,
|
||||
num_output_tokens: int = 6,
|
||||
num_turns: int = 1,
|
||||
num_branches: int = 1,
|
||||
is_truncated: bool = False,
|
||||
is_completed: bool = True,
|
||||
has_error: bool = False,
|
||||
error_type: str = "error",
|
||||
stop_condition: str | None = None,
|
||||
metrics: dict | None = None,
|
||||
rewards: dict | None = None,
|
||||
env_name: str = "env",
|
||||
group_id: str = "g0",
|
||||
is_trainable: bool = True,
|
||||
is_filtered: bool = False,
|
||||
filter_results: dict | None = None,
|
||||
setup: float = 0.0,
|
||||
generation: float = 0.0,
|
||||
finalize: float = 0.0,
|
||||
scoring: float = 0.0,
|
||||
):
|
||||
"""Duck-typed stand-in for ``Rollout``, exposing only the Trace properties the metrics read."""
|
||||
return SimpleNamespace(
|
||||
reward=reward,
|
||||
rewards=rewards or {},
|
||||
num_total_tokens=num_total_tokens,
|
||||
num_input_tokens=num_input_tokens,
|
||||
num_output_tokens=num_output_tokens,
|
||||
num_turns=num_turns,
|
||||
num_branches=num_branches,
|
||||
is_truncated=is_truncated,
|
||||
is_completed=is_completed,
|
||||
has_error=has_error,
|
||||
error=SimpleNamespace(type=error_type) if has_error else None,
|
||||
stop_condition=stop_condition,
|
||||
metrics=metrics or {},
|
||||
env_name=env_name,
|
||||
group_id=group_id,
|
||||
is_trainable=is_trainable,
|
||||
is_filtered=is_filtered,
|
||||
filter_results=filter_results or {},
|
||||
timing=SimpleNamespace(
|
||||
setup=SimpleNamespace(duration=setup),
|
||||
generation=SimpleNamespace(duration=generation),
|
||||
finalize=SimpleNamespace(duration=finalize),
|
||||
scoring=SimpleNamespace(duration=scoring),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def train_wandb(rollouts, subset: str = "all") -> dict:
|
||||
return TrainRollouts(rollouts).metrics.to_wandb(prefix="train/agg", subset=subset)
|
||||
|
||||
|
||||
def test_stat():
|
||||
s = Stat([1.0, 2.0, 3.0])
|
||||
assert (s.mean(), s.max(), s.min()) == (2.0, 3.0, 1.0)
|
||||
assert (s.p10(), s.p90()) == pytest.approx((1.2, 2.8)) # linear-interpolated percentiles
|
||||
assert s.to_dict("p") == pytest.approx({"p/mean": 2.0, "p/max": 3.0, "p/min": 1.0, "p/p10": 1.2, "p/p90": 2.8})
|
||||
assert Stat([]).p90() == 0.0 and Stat([]).to_dict("p") == {}
|
||||
|
||||
|
||||
def test_container_effective_by_env_and_listlike():
|
||||
rc = TrainRollouts(
|
||||
[mk(env_name="a"), mk(env_name="a", has_error=True), mk(env_name="b", is_filtered=True), mk(env_name="b")]
|
||||
)
|
||||
assert len(rc) == 4 and [r.env_name for r in rc] == ["a", "a", "b", "b"] # sized + iterable
|
||||
eff = rc.effective
|
||||
assert isinstance(eff, TrainRollouts) and len(eff) == 2 # same type, errored + filtered dropped
|
||||
assert all(not r.has_error and not r.is_filtered and r in rc.rollouts for r in eff) # view of references
|
||||
by_env = rc.by_env()
|
||||
assert set(by_env) == {"a", "b"} and len(by_env["a"]) == 2 and isinstance(by_env["a"], TrainRollouts)
|
||||
rc.append(mk())
|
||||
assert len(rc) == 5
|
||||
|
||||
|
||||
def test_to_wandb_distributions():
|
||||
m = TrainRollouts(
|
||||
[
|
||||
mk(reward=1.0, num_total_tokens=10, num_input_tokens=4),
|
||||
mk(reward=0.0, num_total_tokens=20, num_input_tokens=6),
|
||||
]
|
||||
).metrics
|
||||
assert m.num_input_tokens.mean() == 5.0 # fluent Stat access
|
||||
out = m.to_wandb(prefix="train/agg", subset="all")
|
||||
assert out["train/agg/all/reward/mean"] == 0.5
|
||||
assert out["train/agg/all/num_total_tokens/mean"] == 15.0
|
||||
assert out["train/agg/all/num_total_tokens/max"] == 20.0 # flat over rollouts, not per-group
|
||||
assert out["train/agg/all/num_input_tokens/mean"] == 5.0
|
||||
assert out["train/agg/all/num_output_tokens/mean"] == 6.0
|
||||
|
||||
|
||||
def test_boolean_rates_and_error_breakdown_all_only():
|
||||
rc = TrainRollouts([mk(is_truncated=True), mk(has_error=True, error_type="ProviderError"), mk(is_filtered=True)])
|
||||
out = rc.metrics.to_wandb(prefix="train/agg", subset="all")
|
||||
assert out["train/agg/all/is_truncated/mean"] == 1 / 3
|
||||
assert out["train/agg/all/is_completed/mean"] == 1.0
|
||||
assert out["train/agg/all/has_error/mean"] == 1 / 3
|
||||
assert out["train/agg/all/error/ProviderError"] == 1 # error-type breakdown by count
|
||||
assert not any("no_response" in k for k in out) # removed metric
|
||||
# has_error + the error-type counts are structurally empty on effective, so emitted on `all` only
|
||||
eff = rc.effective.metrics.to_wandb(prefix="train/agg", subset="effective")
|
||||
assert not any(k.endswith("/has_error/mean") or "/error/" in k for k in eff)
|
||||
|
||||
|
||||
def test_solve_rates():
|
||||
groups = {"A": [1.0, 1.0], "B": [0.0, 0.0], "C": [1.0, 0.0], "D": [1.0, 0.0]} # all / none / some / some
|
||||
out = train_wandb([mk(reward=r, group_id=g) for g, rs in groups.items() for r in rs])
|
||||
rates = (out["train/agg/all/solved_all"], out["train/agg/all/solved_none"], out["train/agg/all/solved_some"])
|
||||
assert rates == (0.25, 0.25, 0.5)
|
||||
|
||||
|
||||
def test_stop_condition_breakdown():
|
||||
truncated = [mk(is_truncated=True, stop_condition=c) for c in ("length", "max_turns", "prompt_too_long")]
|
||||
out = train_wandb(truncated + [mk(stop_condition=None)])
|
||||
assert out["train/agg/all/stop_condition/generation_truncated"] == 0.5 # truncated & not prompt_too_long, over all
|
||||
assert out["train/agg/all/stop_condition/length"] == 1 / 3 # over the 3 recorded conditions
|
||||
assert out["train/agg/all/stop_condition/prompt_too_long"] == 1 / 3
|
||||
|
||||
|
||||
def test_nested_metrics_and_rewards():
|
||||
rollouts = [
|
||||
mk(metrics={"acc": 1.0}, rewards={"correct": 1.0, "format": 0.0}),
|
||||
mk(metrics={"acc": 3.0, "fmt": 5.0}, rewards={"correct": 0.0, "format": 1.0}),
|
||||
]
|
||||
m = TrainRollouts(rollouts).metrics
|
||||
assert m.metrics["acc"].mean() == 2.0 and m.rewards["correct"].mean() == 0.5 # nested group access
|
||||
out = m.to_wandb(prefix="train/agg", subset="all")
|
||||
assert out["train/agg/all/metrics/acc/mean"] == 2.0 # averaged over reporters
|
||||
assert out["train/agg/all/metrics/fmt/mean"] == 5.0 # single reporter
|
||||
assert out["train/agg/all/rewards/format/mean"] == 0.5
|
||||
|
||||
|
||||
def test_nested_timing():
|
||||
m = TrainRollouts([mk(setup=1.0, generation=2.0, finalize=0.5, scoring=0.5)]).metrics
|
||||
assert m.timing.setup.mean() == 1.0 and m.timing.total.mean() == 4.0 # total sums all four phases
|
||||
out = m.to_wandb(prefix="train/agg", subset="all")
|
||||
assert out["train/agg/all/timing/setup/mean"] == 1.0
|
||||
assert out["train/agg/all/timing/total/mean"] == 4.0
|
||||
|
||||
|
||||
def test_train_only_metrics_absent_from_eval():
|
||||
rollouts = [
|
||||
mk(is_trainable=True, is_filtered=True, filter_results={"gibberish": True}),
|
||||
mk(is_trainable=False, filter_results={"gibberish": False}),
|
||||
]
|
||||
out = train_wandb(rollouts)
|
||||
assert out["train/agg/all/is_trainable/mean"] == 0.5
|
||||
assert out["train/agg/all/is_filtered/mean"] == 0.5
|
||||
assert out["train/agg/all/filters/gibberish/mean"] == 0.5
|
||||
eval_out = EvalRollouts(rollouts).metrics.to_wandb(prefix="eval/x", subset="all")
|
||||
assert not any("is_trainable" in k or "is_filtered" in k or "/filters/" in k for k in eval_out)
|
||||
|
||||
|
||||
def test_eval_avg_at_k_and_pass_k():
|
||||
binary = EvalRollouts([mk(reward=1.0, group_id="g0"), mk(reward=0.0, group_id="g0")])
|
||||
eff = binary.effective.metrics.to_wandb(prefix="eval/x", subset="effective")
|
||||
assert eff["eval/x/effective/avg@2"] == 0.5 # mean reward under avg@<k> (k derived from the groups)
|
||||
assert not any(k.startswith("eval/x/effective/reward") for k in eff)
|
||||
assert eff["eval/x/effective/pass@1"] == 0.5 and eff["eval/x/effective/pass^2"] == 0.0
|
||||
all_out = binary.metrics.to_wandb(prefix="eval/x", subset="all")
|
||||
assert all_out["eval/x/all/avg@2"] == 0.5
|
||||
assert not any("pass@" in k or "pass^" in k for k in all_out) # pass@k effective-only
|
||||
non_binary = EvalRollouts([mk(reward=0.5, group_id="g0"), mk(reward=1.0, group_id="g0")])
|
||||
assert not any("pass@" in k for k in non_binary.effective.metrics.to_wandb(prefix="eval/x", subset="effective"))
|
||||
|
||||
|
||||
def test_compute_pass_metrics_matches_closed_form():
|
||||
out = compute_pass_metrics([1.0, 1.0, 0.0, 0.0]) # n=4, c=2
|
||||
assert out["pass@1"] == 1.0 - math.comb(2, 1) / math.comb(4, 1)
|
||||
assert out["pass@2"] == 1.0 - math.comb(2, 2) / math.comb(4, 2)
|
||||
assert out["pass^2"] == math.comb(2, 2) / math.comb(4, 2)
|
||||
assert set(out) == {"pass@1", "pass@2", "pass@4", "pass^1", "pass^2", "pass^4"}
|
||||
@@ -92,7 +92,6 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
||||
dp_world_size=1,
|
||||
seq_len=4,
|
||||
pad_to_multiple_of=1,
|
||||
tokenizer=None,
|
||||
config=FileSystemTransportConfig(),
|
||||
bin_cost=build_bin_cost(None),
|
||||
start_step=0,
|
||||
|
||||
Reference in New Issue
Block a user