Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31e81e5b18 | ||
|
|
137f8f49c8 | ||
|
|
f04c8d988c | ||
|
|
4d361adacc | ||
|
|
7f77713886 | ||
|
|
efeddae6bb | ||
|
|
8dfe8734e3 | ||
|
|
fa21395a68 | ||
|
|
b5daec1cbb | ||
|
|
b452660025 | ||
|
|
060f25bb3a | ||
|
|
77af037537 | ||
|
|
9281c5589a | ||
|
|
9dbb523933 | ||
|
|
5789850d4d | ||
|
|
146fcd0136 | ||
|
|
b0612a0e1f | ||
|
|
c0a026c0d4 | ||
|
|
7c9c1308dc | ||
|
|
941019f2e3 | ||
|
|
9e1f0521e3 |
+3
-2
@@ -23,7 +23,8 @@ configs/endpoints.py
|
||||
final_summary.json
|
||||
.pydantic_config
|
||||
.chroma_db
|
||||
|
||||
deps/nixl_*
|
||||
nixl_workspace/*
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
@@ -202,4 +203,4 @@ debug_I2_zero_band
|
||||
|
||||
outputs/
|
||||
|
||||
third_party/
|
||||
third_party/
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
|
||||
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
|
||||
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
|
||||
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
|
||||
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
|
||||
|
||||
@@ -97,6 +97,7 @@ RUN apt-get update && apt-get install -y \
|
||||
tmux \
|
||||
iperf \
|
||||
openssh-server \
|
||||
git \
|
||||
git-lfs \
|
||||
gpg \
|
||||
sudo \
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Trainer config for multi-run RL integration test
|
||||
max_concurrent_runs = 2
|
||||
enable_token_export = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
Vendored
+1
-1
Submodule deps/research-environments updated: 4c08260f07...841f9a54df
Vendored
+1
-1
Submodule deps/verifiers updated: 0ad8b4d523...78c1b3c545
+13
-3
@@ -136,10 +136,20 @@ 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. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
|
||||
|
||||
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
|
||||
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
|
||||
|
||||
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
|
||||
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
|
||||
```toml
|
||||
[orchestrator.advantage.length_penalty]
|
||||
coef = 0.25 # effective penalty is coef * pass_rate * (completion_tokens / seq_len)
|
||||
gate_by_correctness = false # when true, only penalize rollouts with reward == 1
|
||||
```
|
||||
|
||||
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
|
||||
|
||||
```toml
|
||||
[orchestrator.advantage]
|
||||
length_weighted_baseline = true
|
||||
```
|
||||
|
||||
|
||||
### Custom Advantage
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `token_export` flag) that aren't surfaced here.
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
|
||||
@@ -143,31 +143,22 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return data
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
class LinearLengthPenaltyConfig(BaseConfig):
|
||||
coef: float = Field(0.25, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the linear length penalty. Each reward is reduced by ``coef * pass_rate * (model completion tokens / orchestrator.seq_len)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative."""
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
|
||||
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."""
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
gate_by_correctness: bool = False
|
||||
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
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."""
|
||||
length_penalty: LinearLengthPenaltyConfig | None = None
|
||||
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
|
||||
|
||||
length_weighted_baseline: bool = False
|
||||
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseConfig):
|
||||
|
||||
@@ -167,6 +167,9 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
|
||||
orchestrator_on_inference: bool = False
|
||||
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
|
||||
|
||||
@property
|
||||
def total_infer_nodes(self) -> int:
|
||||
return self.num_infer_nodes * self.num_infer_replicas
|
||||
@@ -603,16 +606,20 @@ class RLConfig(BaseConfig):
|
||||
def auto_setup_inference_client(self):
|
||||
"""Auto-configure orchestrator student client from the inference server config.
|
||||
|
||||
For all modes, sets dp_rank_count from inference DP size. For SFT mode,
|
||||
also sets base_url - rl/opd rely on the ClientConfig default
|
||||
(``["http://localhost:8000/v1"]``) which already matches the auto-launched
|
||||
student vLLM at inference.server.port = 8000.
|
||||
Direct single-node runs expose all local DP ranks behind one base URL,
|
||||
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
|
||||
runs expose a vllm-router URL instead; the router balances across
|
||||
per-rank backend URLs and forwards request headers, so the orchestrator
|
||||
must not inject a DP-rank header there.
|
||||
"""
|
||||
if self.inference is None:
|
||||
return self
|
||||
client = self.orchestrator.student.client
|
||||
if "dp_rank_count" not in client.model_fields_set:
|
||||
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
if self.deployment.type == "multi_node":
|
||||
client.dp_rank_count = 1
|
||||
else:
|
||||
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
|
||||
host = self.inference.server.host or "localhost"
|
||||
port = self.inference.server.port
|
||||
|
||||
@@ -425,6 +425,18 @@ class DefaultLossConfig(BaseConfig):
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IPOLossConfig(BaseConfig):
|
||||
type: Literal["ipo"] = "ipo"
|
||||
ipo_threshold: float = Field(0.1, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(1e-3, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class CustomLossConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
@@ -435,7 +447,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -490,15 +502,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class TokenExportConfig(BaseConfig):
|
||||
"""Configures per-token rollout exports from the RL trainer."""
|
||||
|
||||
|
||||
class TrainerExperimentalConfig(BaseConfig):
|
||||
token_export: TokenExportConfig | None = None
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
@@ -562,7 +565,8 @@ class TrainerConfig(BaseConfig):
|
||||
max_concurrent_runs: int = Field(1, ge=1)
|
||||
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
|
||||
|
||||
experimental: TrainerExperimentalConfig = TrainerExperimentalConfig()
|
||||
enable_token_export: bool = False
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
|
||||
@@ -22,6 +22,8 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
(re.compile(r"^zai-org/GLM-"), "glm45"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
# Only Qwen3 Thinking models reason — Instruct/base models do not.
|
||||
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
|
||||
|
||||
@@ -87,6 +87,8 @@ envs = [
|
||||
"opencode-swe",
|
||||
"reverse-text",
|
||||
"rlm-swe",
|
||||
"rlm-search",
|
||||
"rlm-uuid-ctf",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
@@ -226,6 +228,8 @@ opencode-science = { path = "deps/research-environments/environments/opencode_sc
|
||||
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
rlm-uuid-ctf = { path = "deps/research-environments/environments/rlm_uuid_ctf", editable = true }
|
||||
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
|
||||
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
|
||||
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
|
||||
|
||||
@@ -4,8 +4,74 @@ set -e
|
||||
# Set higher ulimit for file descriptors to prevent API timeout issues
|
||||
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
|
||||
|
||||
# Allow runtime override of the prime-rl source itself.
|
||||
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
|
||||
# optionally points at a fork; defaults to the upstream repo.
|
||||
#
|
||||
# We clone into a per-ref dir under /tmp, seed the venv from the baked
|
||||
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
|
||||
# `uv sync --inexact` re-installs prime_rl from the override source.
|
||||
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
|
||||
# resolves the entrypoints from the override venv.
|
||||
if [ -n "$PRIME_RL_REF" ]; then
|
||||
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
|
||||
# Slug + content hash for the cache dir name. Slug keeps the path
|
||||
# human-readable; the hash (over repo + ref) prevents collisions
|
||||
# between distinct refs that slugify the same way (e.g. `feat/foo`
|
||||
# vs `feat-foo`) and between the same ref on different forks.
|
||||
REF_SLUG="${PRIME_RL_REF//\//-}"
|
||||
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
|
||||
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
|
||||
# Rewrite ssh://git@github.com URLs to https so submodules listed
|
||||
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
|
||||
# can be cloned from the pod without ssh keys.
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
if [ ! -d "$DEST/.git" ]; then
|
||||
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
|
||||
rm -rf "$DEST"
|
||||
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
|
||||
fi
|
||||
# Always fetch + checkout so mutable refs (branches/tags) pick up new
|
||||
# commits between pod restarts. No-op for immutable SHAs.
|
||||
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
|
||||
git -C "$DEST" fetch --quiet --tags --force origin
|
||||
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
|
||||
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
|
||||
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
|
||||
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
|
||||
# Refresh submodules to whatever the parent commit pins. `sync`
|
||||
# picks up URL changes in .gitmodules between checkouts on cache
|
||||
# hit; `update --init --recursive` applies the pinned SHAs.
|
||||
git -C "$DEST" submodule sync --recursive
|
||||
git -C "$DEST" submodule update --init --recursive
|
||||
if [ ! -d "$DEST/.venv" ]; then
|
||||
# Seed from the baked venv so the heavy wheels (flash-attn,
|
||||
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
|
||||
# hardlinks): a subsequent `uv sync` writes into this tree, and
|
||||
# hardlinks would leak those writes back into /app/.venv when
|
||||
# /tmp and /app share a filesystem.
|
||||
cp -a /app/.venv "$DEST/.venv"
|
||||
fi
|
||||
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
|
||||
# Mirror the image's extras (Dockerfile.cuda:82) — explicit instead
|
||||
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
|
||||
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
|
||||
# startup. --inexact keeps the seeded venv's pre-built wheels
|
||||
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
|
||||
# override's lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev \
|
||||
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
|
||||
--extra envs --extra gpt-oss --extra modelexpress \
|
||||
--group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
cd "$DEST"
|
||||
fi
|
||||
|
||||
# Allow runtime override of the verifiers package version.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
|
||||
# PRIME_RL_REF swap so when both are set the install lands in the override
|
||||
# venv (uv pip install targets $VIRTUAL_ENV when exported).
|
||||
if [ -n "$VERIFIERS_VERSION" ]; then
|
||||
echo "Installing verifiers version: $VERIFIERS_VERSION"
|
||||
uv pip install --reinstall-package verifiers \
|
||||
|
||||
@@ -10,6 +10,19 @@ PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
VENV_BIN="$PROJECT_DIR/.venv/bin"
|
||||
PYTHON="$VENV_BIN/python"
|
||||
|
||||
# UCX's --with-verbs silently disables IB/RoCE support when the rdma-core *dev*
|
||||
# headers (verbs.h / rdma_cma.h) are missing, yielding a TCP-only build. On hosts
|
||||
# with RDMA devices, require the headers up front instead of failing at runtime.
|
||||
HAVE_RDMA=0
|
||||
if compgen -G "/sys/class/infiniband/*" > /dev/null; then
|
||||
HAVE_RDMA=1
|
||||
if [ ! -f /usr/include/infiniband/verbs.h ] || [ ! -f /usr/include/rdma/rdma_cma.h ]; then
|
||||
echo "ERROR: host has RDMA devices but the rdma-core dev headers are missing." >&2
|
||||
echo "Install them first, e.g.: apt-get install -y libibverbs-dev librdmacm-dev" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
WORKSPACE="$PROJECT_DIR/nixl_workspace"
|
||||
mkdir -p "$WORKSPACE"
|
||||
UCX_SRC="$WORKSPACE/ucx_source"
|
||||
@@ -40,11 +53,23 @@ if [ ! -f "$UCX_INSTALL/lib/libucs.so" ]; then
|
||||
--enable-devel-headers \
|
||||
--enable-mt \
|
||||
--with-verbs \
|
||||
--with-rdmacm \
|
||||
--with-cuda="$CUDA_PATH" \
|
||||
--with-ze=no
|
||||
make -j"$NPROC"
|
||||
make install
|
||||
echo "=== UCX installed to $UCX_INSTALL ==="
|
||||
|
||||
# Fail loudly if the IB transports didn't make it into the build.
|
||||
if [ "$HAVE_RDMA" = 1 ]; then
|
||||
ucx_transports=$(LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}" \
|
||||
"$UCX_INSTALL/bin/ucx_info" -d)
|
||||
if ! grep -q "Transport: rc_verbs" <<< "$ucx_transports"; then
|
||||
echo "ERROR: UCX built without IB (rc_verbs) transport despite RDMA devices being present." >&2
|
||||
echo "Check that libibverbs-dev / librdmacm-dev were present at configure time." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "=== UCX already built, skipping ==="
|
||||
fi
|
||||
|
||||
@@ -62,10 +62,10 @@ In TOML, an empty section header (`[ckpt]`) does the same.
|
||||
|
||||
## RL trainer token exports
|
||||
|
||||
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
|
||||
```toml
|
||||
[trainer.experimental.token_export]
|
||||
enable_token_export = true
|
||||
```
|
||||
|
||||
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
|
||||
|
||||
@@ -27,7 +27,7 @@ uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
|
||||
```
|
||||
|
||||
The `envs` extra installs every env workspace listed in `[tool.uv.workspace]`. Adding a new env means adding it to `members`, the `envs` extra, and `[tool.uv.sources]`.
|
||||
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
|
||||
|
||||
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
|
||||
@@ -383,6 +383,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
@@ -405,6 +406,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -17,11 +17,29 @@ def transformers_v5_compat():
|
||||
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
|
||||
|
||||
def monkey_patch_nano_v3_reasoning_parser():
|
||||
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
|
||||
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
|
||||
|
||||
class NanoV3ReasoningParser(DeepSeekR1ReasoningParser):
|
||||
def extract_reasoning(self, model_output, request):
|
||||
reasoning_content, final_content = super().extract_reasoning(model_output, request)
|
||||
chat_template_kwargs = getattr(request, "chat_template_kwargs", None)
|
||||
|
||||
if chat_template_kwargs and chat_template_kwargs.get("enable_thinking") is False and final_content is None:
|
||||
reasoning_content, final_content = final_content, reasoning_content
|
||||
|
||||
return reasoning_content, final_content
|
||||
|
||||
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
@@ -66,6 +84,44 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
|
||||
|
||||
|
||||
def monkey_patch_strip_routed_experts_from_chat():
|
||||
"""Drop routed_experts from chat-completions responses.
|
||||
|
||||
routed_experts are only consumed via the serialized ``/generate``
|
||||
(serving_tokens) path used for router-replay training, which encodes them as a
|
||||
``{data, shape, start}`` object the PD router can merge. The stock
|
||||
chat-completions path instead encodes them as a base64 ``np.save`` *string*,
|
||||
which the PD router rejects ("prefill routed_experts must be an object with
|
||||
base64 data and shape") and fails every eval rollout (evals go through chat
|
||||
completions). ``enable_return_routed_experts`` is a server-wide model-config
|
||||
flag with no per-request toggle, so strip the field on the chat path here.
|
||||
"""
|
||||
from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
if getattr(OpenAIServingChat.chat_completion_full_generator, "_prime_rl_strips_routed_experts", False):
|
||||
return
|
||||
|
||||
_original = OpenAIServingChat.chat_completion_full_generator
|
||||
|
||||
async def _strip(result_generator):
|
||||
async for res in result_generator:
|
||||
for output in res.outputs:
|
||||
output.routed_experts = None
|
||||
yield res
|
||||
|
||||
async def _patched(self, request, result_generator, *args, **kwargs):
|
||||
return await _original(self, request, _strip(result_generator), *args, **kwargs)
|
||||
|
||||
_patched._prime_rl_strips_routed_experts = True
|
||||
OpenAIServingChat.chat_completion_full_generator = _patched
|
||||
logger.info(
|
||||
"Stripped routed_experts from chat-completions responses (PD router merges only the /generate object form)."
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
|
||||
y_ptr,
|
||||
@@ -836,3 +892,36 @@ def monkey_patch_fp32_lm_head():
|
||||
LogitsProcessor.__init__ = _patched_init
|
||||
LogitsProcessor._get_logits = _patched_get_logits
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
|
||||
|
||||
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
|
||||
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
|
||||
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
|
||||
"""
|
||||
import multiprocessing.connection
|
||||
import os
|
||||
|
||||
from vllm.v1.engine.coordinator import DPCoordinator
|
||||
|
||||
timeout = float(os.environ.get("PRIME_DP_COORDINATOR_STARTUP_TIMEOUT", "300"))
|
||||
|
||||
def _patched_wait_for_zmq_addrs(self, zmq_addr_pipe):
|
||||
try:
|
||||
ready = multiprocessing.connection.wait([zmq_addr_pipe, self.proc.sentinel], timeout=timeout)
|
||||
if not ready:
|
||||
raise RuntimeError(
|
||||
f"DP Coordinator process failed to report ZMQ addresses within {timeout}s during startup."
|
||||
)
|
||||
try:
|
||||
return zmq_addr_pipe.recv()
|
||||
except EOFError:
|
||||
raise RuntimeError("DP Coordinator process failed during startup.") from None
|
||||
finally:
|
||||
zmq_addr_pipe.close()
|
||||
|
||||
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
|
||||
|
||||
@@ -20,8 +20,11 @@ from prime_rl.utils.logger import get_logger
|
||||
|
||||
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,
|
||||
monkey_patch_vllm_padded_input_scrub,
|
||||
)
|
||||
@@ -35,9 +38,22 @@ 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()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
|
||||
# is available in our pinned runtime.
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
# NOTE: routed_experts are consumed only via the serialized /generate path (router
|
||||
# replay). The chat-completions path encodes them as a base64 np.save string the PD
|
||||
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
|
||||
# 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
|
||||
# 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()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
|
||||
|
||||
@@ -30,12 +30,17 @@ delegates to upstream so we track future vLLM changes for free.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncGenerator
|
||||
from collections.abc import AsyncGenerator, AsyncIterable
|
||||
from functools import cached_property
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
|
||||
from vllm.entrypoints.openai.engine.protocol import (
|
||||
ErrorResponse,
|
||||
PromptTokenUsageInfo,
|
||||
RequestResponseMetadata,
|
||||
UsageInfo,
|
||||
)
|
||||
from vllm.entrypoints.serve.disagg.protocol import (
|
||||
GenerateRequest,
|
||||
GenerateResponse,
|
||||
@@ -55,6 +60,12 @@ class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
|
||||
|
||||
class PrimeRlGenerateResponse(GenerateResponse):
|
||||
choices: list[PrimeRlGenerateResponseChoice]
|
||||
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
|
||||
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
|
||||
# Pydantic silently drops it on serialization. Declare it here so the
|
||||
# router can extract per-run token counts (and cached-prefix tokens) for
|
||||
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
|
||||
usage: UsageInfo | None = None
|
||||
|
||||
|
||||
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
@@ -74,6 +85,49 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
)
|
||||
|
||||
|
||||
class _FinalOutputCapture:
|
||||
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
|
||||
|
||||
Needed so the response builder can construct a ``usage`` block from
|
||||
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
|
||||
after delegating iteration to upstream.
|
||||
"""
|
||||
|
||||
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
|
||||
# ``source`` may be any async-iterable — including
|
||||
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
|
||||
# ``async def __aiter__`` (an async generator function) and has no
|
||||
# ``__anext__`` method. Drive it through ``async for`` rather than
|
||||
# poking ``__anext__`` directly so both shapes work.
|
||||
self._source = source
|
||||
self.final_res: RequestOutput | None = None
|
||||
|
||||
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
|
||||
async for item in self._source:
|
||||
self.final_res = item
|
||||
yield item
|
||||
|
||||
|
||||
def _build_usage(final_res: RequestOutput) -> UsageInfo:
|
||||
assert final_res.prompt_token_ids is not None
|
||||
num_prompt_tokens = len(final_res.prompt_token_ids)
|
||||
if final_res.encoder_prompt_token_ids is not None:
|
||||
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
|
||||
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
|
||||
usage = UsageInfo(
|
||||
prompt_tokens=num_prompt_tokens,
|
||||
completion_tokens=num_generated_tokens,
|
||||
total_tokens=num_prompt_tokens + num_generated_tokens,
|
||||
)
|
||||
# Always emit cached tokens when vLLM reports any. Upstream gates this on
|
||||
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
|
||||
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
|
||||
# billing pipeline always wants the cached subset surfaced.
|
||||
if final_res.num_cached_tokens:
|
||||
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
|
||||
return usage
|
||||
|
||||
|
||||
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
|
||||
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
|
||||
|
||||
@@ -273,11 +327,33 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
)
|
||||
result_generator = capture
|
||||
|
||||
# Always capture the final ``RequestOutput`` so we can attach a
|
||||
# ``usage`` block to the response. The router parses ``usage`` for
|
||||
# per-run billing metrics; without it the cache-discount counter
|
||||
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
|
||||
final_capture = _FinalOutputCapture(result_generator)
|
||||
result_generator = final_capture
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
|
||||
if capture is not None and isinstance(response, GenerateResponse):
|
||||
if not isinstance(response, GenerateResponse):
|
||||
return response
|
||||
|
||||
if capture is not None:
|
||||
response = capture.post_process(response)
|
||||
elif not isinstance(response, PrimeRlGenerateResponse):
|
||||
# Upgrade to the prime-rl subclass so the declared ``usage`` field
|
||||
# actually surfaces in JSON (the parent class would drop it).
|
||||
response = PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
if final_capture.final_res is not None:
|
||||
response.usage = _build_usage(final_capture.final_res)
|
||||
|
||||
return response
|
||||
|
||||
@@ -5,8 +5,6 @@ from typing import TYPE_CHECKING, Callable
|
||||
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from jaxtyping import Float
|
||||
from torch import Tensor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
@@ -14,11 +12,9 @@ if TYPE_CHECKING:
|
||||
from prime_rl.configs.orchestrator import (
|
||||
AdvantageConfig,
|
||||
CustomAdvantageConfig,
|
||||
LengthPenaltyConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
LinearLengthPenaltyConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import get_model_completion_len, get_tool_response_len
|
||||
from prime_rl.orchestrator.utils import get_model_completion_len
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -50,68 +46,36 @@ entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
|
||||
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_penalty: LengthPenaltyConfig | None = None,
|
||||
length_penalty: LinearLengthPenaltyConfig | None = None,
|
||||
max_seq_len: int | None = None,
|
||||
length_weighted_baseline: bool = False,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage for a single group: reward minus per-group baseline.
|
||||
|
||||
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
|
||||
cost: tokens (weighted completion + tool-response) or trajectory turn count.
|
||||
``length_penalty`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
|
||||
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
|
||||
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
|
||||
mean reward as the baseline instead of the plain mean.
|
||||
"""
|
||||
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
|
||||
lengths = torch.tensor([get_model_completion_len(r) for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
|
||||
if isinstance(length_penalty, TokensLengthPenaltyConfig):
|
||||
w_c = length_penalty.completion_weight
|
||||
w_t = length_penalty.tool_response_weight
|
||||
costs = torch.tensor(
|
||||
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
|
||||
costs = torch.tensor([len(r["trajectory"]) for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if length_penalty is not None:
|
||||
if max_seq_len is None:
|
||||
raise ValueError("max_seq_len is required when length_penalty is enabled")
|
||||
penalty = length_penalty.coef * rewards.mean() * (lengths / max_seq_len)
|
||||
if length_penalty.gate_by_correctness:
|
||||
penalty = penalty * rewards
|
||||
rewards = rewards - penalty
|
||||
|
||||
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
|
||||
if length_weighted_baseline:
|
||||
baseline = (lengths * rewards).sum() / lengths.sum()
|
||||
else:
|
||||
baseline = rewards.mean()
|
||||
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None) -> AdvantageFn:
|
||||
"""Setup advantage function from config."""
|
||||
if isinstance(config, CustomAdvantageConfig):
|
||||
custom_fn = import_object(config.import_path)
|
||||
@@ -123,7 +87,12 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
return advantage_fn
|
||||
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_penalty=config.length_penalty,
|
||||
max_seq_len=max_seq_len,
|
||||
length_weighted_baseline=config.length_weighted_baseline,
|
||||
)
|
||||
|
||||
return advantage_fn
|
||||
|
||||
|
||||
@@ -11,8 +11,9 @@
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
source's emptiness), so in-flight rollouts of the opposite kind drain
|
||||
naturally on either side of an eval boundary.
|
||||
- ``on_new_version`` (called by the watcher) bumps ``off_policy_steps`` on
|
||||
in-flight train rollouts and drops groups past ``max_off_policy_steps``.
|
||||
- ``on_version_pending`` (called by the watcher before the engines pause for
|
||||
the weight update) bumps ``off_policy_steps`` on in-flight train rollouts and
|
||||
drops groups past ``max_off_policy_steps``.
|
||||
Eval rollouts are measurements for the policy version they started with,
|
||||
so they are allowed to finish even if training advances.
|
||||
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
|
||||
@@ -116,7 +117,7 @@ class RolloutDispatcher:
|
||||
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
|
||||
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
|
||||
rollouts under shared capacity, and emits ``FinishedRollout``\\ s to
|
||||
``out_q``. The watcher drives ``on_new_version`` for off-policy
|
||||
``out_q``. The watcher drives ``on_version_pending`` for off-policy
|
||||
cancellation; the orchestrator triggers eval epochs."""
|
||||
|
||||
def __init__(
|
||||
@@ -263,11 +264,16 @@ class RolloutDispatcher:
|
||||
await safe_cancel(self.task)
|
||||
self.task = None
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""Bump off-policy counters and drop groups past
|
||||
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
|
||||
the sink still finalizes the partial group). Eval rollouts are not
|
||||
aged because they are tied to their start-time policy version."""
|
||||
aged because they are tied to their start-time policy version.
|
||||
|
||||
Runs *before* the inference engines are paused for the weight update so
|
||||
the resulting aborts are processed while the engine is still stepping —
|
||||
otherwise the orphaned KV transfers crash the decode engine on resume
|
||||
(see ``WeightWatcher.apply_policy_update``)."""
|
||||
stale_groups: set[uuid.UUID] = set()
|
||||
cancelled = 0
|
||||
for meta in self.inflight.values():
|
||||
@@ -287,6 +293,9 @@ class RolloutDispatcher:
|
||||
"Consider increasing it to avoid this."
|
||||
)
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
|
||||
|
||||
async def fill_inflight(self) -> None:
|
||||
"""Schedule new rollouts up to ``max_inflight``, honoring
|
||||
``self.mode``. Eval scheduling ignores the orchestrator's dispatch
|
||||
@@ -602,7 +611,7 @@ class RolloutDispatcher:
|
||||
# markers for those too so the sink hits ``target_rollouts``
|
||||
#
|
||||
# ``last_meta`` can be ``None`` if the only inflight task for this
|
||||
# group completed naturally between ``on_new_version``'s snapshot
|
||||
# group completed naturally between ``on_version_pending``'s snapshot
|
||||
# and us reaching it — synthesize a stand-in from the group state
|
||||
unscheduled_cancelled = 0
|
||||
if group is not None and group.rollouts_to_schedule > 0:
|
||||
|
||||
@@ -162,13 +162,13 @@ class Env:
|
||||
class TrainEnv(Env):
|
||||
config: TrainEnvConfig
|
||||
|
||||
def __init__(self, config: TrainEnvConfig):
|
||||
def __init__(self, config: TrainEnvConfig, max_seq_len: int):
|
||||
super().__init__(config)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
# Built once — custom advantage funcs do an ``import_object`` we don't
|
||||
# want to pay per group. ``None`` = reward-only path.
|
||||
self.advantage_fn: AdvantageFn | None = (
|
||||
setup_advantage_fn(config.advantage) if config.advantage is not None else None
|
||||
setup_advantage_fn(config.advantage, max_seq_len=max_seq_len) if config.advantage is not None else None
|
||||
)
|
||||
|
||||
def get_dataset(self, seed: int | None = None):
|
||||
@@ -246,10 +246,10 @@ class Envs(Generic[EnvT]):
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
"""Collection of training environments."""
|
||||
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig]):
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig], max_seq_len: int):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
for config in configs:
|
||||
env = TrainEnv(config)
|
||||
env = TrainEnv(config, max_seq_len=max_seq_len)
|
||||
self._envs[env.name] = env
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
|
||||
"""MetricsBuilder: assembles the per-step W&B dict.
|
||||
|
||||
The only I/O / state is the trainer's token-export metrics, which lag the
|
||||
orchestrator: ``build`` folds in the oldest unlogged stable step it finds on
|
||||
disk and tracks the last step logged so it never re-logs one.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,12 +12,16 @@ from typing import Any
|
||||
import pandas as pd
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.token_export_metrics import collect_next_token_export_metrics
|
||||
from prime_rl.orchestrator.types import Progress, TrainBatchMetrics, TrainRollout
|
||||
|
||||
|
||||
class MetricsBuilder:
|
||||
def __init__(self, config: OrchestratorConfig) -> None:
|
||||
def __init__(self, config: OrchestratorConfig, start_step: int = 0) -> None:
|
||||
self.config = config
|
||||
# Token exports are read back one step behind the orchestrator; track the
|
||||
# last run step whose metrics we've folded in so we never re-log a step.
|
||||
self._last_token_export_step_logged = start_step - 1
|
||||
|
||||
def build(
|
||||
self,
|
||||
@@ -179,8 +188,29 @@ class MetricsBuilder:
|
||||
for name, count in pre_filter_dropped_by_name.items():
|
||||
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
|
||||
|
||||
# Fold in the trainer's token-export metrics for the oldest unlogged stable
|
||||
# step (exports always lag the orchestrator, so this is a past step).
|
||||
to_log.update(self.next_token_export_metrics())
|
||||
|
||||
return to_log
|
||||
|
||||
@property
|
||||
def last_token_export_step_logged(self) -> int:
|
||||
return self._last_token_export_step_logged
|
||||
|
||||
def next_token_export_metrics(self) -> dict[str, float | int]:
|
||||
"""Log-ready token-export metrics for the next unlogged stable step (empty if
|
||||
none), advancing the cursor. They arrive under trainer/, including trainer/step
|
||||
(the run step they belong to) for plotting against a lag-corrected axis. Shared
|
||||
by build() and the orchestrator's end-of-run drain."""
|
||||
token_export = collect_next_token_export_metrics(
|
||||
self.config.output_dir,
|
||||
last_logged_step=self._last_token_export_step_logged,
|
||||
)
|
||||
if token_export:
|
||||
self._last_token_export_step_logged = token_export["trainer/step"]
|
||||
return token_export
|
||||
|
||||
@staticmethod
|
||||
def timing_df(rollouts: list[TrainRollout]) -> pd.DataFrame:
|
||||
return pd.DataFrame(
|
||||
|
||||
@@ -21,7 +21,6 @@ in ``setup()`` and drives them from ``main_loop()``.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import ctypes
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
@@ -72,6 +71,7 @@ from prime_rl.orchestrator.utils import (
|
||||
save_rollouts,
|
||||
set_default_executor,
|
||||
setup_student_inference_pool,
|
||||
trim_process_memory,
|
||||
)
|
||||
from prime_rl.orchestrator.watcher import WeightWatcher
|
||||
from prime_rl.trainer.model import setup_tokenizer
|
||||
@@ -108,6 +108,11 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# After max_steps, how long to wait for the trainer to finalize the trailing
|
||||
# token-export steps it hadn't flushed yet, and how often to poll for them.
|
||||
TOKEN_EXPORT_DRAIN_TIMEOUT_S = 300.0
|
||||
TOKEN_EXPORT_DRAIN_POLL_S = 2.0
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
# Set in ``__init__``
|
||||
@@ -263,7 +268,7 @@ class Orchestrator:
|
||||
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(config.train.env)
|
||||
self.train_envs = TrainEnvs(config.train.env, max_seq_len=config.seq_len)
|
||||
if config.training_mode == "sft":
|
||||
for env in self.train_envs:
|
||||
env.sampling_args.pop("logprobs", None)
|
||||
@@ -382,7 +387,7 @@ class Orchestrator:
|
||||
training_mode=config.training_mode,
|
||||
use_cache_salt=use_cache_salt,
|
||||
)
|
||||
self.metrics = MetricsBuilder(config)
|
||||
self.metrics = MetricsBuilder(config, start_step=self.progress.step)
|
||||
self.train_sink = TrainSink(
|
||||
config,
|
||||
tokenizer=self.tokenizer,
|
||||
@@ -460,6 +465,7 @@ class Orchestrator:
|
||||
clean_exit = False
|
||||
try:
|
||||
await self.main_loop()
|
||||
await self._drain_token_export_metrics()
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
@@ -476,10 +482,7 @@ class Orchestrator:
|
||||
get_logger().success("Orchestrator finished.")
|
||||
else:
|
||||
get_logger().warning("Orchestrator cleanup complete (forced).")
|
||||
try:
|
||||
ctypes.CDLL("libc.so.6").malloc_trim(0)
|
||||
except Exception as e:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {e}")
|
||||
trim_process_memory()
|
||||
|
||||
async def main_loop(self) -> None:
|
||||
"""Consume ``FinishedRollout``\\ s from the dispatcher and route them
|
||||
@@ -510,6 +513,35 @@ class Orchestrator:
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
|
||||
async def _drain_token_export_metrics(self) -> None:
|
||||
"""Token exports lag the orchestrator, so once the loop ends the trainer is
|
||||
still finalizing the last shipped steps and ``build`` no longer runs to pick
|
||||
them up. Poll for the remaining stable steps up to ``max_steps - 1`` and log
|
||||
each under its own ``trainer/step`` (a local W&B step axis, so the final
|
||||
checkpoint's ``progress.step`` is untouched)."""
|
||||
if self.config.max_steps is None:
|
||||
return
|
||||
if not (self.config.output_dir / "token_exports").exists():
|
||||
return # token export not enabled for this run — don't block shutdown
|
||||
target = self.config.max_steps - 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return # build() already kept up — nothing trailing to flush
|
||||
wandb_step = self.progress.step
|
||||
deadline = time.perf_counter() + TOKEN_EXPORT_DRAIN_TIMEOUT_S
|
||||
while time.perf_counter() < deadline:
|
||||
token_export = self.metrics.next_token_export_metrics()
|
||||
if not token_export:
|
||||
await asyncio.sleep(TOKEN_EXPORT_DRAIN_POLL_S)
|
||||
continue
|
||||
self.monitor.log(token_export, step=wandb_step)
|
||||
wandb_step += 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return
|
||||
get_logger().warning(
|
||||
f"Token-export drain timed out before step {target} "
|
||||
f"(last logged {self.metrics.last_token_export_step_logged})"
|
||||
)
|
||||
|
||||
async def finalize_train_batch(self, batch: TrainBatch) -> None:
|
||||
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
|
||||
side-effects (ckpt, save_rollouts, teacher logprobs, sender.send,
|
||||
@@ -579,6 +611,7 @@ class Orchestrator:
|
||||
|
||||
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
|
||||
self.update_dispatch_gate()
|
||||
trim_process_memory()
|
||||
|
||||
metrics = self.metrics.build(
|
||||
step=step,
|
||||
@@ -841,6 +874,10 @@ class Orchestrator:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
|
||||
the new policy version is live."""
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
|
||||
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
TOKEN_EXPORT_METRIC_FIELDS = ("mismatch_kl", "entropy")
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Stats:
|
||||
total: float = 0.0
|
||||
count: int = 0
|
||||
maximum: float = -math.inf
|
||||
|
||||
def add(self, value: Any) -> None:
|
||||
if not isinstance(value, int | float):
|
||||
return
|
||||
value = float(value)
|
||||
if not math.isfinite(value):
|
||||
return
|
||||
self.total += value
|
||||
self.count += 1
|
||||
self.maximum = max(self.maximum, value)
|
||||
|
||||
def as_metrics(self, prefix: str) -> dict[str, float]:
|
||||
if self.count == 0:
|
||||
return {}
|
||||
return {
|
||||
f"{prefix}/mean": self.total / self.count,
|
||||
f"{prefix}/max": self.maximum,
|
||||
}
|
||||
|
||||
|
||||
def collect_next_token_export_metrics(output_dir: Path, *, last_logged_step: int) -> dict[str, float | int]:
|
||||
"""Log-ready metrics for the oldest unlogged stable step, namespaced under
|
||||
``trainer/`` and stamped with ``trainer/step`` (the run step they belong to).
|
||||
Empty when there is no new stable step."""
|
||||
stable_steps = [step for step in _stable_token_export_steps(output_dir) if step > last_logged_step]
|
||||
if not stable_steps:
|
||||
return {}
|
||||
|
||||
step = min(stable_steps)
|
||||
metrics: dict[str, float | int] = {
|
||||
f"trainer/{key}": value for key, value in collect_token_export_metrics(output_dir, step).items()
|
||||
}
|
||||
metrics["trainer/step"] = step
|
||||
return metrics
|
||||
|
||||
|
||||
def collect_token_export_metrics(output_dir: Path, step: int) -> dict[str, float | int]:
|
||||
step_dir = output_dir / "token_exports" / f"step_{step}"
|
||||
if not (step_dir / "STABLE").exists():
|
||||
return {}
|
||||
|
||||
stats_by_key: dict[str, _Stats] = {}
|
||||
sequence_count = 0
|
||||
skipped_count = 0
|
||||
|
||||
for export_file in sorted(step_dir.glob("rank_*.jsonl")):
|
||||
with export_file.open(encoding="utf-8") as file:
|
||||
for line in file:
|
||||
if not line.strip():
|
||||
continue
|
||||
# Token exports are best-effort monitoring; a malformed line or a
|
||||
# length-mismatched record shouldn't abort the orchestrator step.
|
||||
try:
|
||||
record = json.loads(line)
|
||||
values_by_field = {field: _loss_token_values(record, field) for field in TOKEN_EXPORT_METRIC_FIELDS}
|
||||
except ValueError:
|
||||
skipped_count += 1
|
||||
continue
|
||||
sequence_count += 1
|
||||
for field, values in values_by_field.items():
|
||||
for value in values:
|
||||
stats_by_key.setdefault(field, _Stats()).add(value)
|
||||
|
||||
if skipped_count:
|
||||
get_logger().warning(f"Skipped {skipped_count} malformed token-export record(s) in {step_dir}")
|
||||
|
||||
metrics: dict[str, float | int] = {}
|
||||
if sequence_count == 0:
|
||||
return metrics
|
||||
for key, stats in sorted(stats_by_key.items()):
|
||||
metrics.update(stats.as_metrics(key))
|
||||
return metrics
|
||||
|
||||
|
||||
def _stable_token_export_steps(output_dir: Path) -> list[int]:
|
||||
token_exports_dir = output_dir / "token_exports"
|
||||
if not token_exports_dir.exists():
|
||||
return []
|
||||
|
||||
steps = []
|
||||
for step_dir in token_exports_dir.glob("step_*"):
|
||||
if not (step_dir / "STABLE").exists():
|
||||
continue
|
||||
try:
|
||||
steps.append(int(step_dir.name.removeprefix("step_")))
|
||||
except ValueError:
|
||||
continue
|
||||
return sorted(steps)
|
||||
|
||||
|
||||
def _loss_token_values(record: dict[str, Any], field: str) -> list[Any]:
|
||||
loss_mask = record.get("loss_mask", [])
|
||||
values = record.get(field, [])
|
||||
if len(loss_mask) != len(values):
|
||||
raise ValueError(
|
||||
f"Token export record has mismatched loss_mask and {field} lengths: {len(loss_mask)} != {len(values)}"
|
||||
)
|
||||
return [value for value, keep in zip(values, loss_mask) if keep]
|
||||
@@ -202,7 +202,12 @@ class EvalBatch:
|
||||
|
||||
|
||||
class VersionObserver(Protocol):
|
||||
"""Notified after each policy update; walked by the watcher after it
|
||||
mutates ``Policy``."""
|
||||
"""Notified around each policy update; walked by the watcher.
|
||||
|
||||
``on_version_pending`` fires *before* the inference engines are paused for
|
||||
the weight update; ``on_new_version`` fires *after* the new weights are live
|
||||
and ``Policy`` has been mutated."""
|
||||
|
||||
async def on_version_pending(self, step: int) -> None: ...
|
||||
|
||||
async def on_new_version(self, step: int) -> None: ...
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import asyncio
|
||||
import ctypes
|
||||
import gc
|
||||
import logging
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
@@ -96,6 +98,15 @@ def set_default_executor(max_workers: int = 64) -> None:
|
||||
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
|
||||
|
||||
|
||||
def trim_process_memory() -> None:
|
||||
"""Return freed heap pages to the OS on glibc systems."""
|
||||
gc.collect()
|
||||
try:
|
||||
ctypes.CDLL("libc.so.6").malloc_trim(0)
|
||||
except Exception as exc:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
|
||||
|
||||
|
||||
async def compute_teacher_logprobs(
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
|
||||
@@ -92,6 +92,24 @@ class WeightWatcher:
|
||||
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
|
||||
)
|
||||
|
||||
# Drain off-policy rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
# ``_reqs_not_processed``), which is only propagated to the workers
|
||||
# while the engine is stepping. If we drain after resume instead,
|
||||
# the aborts race with the flush of KV transfers that completed
|
||||
# during the pause and trip ``assert req_id in self.requests`` in
|
||||
# the decode scheduler's ``_update_from_kv_xfer_finished`` — killing
|
||||
# the engine and cascading to every DP rank. Draining first lets the
|
||||
# aborts settle under normal stepping. ``on_new_version`` (below)
|
||||
# still runs post-update for observers that need the live version.
|
||||
for observer in self.observers:
|
||||
try:
|
||||
await observer.on_version_pending(next_step)
|
||||
except Exception as exc:
|
||||
get_logger().warning(
|
||||
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
|
||||
)
|
||||
|
||||
get_logger().debug(f"Updating weights to step {next_step}")
|
||||
t1 = time.perf_counter()
|
||||
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
|
||||
|
||||
@@ -51,6 +51,7 @@ export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
mkdir -p $OUTPUT_DIR/logs/inference
|
||||
rm -f $OUTPUT_DIR/logs/inference/*.log
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
|
||||
# General
|
||||
|
||||
@@ -57,6 +57,7 @@ export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export ORCHESTRATOR_OUTPUT_DIR={{ orchestrator_output_dir }}
|
||||
mkdir -p $OUTPUT_DIR/logs/trainer $OUTPUT_DIR/logs/inference
|
||||
rm -f $OUTPUT_DIR/logs/inference/*.log
|
||||
ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
|
||||
@@ -353,15 +354,6 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
|
||||
else
|
||||
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
|
||||
|
||||
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
fi
|
||||
{%- else %}
|
||||
TRAIN_NODE_RANK=$SLURM_PROCID
|
||||
{%- endif %}
|
||||
@@ -388,6 +380,21 @@ else
|
||||
@ $CONFIG_DIR/trainer.toml \
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
{% if num_infer_nodes > 0 %} fi{% endif %}
|
||||
{% if num_infer_nodes > 0 %}
|
||||
# Launch the orchestrator on one node. Default is trainer rank 0 (SLURM_PROCID ==
|
||||
# NUM_INFER_NODES). With orchestrator_on_inference it moves to the last inference node
|
||||
# (a decode node) to keep its rollout buffer + env workers off host-RAM-saturated
|
||||
# trainer nodes. Top-level (after the role if/else) so the wait -n teardown covers it.
|
||||
{% if orchestrator_on_inference %}ORCH_PROCID=$((NUM_INFER_NODES - 1)){% else %}ORCH_PROCID=$NUM_INFER_NODES{% endif %}
|
||||
if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
# turns background process crashes (router, orchestrator) into task failures
|
||||
|
||||
+185
-76
@@ -1,5 +1,8 @@
|
||||
import copy
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
from prime_rl.trainer.utils import balanced_partition
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
|
||||
|
||||
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
|
||||
@@ -30,17 +33,6 @@ def _slice_routed_experts(routed_experts: RoutedExperts, seq_len: int) -> Routed
|
||||
)
|
||||
|
||||
|
||||
def _append_routed_experts(dst: MicroBatch, src: MicroBatch) -> None:
|
||||
dst_routed = dst.routed_experts
|
||||
src_routed = src.routed_experts
|
||||
assert dst_routed is not None
|
||||
assert src_routed is not None
|
||||
assert dst_routed.dtype == src_routed.dtype
|
||||
assert dst_routed.shape[1:] == src_routed.shape[1:]
|
||||
dst_routed.data += src_routed.data
|
||||
dst_routed.shape[0] += src_routed.shape[0]
|
||||
|
||||
|
||||
def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
|
||||
routed_experts = micro_batch.routed_experts
|
||||
assert routed_experts is not None
|
||||
@@ -125,6 +117,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
loss_mask=loss_mask,
|
||||
position_ids=position_ids,
|
||||
inference_logprobs=inference_logprobs,
|
||||
sequence_lengths=[len(input_ids)],
|
||||
teacher_logprobs=teacher_logprobs,
|
||||
temperatures=temperatures,
|
||||
rewards=rewards,
|
||||
@@ -141,8 +134,149 @@ def _is_multimodal_sample(sample: MicroBatch) -> bool:
|
||||
return sample.mm_kwargs is not None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _MicroBatchBin:
|
||||
samples: list[tuple[int, MicroBatch]]
|
||||
length: int
|
||||
|
||||
@classmethod
|
||||
def from_sample(cls, lora_idx: int, sample: MicroBatch) -> "_MicroBatchBin":
|
||||
return cls(samples=[(lora_idx, sample)], length=len(sample.input_ids))
|
||||
|
||||
@property
|
||||
def first_sample(self) -> MicroBatch:
|
||||
return self.samples[0][1]
|
||||
|
||||
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
|
||||
first_sample = self.first_sample
|
||||
return (
|
||||
not _is_multimodal_sample(first_sample)
|
||||
and not _is_multimodal_sample(sample)
|
||||
and self.length + len(sample.input_ids) <= max_seq_len
|
||||
and first_sample.training_mode == sample.training_mode
|
||||
and (first_sample.routed_experts is None) == (sample.routed_experts is None)
|
||||
)
|
||||
|
||||
def add(self, lora_idx: int, sample: MicroBatch) -> None:
|
||||
self.samples.append((lora_idx, sample))
|
||||
self.length += len(sample.input_ids)
|
||||
|
||||
def workload(self, bin_cost: Callable[[Sequence[int]], int]) -> int:
|
||||
return bin_cost([len(sample.input_ids) for _, sample in self.samples])
|
||||
|
||||
def split_by_workload(self, bin_cost: Callable[[Sequence[int]], int]) -> tuple["_MicroBatchBin", "_MicroBatchBin"]:
|
||||
# Greedily place the heaviest sample on the currently lighter side (longest-processing-time).
|
||||
ranked = sorted(self.samples, key=lambda pair: -bin_cost([len(pair[1].input_ids)]))
|
||||
left: list[tuple[int, MicroBatch]] = []
|
||||
right: list[tuple[int, MicroBatch]] = []
|
||||
left_workload = right_workload = 0
|
||||
for lora_idx, sample in ranked:
|
||||
sample_workload = bin_cost([len(sample.input_ids)])
|
||||
if left_workload <= right_workload:
|
||||
left.append((lora_idx, sample))
|
||||
left_workload += sample_workload
|
||||
else:
|
||||
right.append((lora_idx, sample))
|
||||
right_workload += sample_workload
|
||||
return (
|
||||
_MicroBatchBin(left, sum(len(sample.input_ids) for _, sample in left)),
|
||||
_MicroBatchBin(right, sum(len(sample.input_ids) for _, sample in right)),
|
||||
)
|
||||
|
||||
|
||||
def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
||||
has_rewards = any(sample.rewards is not None for _, sample in bin_content.samples)
|
||||
has_teacher_logprobs = any(sample.teacher_logprobs is not None for _, sample in bin_content.samples)
|
||||
has_mm_token_type_ids = any(sample.mm_token_type_ids is not None for _, sample in bin_content.samples)
|
||||
|
||||
input_ids: list[int] = []
|
||||
loss_mask: list[bool] = []
|
||||
advantages: list[float] = []
|
||||
inference_logprobs: list[float] = []
|
||||
position_ids: list[int] = []
|
||||
temperatures: list[float] = []
|
||||
env_names: list[str] = []
|
||||
rewards: list[float] | None = [] if has_rewards else None
|
||||
teacher_logprobs: list[float] | None = [] if has_teacher_logprobs else None
|
||||
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
|
||||
routed_experts: RoutedExperts | None = None
|
||||
lora_num_tokens = [0] * num_loras
|
||||
|
||||
for lora_idx, sample in bin_content.samples:
|
||||
sample_len = len(sample.input_ids)
|
||||
input_ids.extend(sample.input_ids)
|
||||
loss_mask.extend(sample.loss_mask)
|
||||
advantages.extend(sample.advantages)
|
||||
inference_logprobs.extend(sample.inference_logprobs)
|
||||
position_ids.extend(sample.position_ids)
|
||||
temperatures.extend(sample.temperatures)
|
||||
env_names.extend(sample.env_names)
|
||||
if rewards is not None:
|
||||
rewards.extend(sample.rewards if sample.rewards is not None else [float("nan")] * sample_len)
|
||||
if teacher_logprobs is not None:
|
||||
teacher_logprobs.extend(
|
||||
sample.teacher_logprobs if sample.teacher_logprobs is not None else [0.0] * sample_len
|
||||
)
|
||||
if mm_token_type_ids is not None:
|
||||
mm_token_type_ids.extend(
|
||||
sample.mm_token_type_ids if sample.mm_token_type_ids is not None else [0] * sample_len
|
||||
)
|
||||
if sample.routed_experts is not None:
|
||||
if routed_experts is None:
|
||||
routed_experts = _copy_routed_experts(sample.routed_experts)
|
||||
else:
|
||||
assert routed_experts.dtype == sample.routed_experts.dtype
|
||||
assert routed_experts.shape[1:] == sample.routed_experts.shape[1:]
|
||||
routed_experts.data += sample.routed_experts.data
|
||||
routed_experts.shape[0] += sample.routed_experts.shape[0]
|
||||
lora_num_tokens[lora_idx] += sample_len
|
||||
|
||||
sequence_lengths = [len(sample.input_ids) for _, sample in bin_content.samples]
|
||||
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
|
||||
first_sample = bin_content.first_sample
|
||||
|
||||
return MicroBatch(
|
||||
input_ids=input_ids,
|
||||
advantages=advantages,
|
||||
loss_mask=loss_mask,
|
||||
position_ids=position_ids,
|
||||
inference_logprobs=inference_logprobs,
|
||||
sequence_lengths=sequence_lengths,
|
||||
teacher_logprobs=teacher_logprobs,
|
||||
temperatures=temperatures,
|
||||
rewards=rewards,
|
||||
lora_num_tokens=lora_num_tokens,
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=first_sample.mm_kwargs if _is_multimodal_sample(first_sample) else None,
|
||||
training_mode=first_sample.training_mode,
|
||||
)
|
||||
|
||||
|
||||
def _expand_bins_by_splitting(
|
||||
bins: list[_MicroBatchBin], target_count: int, bin_cost: Callable[[Sequence[int]], int]
|
||||
) -> None:
|
||||
while len(bins) < target_count:
|
||||
candidates = [
|
||||
(bin_content.workload(bin_cost), idx)
|
||||
for idx, bin_content in enumerate(bins)
|
||||
if len(bin_content.samples) > 1
|
||||
]
|
||||
if not candidates:
|
||||
break
|
||||
_, idx = max(candidates)
|
||||
left, right = bins[idx].split_by_workload(bin_cost)
|
||||
bins[idx] = left
|
||||
bins.append(right)
|
||||
|
||||
|
||||
def packed_samples_into_micro_bs(
|
||||
samples: list[tuple[int, MicroBatch]], max_seq_len: int, num_loras: int
|
||||
samples: list[tuple[int, MicroBatch]],
|
||||
max_seq_len: int,
|
||||
num_loras: int,
|
||||
num_train_workers: int,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
) -> list[MicroBatch]:
|
||||
"""
|
||||
Pack samples into micro_batch efficiently.
|
||||
@@ -155,63 +289,40 @@ def packed_samples_into_micro_bs(
|
||||
# Sort by (lora_idx, -length) for packing efficiency
|
||||
samples.sort(key=lambda x: (x[0], -len(x[1].input_ids)))
|
||||
|
||||
## we create bins
|
||||
micro_batches: list[MicroBatch] = []
|
||||
bins: list[_MicroBatchBin] = []
|
||||
|
||||
for idx, sample in samples:
|
||||
# Multimodal samples cannot be packed - each becomes its own micro batch
|
||||
if _is_multimodal_sample(sample):
|
||||
sample.lora_num_tokens = [0] * num_loras
|
||||
sample.lora_num_tokens[idx] = len(sample.input_ids)
|
||||
micro_batches.append(sample)
|
||||
continue
|
||||
|
||||
# Try to find a bin that can fit this sequence (only pack text-only samples)
|
||||
for bin_content in micro_batches:
|
||||
# Don't pack into multimodal micro batches
|
||||
if _is_multimodal_sample(bin_content):
|
||||
continue
|
||||
# Check if sequence fits in this bin
|
||||
if (
|
||||
len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len
|
||||
and bin_content.training_mode == sample.training_mode
|
||||
):
|
||||
existing_len = len(bin_content.input_ids)
|
||||
bin_content.input_ids.extend(sample.input_ids)
|
||||
bin_content.loss_mask.extend(sample.loss_mask)
|
||||
bin_content.advantages.extend(sample.advantages)
|
||||
if sample.rewards is not None:
|
||||
if bin_content.rewards is None:
|
||||
bin_content.rewards = [float("nan")] * existing_len
|
||||
bin_content.rewards.extend(sample.rewards)
|
||||
elif bin_content.rewards is not None:
|
||||
bin_content.rewards.extend([float("nan")] * len(sample.input_ids))
|
||||
bin_content.inference_logprobs.extend(sample.inference_logprobs)
|
||||
bin_content.temperatures.extend(sample.temperatures)
|
||||
if sample.teacher_logprobs is not None:
|
||||
if bin_content.teacher_logprobs is None:
|
||||
bin_content.teacher_logprobs = []
|
||||
bin_content.teacher_logprobs.extend(sample.teacher_logprobs)
|
||||
assert (bin_content.routed_experts is None) == (sample.routed_experts is None)
|
||||
if sample.routed_experts is not None:
|
||||
if bin_content.routed_experts is None:
|
||||
bin_content.routed_experts = _copy_routed_experts(sample.routed_experts)
|
||||
else:
|
||||
_append_routed_experts(bin_content, sample)
|
||||
if sample.mm_token_type_ids is not None:
|
||||
if bin_content.mm_token_type_ids is None:
|
||||
bin_content.mm_token_type_ids = []
|
||||
bin_content.mm_token_type_ids.extend(sample.mm_token_type_ids)
|
||||
bin_content.env_names.extend(sample.env_names)
|
||||
bin_content.position_ids.extend(sample.position_ids)
|
||||
bin_content.lora_num_tokens[idx] += len(sample.input_ids)
|
||||
for bin_content in bins:
|
||||
if bin_content.can_add(sample, max_seq_len):
|
||||
bin_content.add(idx, sample)
|
||||
break
|
||||
else:
|
||||
sample.lora_num_tokens = [0] * num_loras
|
||||
sample.lora_num_tokens[idx] = len(sample.input_ids)
|
||||
micro_batches.append(sample)
|
||||
bins.append(_MicroBatchBin.from_sample(idx, sample))
|
||||
|
||||
return micro_batches
|
||||
if num_train_workers > 1:
|
||||
target_count = max(
|
||||
((len(bins) + num_train_workers - 1) // num_train_workers) * num_train_workers,
|
||||
num_train_workers,
|
||||
)
|
||||
_expand_bins_by_splitting(bins, target_count, bin_cost)
|
||||
|
||||
return [_materialize_bin(bin_content, num_loras) for bin_content in bins]
|
||||
|
||||
|
||||
def _distribute_group(
|
||||
group: list[MicroBatch],
|
||||
num_train_workers: int,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
) -> list[list[MicroBatch]]:
|
||||
# Callers pad each group to a positive multiple of num_train_workers first.
|
||||
assert len(group) % num_train_workers == 0, "Number of micro batches is not divisible by number of data ranks"
|
||||
if not group:
|
||||
return [[] for _ in range(num_train_workers)]
|
||||
|
||||
weights = [bin_cost(micro_batch.sequence_lengths) for micro_batch in group]
|
||||
partitions = balanced_partition(weights, num_train_workers)
|
||||
return [[group[i] for i in partition] for partition in partitions]
|
||||
|
||||
|
||||
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
|
||||
@@ -242,14 +353,16 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
micro_batch.rewards.extend([float("nan")] * padding_size)
|
||||
micro_batch.loss_mask.extend([False] * padding_size)
|
||||
micro_batch.position_ids.extend(list(range(padding_size)))
|
||||
micro_batch.sequence_lengths.append(padding_size)
|
||||
micro_batch.inference_logprobs.extend([0.0] * padding_size)
|
||||
# Use temperature 1.0 for padding tokens (doesn't matter since loss_mask is False)
|
||||
micro_batch.temperatures.extend([1.0] * padding_size)
|
||||
if micro_batch.teacher_logprobs is not None:
|
||||
micro_batch.teacher_logprobs.extend([0.0] * padding_size)
|
||||
micro_batch.lora_num_tokens[-1] += (
|
||||
padding_size # We send padding to the last lora so that tokens have ascending lora idx
|
||||
)
|
||||
if micro_batch.lora_num_tokens is not None:
|
||||
micro_batch.lora_num_tokens[-1] += (
|
||||
padding_size # We send padding to the last lora so that tokens have ascending lora idx
|
||||
)
|
||||
if micro_batch.mm_token_type_ids is not None:
|
||||
micro_batch.mm_token_type_ids.extend([0] * padding_size)
|
||||
if micro_batch.routed_experts is not None:
|
||||
@@ -282,6 +395,7 @@ def prepare_batch(
|
||||
num_train_workers: int,
|
||||
idxs: list[int],
|
||||
num_loras: int,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
pad_to_multiple_of: int = 1,
|
||||
) -> list[list[MicroBatch]]:
|
||||
"""
|
||||
@@ -295,7 +409,7 @@ def prepare_batch(
|
||||
"""
|
||||
all_samples = [(idx, prepare_sample(rollout, seq_len)) for idx, rollout in zip(idxs, rollouts)]
|
||||
|
||||
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras)
|
||||
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras, num_train_workers, bin_cost)
|
||||
micro_batches = [pad_micro_batch(micro_batch, pad_to_multiple_of) for micro_batch in micro_batches]
|
||||
|
||||
# Separate by modality so each step index has uniform modality across all ranks
|
||||
@@ -306,15 +420,10 @@ def prepare_batch(
|
||||
mm_batches = _pad_group_for_distribution(mm_batches, num_train_workers)
|
||||
text_batches = _pad_group_for_distribution(text_batches, num_train_workers)
|
||||
|
||||
# Combine: all multimodal first, then all text-only. Since each group's length is
|
||||
# divisible by num_train_workers, the modality boundary aligns with distribution rows.
|
||||
ordered = mm_batches + text_batches
|
||||
|
||||
assert len(ordered) % num_train_workers == 0, "Number of micro batches is not divisible by number of data ranks"
|
||||
|
||||
# Distribute in strided order so each step index has the same modality across ranks
|
||||
batches_per_gpu: list[list[MicroBatch]] = [[] for _ in range(num_train_workers)]
|
||||
for i, batch in enumerate(ordered):
|
||||
batches_per_gpu[i % num_train_workers].append(batch)
|
||||
for group in (mm_batches, text_batches):
|
||||
group_batches_per_gpu = _distribute_group(group, num_train_workers, bin_cost)
|
||||
for worker_idx, worker_batches in enumerate(group_batches_per_gpu):
|
||||
batches_per_gpu[worker_idx].extend(worker_batches)
|
||||
|
||||
return batches_per_gpu
|
||||
|
||||
@@ -37,6 +37,7 @@ from prime_rl.trainer.models import (
|
||||
get_custom_vlm_cls,
|
||||
supports_custom_impl,
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
|
||||
from prime_rl.trainer.models.layers.checkpointing import (
|
||||
get_supported_targets,
|
||||
set_selective_activation_checkpointing,
|
||||
@@ -350,6 +351,29 @@ def freeze_moe_router(model: nn.Module) -> None:
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
|
||||
|
||||
def freeze_sparse_indexer(model: nn.Module) -> None:
|
||||
"""Freeze DSA sparse-attention indexer parameters.
|
||||
|
||||
The indexer's `compute_sparse_indices` forward runs under `torch.no_grad()`, so its
|
||||
params never receive a gradient and cannot be trained. Left with requires_grad=True
|
||||
they stay stateless in the optimizer, which breaks strict checkpoint resume: DCP
|
||||
materializes optimizer state for every requires_grad param at load time, but the
|
||||
stateless params were never saved -> "Missing key in checkpoint state_dict". Freezing
|
||||
them keeps the saved and loaded optimizer state symmetric.
|
||||
"""
|
||||
logger = get_logger()
|
||||
num_frozen = 0
|
||||
|
||||
for module in model.modules():
|
||||
if isinstance(module, Indexer):
|
||||
for param in module.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
|
||||
if num_frozen > 0:
|
||||
logger.info(f"Froze {num_frozen} sparse indexer parameters")
|
||||
|
||||
|
||||
def apply_force_balanced_routing(model: nn.Module) -> None:
|
||||
"""Force MoE token-choice routers into round-robin assignment for fake-data smoke tests."""
|
||||
logger = get_logger()
|
||||
@@ -1075,6 +1099,11 @@ def setup_model(
|
||||
if config.freeze_moe_router:
|
||||
freeze_moe_router(model)
|
||||
|
||||
# The DSA sparse-attention indexer runs its forward under torch.no_grad(), so it is
|
||||
# never trainable. Freeze it so optimizer state stays symmetric across checkpoint
|
||||
# save/resume. No-op for models without a sparse indexer.
|
||||
freeze_sparse_indexer(model)
|
||||
|
||||
if config.debug.force_balanced_routing:
|
||||
apply_force_balanced_routing(model)
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import torch.nn as nn
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.vlm import get_final_logit_softcapping
|
||||
|
||||
FUSED_CE_IGNORE_INDEX = -100
|
||||
|
||||
@@ -299,8 +300,8 @@ def inject_prime_lm_head(
|
||||
|
||||
logger = get_logger()
|
||||
|
||||
# Check for Gemma-style softcapping - dispatch to specialized implementation
|
||||
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
|
||||
# Check for Gemma-style softcapping - dispatch to specialized implementation.
|
||||
final_logit_softcapping = get_final_logit_softcapping(model.config)
|
||||
if final_logit_softcapping:
|
||||
if fused_cross_entropy == "quack":
|
||||
raise ValueError(
|
||||
|
||||
@@ -149,10 +149,15 @@ def _create_optimizer(
|
||||
"""Create optimizer. If lr is None, uses config.lr."""
|
||||
if lr is None:
|
||||
lr = config.lr
|
||||
# Only hand trainable params to the optimizer. Frozen params (e.g. the DSA sparse
|
||||
# indexer, which runs under no_grad) carry no optimizer state, and including them
|
||||
# breaks strict checkpoint resume (DCP materializes state for every requires_grad
|
||||
# param at load time, mismatching the saved state). Muon filters internally below.
|
||||
trainable_params = [p for _, p in named_params if p.requires_grad]
|
||||
match config.type:
|
||||
case "sgd":
|
||||
return SGD(
|
||||
params=[p for _, p in named_params],
|
||||
params=trainable_params,
|
||||
lr=lr,
|
||||
weight_decay=config.weight_decay,
|
||||
momentum=config.momentum,
|
||||
@@ -160,7 +165,7 @@ def _create_optimizer(
|
||||
)
|
||||
case "adamw":
|
||||
return AdamW(
|
||||
params=[p for _, p in named_params],
|
||||
params=trainable_params,
|
||||
lr=lr,
|
||||
weight_decay=config.weight_decay,
|
||||
betas=(config.betas1, config.betas2),
|
||||
@@ -169,7 +174,7 @@ def _create_optimizer(
|
||||
return _create_muon_optimizer(config, named_params, parallel_dims, lr)
|
||||
case "sign_sgd":
|
||||
return SignSGD(
|
||||
params=[p for _, p in named_params],
|
||||
params=trainable_params,
|
||||
lr=lr,
|
||||
weight_decay=config.weight_decay,
|
||||
)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from collections.abc import Callable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
@@ -10,7 +11,12 @@ from prime_rl.configs.trainer import FakeDataLoaderConfig
|
||||
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfig, setup_micro_batch_receiver
|
||||
from prime_rl.transport import (
|
||||
MicroBatch,
|
||||
MicroBatchReceiver,
|
||||
TransportConfig,
|
||||
setup_micro_batch_receiver,
|
||||
)
|
||||
|
||||
|
||||
class TensorMicroBatch(TypedDict):
|
||||
@@ -26,6 +32,7 @@ class TensorMicroBatch(TypedDict):
|
||||
loss_mask: Bool[Tensor, "batch seq"]
|
||||
temperatures: Float[Tensor, "batch seq"] # Per-token temperatures
|
||||
env_names: list[str]
|
||||
sequence_lengths: list[int]
|
||||
|
||||
# Batch level
|
||||
lora_num_tokens: Int[Tensor, "n_loras"]
|
||||
@@ -46,6 +53,10 @@ class TensorMicroBatch(TypedDict):
|
||||
# sft → sft loss). All samples in a micro batch share the same mode.
|
||||
training_mode: str
|
||||
|
||||
# Packer-derived metadata used for run-local debug exports.
|
||||
run_id: str | None
|
||||
run_step: int | None
|
||||
|
||||
|
||||
class FakeDataLoader:
|
||||
def __init__(self, config: FakeDataLoaderConfig, seq_len: int, dp_world_size: int):
|
||||
@@ -84,6 +95,7 @@ class FakeDataLoader:
|
||||
total_seq_len = 0
|
||||
input_ids = []
|
||||
position_ids = []
|
||||
sequence_lengths = []
|
||||
|
||||
while total_seq_len < self.seq_len:
|
||||
# Generate reasonably long documents
|
||||
@@ -91,6 +103,7 @@ class FakeDataLoader:
|
||||
if seq_len_to_generate + total_seq_len > self.seq_len:
|
||||
seq_len_to_generate = self.seq_len - total_seq_len
|
||||
total_seq_len += seq_len_to_generate
|
||||
sequence_lengths.append(seq_len_to_generate)
|
||||
tmp_input_ids = torch.randint(0, 120000, (seq_len_to_generate,), generator=generator).long()
|
||||
tmp_position_ids = torch.arange(seq_len_to_generate).long()
|
||||
|
||||
@@ -114,12 +127,15 @@ class FakeDataLoader:
|
||||
"teacher_logprobs": None,
|
||||
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
|
||||
"env_names": ["fake"] * input_ids.shape[0],
|
||||
"sequence_lengths": sequence_lengths,
|
||||
"loss_mask": loss_mask.unsqueeze(0),
|
||||
"lora_num_tokens": lora_num_tokens,
|
||||
"routed_experts": None,
|
||||
"mm_kwargs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"training_mode": "rl",
|
||||
"run_id": None,
|
||||
"run_step": None,
|
||||
}
|
||||
|
||||
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
|
||||
@@ -142,12 +158,15 @@ class FakeDataLoader:
|
||||
"teacher_logprobs": None,
|
||||
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
|
||||
"env_names": ["fake"] * self.seq_len,
|
||||
"sequence_lengths": [self.seq_len],
|
||||
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
|
||||
"lora_num_tokens": lora_num_tokens,
|
||||
"routed_experts": None,
|
||||
"mm_kwargs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"training_mode": "rl",
|
||||
"run_id": None,
|
||||
"run_step": None,
|
||||
}
|
||||
|
||||
|
||||
@@ -162,6 +181,7 @@ class DataLoader:
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
config: TransportConfig,
|
||||
):
|
||||
self.world = get_world()
|
||||
@@ -173,6 +193,7 @@ class DataLoader:
|
||||
tokenizer=tokenizer,
|
||||
transport_config=config,
|
||||
pad_to_multiple_of=pad_to_multiple_of,
|
||||
bin_cost=bin_cost,
|
||||
start_step=start_step,
|
||||
)
|
||||
|
||||
@@ -236,6 +257,7 @@ class DataLoader:
|
||||
loss_mask=torch.tensor(micro_batch.loss_mask, dtype=torch.bool).unsqueeze(0),
|
||||
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
|
||||
env_names=micro_batch.env_names,
|
||||
sequence_lengths=micro_batch.sequence_lengths,
|
||||
lora_num_tokens=torch.tensor(micro_batch.lora_num_tokens, dtype=torch.int32),
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=torch.tensor(micro_batch.mm_token_type_ids, dtype=torch.long).unsqueeze(0)
|
||||
@@ -243,6 +265,8 @@ class DataLoader:
|
||||
else None,
|
||||
routed_experts=routed_experts,
|
||||
training_mode=micro_batch.training_mode,
|
||||
run_id=micro_batch.run_id,
|
||||
run_step=micro_batch.run_step,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
|
||||
from jaxtyping import Bool, Float, Int, jaxtyped
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -165,6 +165,35 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
|
||||
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
|
||||
|
||||
is_masked = abs_probs_diff > loss_config.ipo_threshold
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def opd_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
"""
|
||||
On-policy distillation loss: the default DPPO+KL math with the tau knobs
|
||||
@@ -240,7 +269,8 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
|
||||
- ``"opd"`` → ``opd_loss_fn`` (teacher KL as gradient signal, hardcoded
|
||||
DPPO + KL knobs)
|
||||
- ``"rl"`` → ``default_loss_fn(loss_config)`` for ``DefaultLossConfig``,
|
||||
or the imported function for ``CustomLossConfig``.
|
||||
``ipo_loss_fn(loss_config)`` for ``IPOLossConfig``, or the imported
|
||||
function for ``CustomLossConfig``.
|
||||
|
||||
``trainer.loss`` only affects the rl path - opd and sft are independent.
|
||||
"""
|
||||
@@ -250,6 +280,10 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return custom_fn(inputs, **kwargs)
|
||||
elif isinstance(loss_config, IPOLossConfig):
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return ipo_loss_fn(inputs, loss_config)
|
||||
else:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
|
||||
@@ -4,6 +4,7 @@ import threading
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Sequence
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
@@ -32,6 +33,7 @@ class BasePacker(ABC):
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
@@ -40,6 +42,7 @@ class BasePacker(ABC):
|
||||
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)
|
||||
self.sender: MicroBatchSender = setup_micro_batch_sender(
|
||||
@@ -84,9 +87,10 @@ class SinglePacker(BasePacker):
|
||||
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, start_step)
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
|
||||
assert self.multi_run_manager.max_runs == 1, "SinglePacker only supports one run"
|
||||
|
||||
def pack(self):
|
||||
@@ -110,7 +114,14 @@ class SinglePacker(BasePacker):
|
||||
num_train_workers=self.dp_world_size,
|
||||
idxs=[0] * len(batch.examples),
|
||||
num_loras=self.multi_run_manager.max_runs,
|
||||
bin_cost=self.bin_cost,
|
||||
)
|
||||
# The receiver always stamps run_idx from used_idxs (a key of idx_2_id).
|
||||
run_id = self.multi_run_manager.idx_2_id[batch.run_idx]
|
||||
for worker_batches in micro_batch_grid:
|
||||
for micro_batch in worker_batches:
|
||||
micro_batch.run_id = run_id
|
||||
micro_batch.run_step = batch.step
|
||||
|
||||
self.sender.send(micro_batch_grid)
|
||||
|
||||
@@ -123,9 +134,10 @@ class MultiPacker(BasePacker):
|
||||
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, start_step)
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, 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)
|
||||
@@ -300,10 +312,14 @@ class MultiPacker(BasePacker):
|
||||
# Group samples by run_idx - each microbatch must contain samples from only ONE run
|
||||
# because MultiLoRAGroupedExperts (MoE) only supports one adapter per microbatch
|
||||
samples_by_run: dict[int, list[TrainingSample]] = {}
|
||||
steps_by_run: dict[int, int] = {}
|
||||
per_run_stats: dict[int, tuple[int, int]] = {}
|
||||
for run_idx, sample, step in selected_samples:
|
||||
if run_idx not in samples_by_run:
|
||||
samples_by_run[run_idx] = []
|
||||
steps_by_run[run_idx] = step
|
||||
else:
|
||||
assert steps_by_run[run_idx] == step, "Micro batches for a run must come from a single run step"
|
||||
samples_by_run[run_idx].append(sample)
|
||||
|
||||
num_tokens = len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
@@ -327,9 +343,15 @@ class MultiPacker(BasePacker):
|
||||
num_train_workers=self.dp_world_size,
|
||||
idxs=[run_idx] * len(run_samples),
|
||||
num_loras=self.multi_run_manager.max_runs,
|
||||
bin_cost=self.bin_cost,
|
||||
)
|
||||
run_id = self.multi_run_manager.idx_2_id[run_idx]
|
||||
run_step = steps_by_run[run_idx]
|
||||
# Merge into combined grid
|
||||
for worker_idx, worker_batches in enumerate(run_micro_batch_grid):
|
||||
for micro_batch in worker_batches:
|
||||
micro_batch.run_id = run_id
|
||||
micro_batch.run_step = run_step
|
||||
all_micro_batches[worker_idx].extend(worker_batches)
|
||||
|
||||
self.sender.send(all_micro_batches)
|
||||
@@ -341,10 +363,15 @@ def setup_packer(
|
||||
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, start_step)
|
||||
return SinglePacker(
|
||||
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
|
||||
)
|
||||
else:
|
||||
return MultiPacker(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, start_step)
|
||||
return MultiPacker(
|
||||
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
|
||||
)
|
||||
|
||||
@@ -18,6 +18,9 @@ class DisabledTokenExporter:
|
||||
def export(self, *args: Any, **kwargs: Any) -> None:
|
||||
return
|
||||
|
||||
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
|
||||
return
|
||||
|
||||
def close(self) -> None:
|
||||
return
|
||||
|
||||
@@ -30,10 +33,10 @@ class TokenExporter:
|
||||
) -> None:
|
||||
self.rank = rank
|
||||
self.output_dir = output_dir / "token_exports"
|
||||
self._file: Any | None = None
|
||||
self._closed = False
|
||||
self._current_step: int | None = None
|
||||
self._sequences_this_step = 0
|
||||
self._initialized_files: set[tuple[str | None, int, int]] = set()
|
||||
self._sequences_by_file: dict[tuple[str | None, int, int], int] = {}
|
||||
self._pending_stable_dirs: dict[str | None, set[Path]] = {}
|
||||
atexit.register(self.close)
|
||||
|
||||
def export(
|
||||
@@ -42,17 +45,17 @@ class TokenExporter:
|
||||
micro_step: int,
|
||||
micro_batch: Mapping[str, Any],
|
||||
model_output: Mapping[str, Tensor],
|
||||
response_lengths: list[int],
|
||||
sequence_lengths: list[int],
|
||||
loss_config: Any,
|
||||
) -> None:
|
||||
if self._current_step != step:
|
||||
self._start_step(step)
|
||||
|
||||
columns = _export_columns(micro_batch, model_output, loss_config)
|
||||
_check_lengths(columns)
|
||||
run_id = micro_batch.get("run_id")
|
||||
export_step = micro_batch.get("run_step") if micro_batch.get("run_step") is not None else step
|
||||
file_key = (run_id, export_step, self.rank)
|
||||
|
||||
start = 0
|
||||
for micro_sequence_idx, length in enumerate(response_lengths):
|
||||
for micro_sequence_idx, length in enumerate(sequence_lengths):
|
||||
raw_end = start + length
|
||||
end = _trim_padding(columns, start, raw_end)
|
||||
if end > start and any(columns["loss_mask"][start:end]):
|
||||
@@ -60,54 +63,73 @@ class TokenExporter:
|
||||
{
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"step": step,
|
||||
"export_step": export_step,
|
||||
"rank": self.rank,
|
||||
"micro_step": micro_step,
|
||||
"micro_sequence_idx": micro_sequence_idx,
|
||||
"export_sequence_idx": self._sequences_this_step,
|
||||
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
|
||||
"run_id": run_id,
|
||||
"env_name": _first_non_empty(columns["env_names"][start:end]),
|
||||
"training_mode": str(micro_batch["training_mode"]),
|
||||
**_slice_columns(columns, start, end),
|
||||
}
|
||||
},
|
||||
run_id,
|
||||
export_step,
|
||||
)
|
||||
self._sequences_this_step += 1
|
||||
self._sequences_by_file[file_key] = self._sequences_by_file.get(file_key, 0) + 1
|
||||
start = raw_end
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
|
||||
def _start_step(self, step: int) -> None:
|
||||
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
|
||||
# A single run step's sequences can span multiple trainer steps (the packer
|
||||
# splits a run step across packs when it exceeds the token budget). Only
|
||||
# finalize a run's export dir once that run step is fully consumed — the same
|
||||
# `ready_to_update` signal that gates its optimizer step. ``run_id is None``
|
||||
# is single-run export, where a step never spans trainer steps, so mark it now.
|
||||
# The caller barriers first so a STABLE only lands after every rank flushed.
|
||||
ready_run_ids = ready_run_ids or set()
|
||||
for run_id in [rid for rid in self._pending_stable_dirs if rid is None or rid in ready_run_ids]:
|
||||
for stable_dir in self._pending_stable_dirs.pop(run_id):
|
||||
(stable_dir / "STABLE").touch()
|
||||
|
||||
def _export_dir(self, export_step: int, run_id: str | None) -> Path:
|
||||
if run_id is not None:
|
||||
return self.output_dir.parent / run_id / "token_exports" / f"step_{export_step}"
|
||||
return self.output_dir / f"step_{export_step}"
|
||||
|
||||
def _export_file(self, export_step: int, run_id: str | None) -> Path:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._current_step = step
|
||||
self._sequences_this_step = 0
|
||||
step_dir = self.output_dir / f"step_{step}"
|
||||
|
||||
step_dir = self._export_dir(export_step, run_id)
|
||||
try:
|
||||
step_dir.mkdir(parents=True, exist_ok=True)
|
||||
except FileExistsError:
|
||||
if not step_dir.is_dir():
|
||||
raise
|
||||
self._file = (step_dir / f"rank_{self.rank}.jsonl").open("w", encoding="utf-8")
|
||||
return step_dir / f"rank_{self.rank}.jsonl"
|
||||
|
||||
def _write(self, record: dict[str, Any]) -> None:
|
||||
def _write(self, record: dict[str, Any], run_id: str | None, export_step: int) -> None:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
if self._file is None:
|
||||
raise RuntimeError("Token exporter has no active step file")
|
||||
self._file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
|
||||
|
||||
file_key = (run_id, export_step, self.rank)
|
||||
mode = "a" if file_key in self._initialized_files else "w"
|
||||
export_file = self._export_file(export_step, run_id)
|
||||
with export_file.open(mode, encoding="utf-8") as file:
|
||||
file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
|
||||
self._initialized_files.add(file_key)
|
||||
self._pending_stable_dirs.setdefault(run_id, set()).add(export_file.parent)
|
||||
|
||||
|
||||
def setup_token_exporter(
|
||||
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
|
||||
) -> TokenExporter | DisabledTokenExporter:
|
||||
token_export_config = config.experimental.token_export
|
||||
if token_export_config is None:
|
||||
if not config.enable_token_export:
|
||||
return DisabledTokenExporter()
|
||||
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
|
||||
return DisabledTokenExporter()
|
||||
|
||||
@@ -46,6 +46,7 @@ from prime_rl.trainer.model import (
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims
|
||||
from prime_rl.trainer.perf import get_perf_counter
|
||||
from prime_rl.trainer.utils import (
|
||||
build_bin_cost,
|
||||
GarbageCollection,
|
||||
MemoryProfiler,
|
||||
Tensors,
|
||||
@@ -55,7 +56,6 @@ from prime_rl.trainer.utils import (
|
||||
get_ckpt_disk_metrics,
|
||||
setup_torch_distributed,
|
||||
print_benchmark,
|
||||
get_response_lengths,
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.trainer.runs import setup_multi_run_manager, Progress, get_multi_run_manager
|
||||
@@ -237,6 +237,7 @@ def train(config: TrainerConfig):
|
||||
config.model.seq_len,
|
||||
config.model.cp,
|
||||
tokenizer,
|
||||
build_bin_cost(model.config),
|
||||
config.rollout_transport,
|
||||
)
|
||||
|
||||
@@ -472,15 +473,15 @@ def train(config: TrainerConfig):
|
||||
)
|
||||
|
||||
# Compute loss
|
||||
response_lengths = get_response_lengths(position_ids)
|
||||
sequence_lengths = micro_batch["sequence_lengths"]
|
||||
loss, loss_tensors = compute_loss(
|
||||
trainer_logprobs=out["logprobs"].squeeze().split(response_lengths),
|
||||
inference_logprobs=inference_logprobs.squeeze().split(response_lengths),
|
||||
teacher_logprobs=teacher_logprobs.squeeze().split(response_lengths)
|
||||
trainer_logprobs=out["logprobs"].squeeze().split(sequence_lengths),
|
||||
inference_logprobs=inference_logprobs.squeeze().split(sequence_lengths),
|
||||
teacher_logprobs=teacher_logprobs.squeeze().split(sequence_lengths)
|
||||
if teacher_logprobs is not None
|
||||
else None,
|
||||
advantages=advantages.squeeze().split(response_lengths),
|
||||
loss_mask=loss_mask.squeeze().split(response_lengths),
|
||||
advantages=advantages.squeeze().split(sequence_lengths),
|
||||
loss_mask=loss_mask.squeeze().split(sequence_lengths),
|
||||
loss_fns=loss_fns,
|
||||
loss_scale=loss_scale,
|
||||
training_mode=micro_batch["training_mode"],
|
||||
@@ -512,7 +513,14 @@ def train(config: TrainerConfig):
|
||||
for env_name, indices in env_to_indices.items():
|
||||
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
|
||||
|
||||
token_exporter.export(progress.step, micro_step, micro_batch, out, response_lengths, config.loss)
|
||||
token_exporter.export(
|
||||
progress.step,
|
||||
micro_step,
|
||||
micro_batch,
|
||||
out,
|
||||
sequence_lengths,
|
||||
config.loss,
|
||||
)
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
load_balance_stats = get_load_balance_stats(model)
|
||||
@@ -534,6 +542,15 @@ def train(config: TrainerConfig):
|
||||
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
|
||||
logger.debug(micro_step_message)
|
||||
|
||||
if config.enable_token_export:
|
||||
dist.barrier()
|
||||
ready_run_ids = {
|
||||
multi_run_manager.idx_2_id[idx]
|
||||
for idx in multi_run_manager.ready_to_update_idxs
|
||||
if idx in multi_run_manager.idx_2_id
|
||||
}
|
||||
token_exporter.mark_stable(ready_run_ids)
|
||||
|
||||
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
|
||||
# across dp_cp so the final gradient is the true per-token mean over the global batch.
|
||||
for param in model.parameters():
|
||||
|
||||
+238
-37
@@ -1,10 +1,12 @@
|
||||
import gc
|
||||
import heapq
|
||||
import json
|
||||
import pickle
|
||||
import shutil
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from collections.abc import Callable, Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -28,6 +30,241 @@ from prime_rl.utils.utils import format_num, format_time, get_step_path
|
||||
DEFAULT_TIMEOUT = timedelta(seconds=600)
|
||||
|
||||
|
||||
def _text_config(model_config: Any) -> Any:
|
||||
"""Unwrap a multimodal model's text config, else return the config unchanged."""
|
||||
return getattr(model_config, "text_config", model_config)
|
||||
|
||||
|
||||
def _is_mla(config: Any) -> bool:
|
||||
return bool(getattr(config, "multi_latent_attention", False) or hasattr(config, "q_lora_rank"))
|
||||
|
||||
|
||||
def _kv_channels(config: Any) -> int:
|
||||
return getattr(config, "kv_channels", getattr(config, "head_dim", config.hidden_size // config.num_attention_heads))
|
||||
|
||||
|
||||
def _qkv_projection_flops_per_token(config: Any) -> int:
|
||||
"""Linear-in-seqlen FLOPs of the Q/K/V projections (per token)."""
|
||||
hidden_size = config.hidden_size
|
||||
num_attention_heads = config.num_attention_heads
|
||||
kv_channels = _kv_channels(config)
|
||||
is_mla = _is_mla(config)
|
||||
qk_head_dim = getattr(config, "qk_head_dim", 0)
|
||||
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
|
||||
|
||||
if is_mla and getattr(config, "q_lora_rank", None) is not None:
|
||||
q_flops = 2 * config.q_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim))
|
||||
else:
|
||||
q_head_dim = (qk_head_dim + qk_pos_emb_head_dim) if is_mla else kv_channels
|
||||
q_flops = 2 * hidden_size * num_attention_heads * q_head_dim
|
||||
|
||||
if is_mla and getattr(config, "kv_lora_rank", None) is not None:
|
||||
v_head_dim = getattr(config, "v_head_dim", 0)
|
||||
kv_flops = 2 * (
|
||||
config.kv_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + v_head_dim))
|
||||
+ hidden_size * qk_pos_emb_head_dim
|
||||
)
|
||||
else:
|
||||
num_query_groups = getattr(
|
||||
config, "num_query_groups", getattr(config, "num_key_value_heads", num_attention_heads)
|
||||
)
|
||||
kv_flops = 4 * hidden_size * num_query_groups * kv_channels
|
||||
return q_flops + kv_flops
|
||||
|
||||
|
||||
def _attention_flops_per_token_squared(config: Any) -> int:
|
||||
"""Quadratic-in-seqlen FLOPs of the attention scores and values (per token^2)."""
|
||||
num_attention_heads = config.num_attention_heads
|
||||
kv_channels = _kv_channels(config)
|
||||
if _is_mla(config):
|
||||
qk_head_dim = getattr(config, "qk_head_dim", 0)
|
||||
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
|
||||
v_head_dim = getattr(config, "v_head_dim", kv_channels)
|
||||
return num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim) + num_attention_heads * v_head_dim
|
||||
return 2 * num_attention_heads * kv_channels
|
||||
|
||||
|
||||
def _ffn_flops_per_token(hidden_size: int, ffn_hidden_size: int) -> int:
|
||||
return 6 * hidden_size * ffn_hidden_size
|
||||
|
||||
|
||||
def _dense_ffn_hidden_size(config: Any) -> int:
|
||||
return getattr(
|
||||
config, "ffn_hidden_size", getattr(config, "intermediate_size", getattr(config, "moe_intermediate_size", 0))
|
||||
)
|
||||
|
||||
|
||||
def _moe_ffn_hidden_size(config: Any) -> int:
|
||||
"""Effective FFN width of an MoE layer: routed experts (topk) plus shared experts."""
|
||||
dense_ffn = _dense_ffn_hidden_size(config)
|
||||
routed_topk = getattr(config, "moe_router_topk", getattr(config, "num_experts_per_tok", 1))
|
||||
moe_ffn = getattr(config, "moe_ffn_hidden_size", getattr(config, "moe_intermediate_size", dense_ffn))
|
||||
return moe_ffn * routed_topk + (getattr(config, "moe_shared_expert_intermediate_size", None) or 0)
|
||||
|
||||
|
||||
def _count_dense_and_moe_layers(config: Any) -> tuple[int, int]:
|
||||
"""Split the model's layers into (dense, moe) counts."""
|
||||
num_experts = getattr(config, "num_experts", getattr(config, "n_routed_experts", None))
|
||||
if num_experts is None:
|
||||
return config.num_hidden_layers, 0
|
||||
|
||||
moe_layer_freq = getattr(config, "moe_layer_freq", None)
|
||||
if isinstance(moe_layer_freq, list):
|
||||
num_dense = sum(1 for freq in moe_layer_freq if freq == 0)
|
||||
num_moe = sum(1 for freq in moe_layer_freq if freq > 0)
|
||||
elif isinstance(moe_layer_freq, int):
|
||||
num_dense = sum(1 for i in range(config.num_hidden_layers) if i % moe_layer_freq != 0)
|
||||
num_moe = config.num_hidden_layers - num_dense
|
||||
elif getattr(config, "first_k_dense_replace", None) is not None:
|
||||
num_dense = config.first_k_dense_replace
|
||||
num_moe = config.num_hidden_layers - num_dense
|
||||
else:
|
||||
num_dense = 0
|
||||
num_moe = config.num_hidden_layers
|
||||
return num_dense, num_moe
|
||||
|
||||
|
||||
def _packing_cost_coeffs(config: Any) -> tuple[int, int]:
|
||||
"""Return the (linear, quadratic) coefficients of the per-sequence forward FLOPs."""
|
||||
hidden_size = config.hidden_size
|
||||
num_dense_layers, num_moe_layers = _count_dense_and_moe_layers(config)
|
||||
qkv_per_token = _qkv_projection_flops_per_token(config)
|
||||
attn_per_token_squared = _attention_flops_per_token_squared(config)
|
||||
|
||||
def layer_linear(ffn_hidden_size: int) -> int:
|
||||
return qkv_per_token + 2 * hidden_size * hidden_size + _ffn_flops_per_token(hidden_size, ffn_hidden_size)
|
||||
|
||||
linear = (
|
||||
num_dense_layers * layer_linear(_dense_ffn_hidden_size(config))
|
||||
+ num_moe_layers * layer_linear(_moe_ffn_hidden_size(config))
|
||||
+ 2 * hidden_size * config.vocab_size
|
||||
)
|
||||
quadratic = (num_dense_layers + num_moe_layers) * attn_per_token_squared
|
||||
return linear, quadratic
|
||||
|
||||
|
||||
def build_bin_cost(model_config: Any | None) -> Callable[[Sequence[int]], int]:
|
||||
"""Build a closure scoring a packed bin by estimated forward compute.
|
||||
|
||||
With ``model_config=None`` the linear/quadratic coefficients are ``(1, 0)``, so
|
||||
the cost reduces to the token count and balancing falls back to sequence length.
|
||||
"""
|
||||
if model_config is None:
|
||||
linear, quadratic = 1, 0
|
||||
else:
|
||||
linear, quadratic = _packing_cost_coeffs(_text_config(model_config))
|
||||
|
||||
def bin_cost(seqlens: Sequence[int]) -> int:
|
||||
return linear * sum(seqlens) + quadratic * sum(n * n for n in seqlens)
|
||||
|
||||
return bin_cost
|
||||
|
||||
|
||||
@dataclass
|
||||
class _WeightedSet:
|
||||
total: int = 0
|
||||
items: list[int] = field(default_factory=list)
|
||||
|
||||
def add(self, idx: int, weight: int) -> None:
|
||||
self.items.append(idx)
|
||||
self.total += weight
|
||||
|
||||
def merge(self, other: "_WeightedSet") -> None:
|
||||
self.items.extend(other.items)
|
||||
self.total += other.total
|
||||
|
||||
def __lt__(self, other: "_WeightedSet") -> bool:
|
||||
if self.total != other.total:
|
||||
return self.total < other.total
|
||||
return self.items < other.items
|
||||
|
||||
|
||||
class _KKState:
|
||||
def __init__(self, items: list[tuple[int, int]], k: int):
|
||||
self.sets = [_WeightedSet() for _ in range(k)]
|
||||
for set_idx, (idx, weight) in enumerate(items):
|
||||
self.sets[set_idx].add(idx, weight)
|
||||
self.sets.sort(reverse=True)
|
||||
|
||||
@property
|
||||
def spread(self) -> int:
|
||||
return self.sets[0].total - self.sets[-1].total
|
||||
|
||||
def merge(self, other: "_KKState") -> None:
|
||||
k = len(self.sets)
|
||||
for i in range(k):
|
||||
self.sets[i].merge(other.sets[k - 1 - i])
|
||||
self.sets.sort(reverse=True)
|
||||
|
||||
def partitions(self) -> list[list[int]]:
|
||||
return [sorted(weighted_set.items) for weighted_set in self.sets]
|
||||
|
||||
def __lt__(self, other: "_KKState") -> bool:
|
||||
if self.spread != other.spread:
|
||||
return self.spread > other.spread
|
||||
return self.sets[0] > other.sets[0]
|
||||
|
||||
|
||||
def _karmarkar_karp(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
|
||||
assert len(weights) >= num_partitions
|
||||
assert len(weights) % num_partitions == 0
|
||||
weighted_indices = sorted((weight, idx) for idx, weight in enumerate(weights))
|
||||
states: list[_KKState] = []
|
||||
for offset in range(0, len(weighted_indices), num_partitions):
|
||||
items = [(idx, weight) for weight, idx in weighted_indices[offset : offset + num_partitions]]
|
||||
heapq.heappush(states, _KKState(items, num_partitions))
|
||||
|
||||
while len(states) > 1:
|
||||
state = heapq.heappop(states)
|
||||
state.merge(heapq.heappop(states))
|
||||
heapq.heappush(states, state)
|
||||
|
||||
return states[0].partitions()
|
||||
|
||||
|
||||
def _partition_loads(weights: Sequence[int], partitions: list[list[int]]) -> list[int]:
|
||||
return [sum(weights[i] for i in partition) for partition in partitions]
|
||||
|
||||
|
||||
def _refine_by_swapping(weights: Sequence[int], partitions: list[list[int]]) -> list[list[int]]:
|
||||
partitions = [list(partition) for partition in partitions]
|
||||
loads = _partition_loads(weights, partitions)
|
||||
|
||||
while True:
|
||||
best_swap = None
|
||||
best_score = (max(loads), max(loads) - min(loads))
|
||||
for left_rank in range(len(partitions)):
|
||||
for right_rank in range(left_rank + 1, len(partitions)):
|
||||
for left_pos, left_idx in enumerate(partitions[left_rank]):
|
||||
for right_pos, right_idx in enumerate(partitions[right_rank]):
|
||||
new_left = loads[left_rank] - weights[left_idx] + weights[right_idx]
|
||||
new_right = loads[right_rank] - weights[right_idx] + weights[left_idx]
|
||||
new_loads = list(loads)
|
||||
new_loads[left_rank] = new_left
|
||||
new_loads[right_rank] = new_right
|
||||
score = (max(new_loads), max(new_loads) - min(new_loads))
|
||||
if score < best_score:
|
||||
best_score = score
|
||||
best_swap = (left_rank, right_rank, left_pos, right_pos, new_loads)
|
||||
if best_swap is None:
|
||||
return partitions
|
||||
|
||||
left_rank, right_rank, left_pos, right_pos, loads = best_swap
|
||||
partitions[left_rank][left_pos], partitions[right_rank][right_pos] = (
|
||||
partitions[right_rank][right_pos],
|
||||
partitions[left_rank][left_pos],
|
||||
)
|
||||
|
||||
|
||||
def balanced_partition(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
|
||||
"""Partition item indices into ``num_partitions`` groups of near-equal total weight.
|
||||
|
||||
Requires ``len(weights)`` to be a positive multiple of ``num_partitions``.
|
||||
"""
|
||||
partitions = _karmarkar_karp(weights, num_partitions)
|
||||
return _refine_by_swapping(weights, partitions)
|
||||
|
||||
|
||||
class GarbageCollection:
|
||||
"""Controls Python garbage collection to avoid stragglers in distributed training.
|
||||
|
||||
@@ -143,42 +380,6 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
|
||||
dist.init_process_group(backend=backend, timeout=timeout, device_id=device_id)
|
||||
|
||||
|
||||
def get_response_lengths(position_ids: torch.Tensor) -> list[int]:
|
||||
"""
|
||||
Compute lengths of concatenated sequences from position_ids.
|
||||
|
||||
Each sequence starts at 0 and increments. When position_ids resets to 0,
|
||||
it indicates the start of a new sequence. Trailing zeros (padding) are
|
||||
counted as part of the last sequence.
|
||||
|
||||
Args:
|
||||
position_ids: Tensor of shape [total_seqlen]
|
||||
|
||||
Returns:
|
||||
List of sequence lengths
|
||||
"""
|
||||
position_ids = position_ids.flatten()
|
||||
|
||||
boundaries = [0] # Start of first sequence
|
||||
|
||||
for i in range(1, len(position_ids)):
|
||||
if position_ids[i] == 0 and position_ids[i - 1] != 0:
|
||||
# This is a potential sequence boundary (0 after non-zero)
|
||||
# But only if the next element is 1 (indicating a new incrementing sequence)
|
||||
# Otherwise, this 0 is padding and belongs to current sequence
|
||||
if i + 1 < len(position_ids) and position_ids[i + 1] == 1:
|
||||
boundaries.append(i)
|
||||
|
||||
# Calculate lengths based on boundaries
|
||||
lengths = []
|
||||
for i in range(len(boundaries)):
|
||||
start = boundaries[i]
|
||||
end = boundaries[i + 1] if i + 1 < len(boundaries) else len(position_ids)
|
||||
lengths.append(end - start)
|
||||
|
||||
return lengths
|
||||
|
||||
|
||||
def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrainedTokenizer):
|
||||
"""
|
||||
Visualize the loss mask of a tokenized sample using rich.
|
||||
|
||||
@@ -8,7 +8,12 @@ from prime_rl.transport.filesystem import (
|
||||
FileSystemTrainingBatchReceiver,
|
||||
FileSystemTrainingBatchSender,
|
||||
)
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingBatch, TrainingSample
|
||||
from prime_rl.transport.types import (
|
||||
MicroBatch,
|
||||
RoutedExperts,
|
||||
TrainingBatch,
|
||||
TrainingSample,
|
||||
)
|
||||
from prime_rl.transport.zmq import (
|
||||
ZMQMicroBatchReceiver,
|
||||
ZMQMicroBatchSender,
|
||||
|
||||
@@ -76,6 +76,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
position_ids: list[int]
|
||||
temperatures: list[float] # Per-token temperatures used during generation
|
||||
env_names: list[str]
|
||||
sequence_lengths: list[int]
|
||||
teacher_logprobs: list[float] | None = None
|
||||
lora_num_tokens: list[int] | None = None
|
||||
routed_experts: RoutedExperts | None = None
|
||||
@@ -89,3 +90,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
# sft → sft loss). All samples packed into a micro batch share the same mode.
|
||||
training_mode: TrainingMode = "rl"
|
||||
rewards: list[float] | None = None
|
||||
|
||||
# Packer-derived metadata used for run-local token exports.
|
||||
run_id: str | None = None
|
||||
run_step: int | None = None
|
||||
|
||||
@@ -16,8 +16,8 @@ import verifiers as vf
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
|
||||
|
||||
@@ -112,7 +112,7 @@ class PrimeMonitor(Monitor):
|
||||
config: PrimeMonitorConfig | None,
|
||||
output_dir: Path | None = None,
|
||||
tokenizer: PreTrainedTokenizer | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
run_config: OrchestratorConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
):
|
||||
self.config = config
|
||||
@@ -185,7 +185,7 @@ class PrimeMonitor(Monitor):
|
||||
if config.log_extras.distributions:
|
||||
self.last_log_distributions_step = -1
|
||||
|
||||
def _register_run(self, config: PrimeMonitorConfig, run_config: BaseConfig | None) -> str | None:
|
||||
def _register_run(self, config: PrimeMonitorConfig, run_config: OrchestratorConfig | None) -> str | None:
|
||||
"""Register an external run with the platform. Returns run_id on success, None on failure."""
|
||||
prime_config = None
|
||||
team_id = config.team_id
|
||||
@@ -197,22 +197,23 @@ class PrimeMonitor(Monitor):
|
||||
if frontend_url is None:
|
||||
frontend_url = prime_config.frontend_url
|
||||
|
||||
model = getattr(run_config, "model", None) if run_config else None
|
||||
environments = getattr(run_config, "env", None) if run_config else None
|
||||
wandb = getattr(run_config, "wandb", None) if run_config else None
|
||||
|
||||
payload: dict = {
|
||||
"base_model": model.name if model else "unknown",
|
||||
"max_steps": getattr(run_config, "max_steps", None) or 0,
|
||||
payload: dict[str, Any] = {
|
||||
"base_model": run_config.student.model.name if run_config else "unknown",
|
||||
"max_steps": (run_config.max_steps if run_config else None) or 0,
|
||||
}
|
||||
if run_config:
|
||||
if run_config.batch_size is not None:
|
||||
payload["batch_size"] = run_config.batch_size
|
||||
payload["rollouts_per_example"] = run_config.group_size
|
||||
payload["seq_len"] = run_config.seq_len
|
||||
payload["environments"] = [{"id": env.id} for env in run_config.train.env]
|
||||
payload["run_config"] = run_config.model_dump(exclude_none=True, mode="json")
|
||||
if run_config.wandb:
|
||||
payload["wandb_project"] = run_config.wandb.project
|
||||
if config.run_name:
|
||||
payload["name"] = config.run_name
|
||||
if team_id:
|
||||
payload["team_id"] = team_id
|
||||
if environments:
|
||||
payload["environments"] = [{"id": env.id} for env in environments if hasattr(env, "id")]
|
||||
if wandb and getattr(wandb, "project", None):
|
||||
payload["wandb_project"] = wandb.project
|
||||
|
||||
try:
|
||||
response = httpx.post(
|
||||
|
||||
@@ -29,6 +29,7 @@ VLM_REGISTRY: dict[str, VLMModelInfo] = {
|
||||
"qwen3_5": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_5_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_vl_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"gemma4": VLMModelInfo(vision_encoder_attr="model.vision_tower", language_model_attr="model.language_model"),
|
||||
}
|
||||
|
||||
# Text-only default
|
||||
@@ -86,6 +87,16 @@ def is_vlm_architecture(model_config: PretrainedConfig) -> bool:
|
||||
return _get_model_info_from_config(model_config) is not None
|
||||
|
||||
|
||||
def get_final_logit_softcapping(model_config: PretrainedConfig) -> float | None:
|
||||
"""Read ``final_logit_softcapping`` from the text config.
|
||||
|
||||
For composite VLM configs (e.g. Gemma) the value lives under ``text_config``;
|
||||
``get_text_config()`` returns that for VLMs and the config itself for text-only
|
||||
models, so a plain top-level ``getattr`` would miss it and silently drop softcapping.
|
||||
"""
|
||||
return getattr(model_config.get_text_config(), "final_logit_softcapping", None)
|
||||
|
||||
|
||||
def get_layer_prefix(model_config: PretrainedConfig, override: str | None = None) -> str:
|
||||
"""Return the weight key prefix for language model layers.
|
||||
|
||||
|
||||
@@ -14,12 +14,17 @@ import asyncio
|
||||
|
||||
import numpy as np
|
||||
import pybase64
|
||||
from vllm.entrypoints.openai.engine.protocol import UsageInfo
|
||||
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse, GenerateResponseChoice
|
||||
|
||||
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
|
||||
from prime_rl.inference.vllm.serving_tokens import (
|
||||
PrimeRlGenerateResponse,
|
||||
PrimeRlGenerateResponseChoice,
|
||||
PrimeRlServingTokens,
|
||||
_build_usage,
|
||||
_client_set_max_tokens,
|
||||
_FinalOutputCapture,
|
||||
_GenerateRoutedExpertsCapture,
|
||||
)
|
||||
|
||||
@@ -105,6 +110,153 @@ def test_client_set_max_tokens_detects_unset():
|
||||
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(body_without_sp))) is False
|
||||
|
||||
|
||||
class _FakeOutput:
|
||||
def __init__(self, token_ids):
|
||||
self.token_ids = token_ids
|
||||
|
||||
|
||||
class _FakeRequestOutput:
|
||||
"""Minimal stand-in for ``vllm.outputs.RequestOutput``.
|
||||
|
||||
``_build_usage`` only touches four attributes; constructing a real
|
||||
``RequestOutput`` would require a full ``CompletionOutput`` graph and
|
||||
isn't worth it for a serialization-shape test.
|
||||
"""
|
||||
|
||||
def __init__(self, prompt_token_ids, output_token_ids_list, num_cached_tokens=0, encoder_prompt_token_ids=None):
|
||||
self.prompt_token_ids = prompt_token_ids
|
||||
self.encoder_prompt_token_ids = encoder_prompt_token_ids
|
||||
self.outputs = [_FakeOutput(t) for t in output_token_ids_list]
|
||||
self.num_cached_tokens = num_cached_tokens
|
||||
|
||||
|
||||
def test_prime_rl_generate_response_serializes_usage_block():
|
||||
# Regression for prime-rl PR #2408: parent ``GenerateResponse`` doesn't
|
||||
# declare ``usage``, so the field must be declared on the subclass for
|
||||
# Pydantic to emit it in JSON. Without this the router can't extract
|
||||
# per-run token / cache counts for billing.
|
||||
response = PrimeRlGenerateResponse(
|
||||
request_id="req-1",
|
||||
choices=[PrimeRlGenerateResponseChoice(index=0, token_ids=[1, 2, 3])],
|
||||
usage=UsageInfo(prompt_tokens=4, completion_tokens=3, total_tokens=7),
|
||||
)
|
||||
payload = response.model_dump(mode="json")
|
||||
assert payload["usage"] == {
|
||||
"prompt_tokens": 4,
|
||||
"completion_tokens": 3,
|
||||
"total_tokens": 7,
|
||||
"prompt_tokens_details": None,
|
||||
}
|
||||
|
||||
|
||||
def test_build_usage_sums_prompt_and_completion_tokens():
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4, 5],
|
||||
output_token_ids_list=[[10, 11], [20, 21, 22]],
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens == 5
|
||||
assert usage.completion_tokens == 5 # 2 + 3
|
||||
assert usage.total_tokens == 10
|
||||
assert usage.prompt_tokens_details is None
|
||||
|
||||
|
||||
def test_build_usage_includes_encoder_prompt_tokens():
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
output_token_ids_list=[[10]],
|
||||
encoder_prompt_token_ids=[100, 101],
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens == 5 # 3 + 2
|
||||
assert usage.total_tokens == 6
|
||||
|
||||
|
||||
def test_build_usage_reports_cached_tokens_unconditionally():
|
||||
# Unlike upstream's ``enable_prompt_tokens_details`` gate, prime-rl always
|
||||
# surfaces cached tokens — the cache-discount billing pipeline needs them.
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4],
|
||||
output_token_ids_list=[[10, 11]],
|
||||
num_cached_tokens=3,
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens_details is not None
|
||||
assert usage.prompt_tokens_details.cached_tokens == 3
|
||||
|
||||
|
||||
def test_build_usage_skips_cached_tokens_when_zero():
|
||||
# Don't emit a details block with cached=0, which would be misleading
|
||||
# to the router's billing extractor.
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4],
|
||||
output_token_ids_list=[[10, 11]],
|
||||
num_cached_tokens=0,
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens_details is None
|
||||
|
||||
|
||||
def test_final_output_capture_records_last_item():
|
||||
async def _gen():
|
||||
for r in [
|
||||
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2, 3], output_token_ids_list=[[1, 2, 3]]),
|
||||
]:
|
||||
yield r
|
||||
|
||||
async def _drain(capture):
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
capture = _FinalOutputCapture(_gen())
|
||||
asyncio.run(_drain(capture))
|
||||
assert capture.final_res is not None
|
||||
assert capture.final_res.prompt_token_ids == [1, 2, 3]
|
||||
|
||||
|
||||
def test_final_output_capture_works_over_async_def_aiter_source():
|
||||
# ``_GenerateRoutedExpertsCapture`` exposes the async-iterator protocol
|
||||
# via ``async def __aiter__`` (an async generator function) and has no
|
||||
# ``__anext__``. The wrapper must drive it through ``async for`` rather
|
||||
# than poking ``__anext__`` directly, or routed-experts runs raise
|
||||
# AttributeError before the response is built.
|
||||
|
||||
class _AsyncGenAiterSource:
|
||||
def __init__(self, items):
|
||||
self._items = items
|
||||
|
||||
async def __aiter__(self):
|
||||
for item in self._items:
|
||||
yield item
|
||||
|
||||
items = [
|
||||
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
|
||||
]
|
||||
capture = _FinalOutputCapture(_AsyncGenAiterSource(items))
|
||||
|
||||
async def _drain():
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
asyncio.run(_drain())
|
||||
assert capture.final_res is not None
|
||||
assert capture.final_res.prompt_token_ids == [1, 2]
|
||||
|
||||
|
||||
def test_final_output_capture_handles_empty_stream():
|
||||
capture = _FinalOutputCapture(_empty_request_outputs())
|
||||
|
||||
async def _drain():
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
asyncio.run(_drain())
|
||||
assert capture.final_res is None
|
||||
|
||||
|
||||
def test_client_set_max_tokens_assumes_set_when_body_unreadable():
|
||||
# No raw_request → can't tell, don't override.
|
||||
assert asyncio.run(_client_set_max_tokens(None)) is True
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import math
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
@@ -6,8 +5,8 @@ import pytest
|
||||
from prime_rl.configs.orchestrator import (
|
||||
CustomAdvantageConfig,
|
||||
DefaultAdvantageConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
LinearLengthPenaltyConfig,
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.advantage import (
|
||||
AdvantageInputs,
|
||||
@@ -16,48 +15,29 @@ from prime_rl.orchestrator.advantage import (
|
||||
default_advantage_fn,
|
||||
setup_advantage_fn,
|
||||
)
|
||||
from prime_rl.orchestrator.envs import Env, TrainEnv
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
|
||||
|
||||
def _make_rollout(
|
||||
reward: float,
|
||||
completion_len: int = 0,
|
||||
num_turns: int = 1,
|
||||
env_name: str = "test",
|
||||
example_id: int = 0,
|
||||
) -> dict:
|
||||
"""Create a minimal rollout dict for advantage testing.
|
||||
|
||||
`completion_len` tokens are split across `num_turns` trajectory steps.
|
||||
"""
|
||||
per_turn, rem = divmod(completion_len, max(num_turns, 1))
|
||||
trajectory = [
|
||||
{"tokens": {"prompt_ids": [0], "completion_ids": list(range(per_turn + (rem if i == 0 else 0)))}}
|
||||
for i in range(num_turns)
|
||||
]
|
||||
def _make_rollout(reward: float, completion_len: int = 0) -> dict:
|
||||
"""Minimal single-turn rollout dict with ``completion_len`` completion tokens."""
|
||||
return {
|
||||
"reward": reward,
|
||||
"trajectory": trajectory,
|
||||
"env_name": env_name,
|
||||
"example_id": example_id,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(completion_len))}}],
|
||||
"env_name": "test",
|
||||
"example_id": 0,
|
||||
}
|
||||
|
||||
|
||||
def _make_group(rewards, completion_lengths=None, num_turns=None) -> AdvantageInputs:
|
||||
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths/turns."""
|
||||
def _make_group(rewards, completion_lengths=None) -> AdvantageInputs:
|
||||
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths."""
|
||||
rollouts = []
|
||||
for i, reward in enumerate(rewards):
|
||||
cl = int(completion_lengths[i]) if completion_lengths is not None else 0
|
||||
nt = int(num_turns[i]) if num_turns is not None else 1
|
||||
rollouts.append(_make_rollout(float(reward), cl, nt))
|
||||
rollouts.append(_make_rollout(float(reward), cl))
|
||||
return AdvantageInputs(rollouts=rollouts)
|
||||
|
||||
|
||||
# Helper aliases for readability — completion-only and tool-only token shaping.
|
||||
_TOKENS_COMPLETION = TokensLengthPenaltyConfig(completion_weight=1.0, tool_response_weight=0.0)
|
||||
_TOKENS_TOOL_ONLY = TokensLengthPenaltyConfig(completion_weight=0.0, tool_response_weight=1.0)
|
||||
|
||||
|
||||
def test_default_advantage_fn_simple_mean():
|
||||
inputs = _make_group(rewards=[1.0, 0.5, 0.8], completion_lengths=[10, 12, 8])
|
||||
result = default_advantage_fn(inputs)
|
||||
@@ -66,187 +46,141 @@ def test_default_advantage_fn_simple_mean():
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_mixed_group():
|
||||
"""Mixed group: reward shaping preserves zero-mean, shorter correct gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_linear_length_penalty_scales_by_pass_rate():
|
||||
"""Linear penalty subtracts coef * pass_rate * (completion tokens / max_seq_len), then mean-centers.
|
||||
|
||||
# mean_correct_len = (10+30+20)/3 = 20
|
||||
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
|
||||
# shaped_rewards = R * (1 + bonus * correct_mask) = [1.5, 1, 0, 1]
|
||||
# baseline = mean(shaped_rewards) = 0.875
|
||||
# A = shaped_rewards - baseline = [0.625, 0.125, -0.875, 0.125]
|
||||
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
|
||||
``pass_rate`` is the group's mean reward, so a half-solved group scales the penalty by 0.5.
|
||||
"""
|
||||
rewards = [1.0, 1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
|
||||
result = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=2.0), max_seq_len=100)
|
||||
|
||||
# Zero-mean per group
|
||||
pass_rate = sum(rewards) / len(rewards) # 0.5
|
||||
penalized = [r - 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
# Zero-mean per group, and within each reward tier shorter output → higher advantage
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
# All correct rollouts have positive advantage
|
||||
for rollout, adv in zip(inputs.rollouts, result.advantages):
|
||||
if rollout["reward"] >= 1.0:
|
||||
assert adv > 0
|
||||
assert result.advantages[0] > result.advantages[1]
|
||||
assert result.advantages[2] > result.advantages[3]
|
||||
|
||||
|
||||
def test_efficiency_all_correct_group():
|
||||
"""All-correct group: zero-mean, shorter gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 1.0], completion_lengths=[10, 20, 40])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
|
||||
# mean_len = 70/3 ≈ 23.33
|
||||
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
|
||||
# shaped_rewards = [1+4/7, 1+1/7, 1] = [11/7, 8/7, 1]
|
||||
shaped = [11.0 / 7, 8.0 / 7, 1.0]
|
||||
mean_shaped = sum(shaped) / len(shaped)
|
||||
expected = [s - mean_shaped for s in shaped]
|
||||
assert result.advantages == pytest.approx(expected, abs=1e-6)
|
||||
|
||||
# Zero-mean
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
# Shortest has highest advantage
|
||||
assert result.advantages[0] > result.advantages[1] > result.advantages[2]
|
||||
def test_linear_length_penalty_zero_pass_rate_disables_penalty():
|
||||
"""A never-solved group (mean reward 0) gets no length pressure — falls back to plain GRPO."""
|
||||
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 50, 200])
|
||||
penalized = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=5.0), max_seq_len=100)
|
||||
plain = default_advantage_fn(inputs)
|
||||
assert penalized.advantages == pytest.approx(plain.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_all_zero_rewards():
|
||||
"""When all rewards are 0, no length shaping — falls back to standard GRPO."""
|
||||
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 20, 15])
|
||||
result_with = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
result_without = default_advantage_fn(inputs)
|
||||
def test_linear_length_penalty_gate_by_correctness():
|
||||
"""Gating scales each rollout's penalty by its reward, so reward-0 rollouts are untouched."""
|
||||
rewards = [1.0, 1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
|
||||
cfg = LinearLengthPenaltyConfig(coef=2.0, gate_by_correctness=True)
|
||||
result = default_advantage_fn(inputs, length_penalty=cfg, max_seq_len=100)
|
||||
|
||||
assert result_with.advantages == pytest.approx(result_without.advantages, abs=1e-6)
|
||||
pass_rate = sum(rewards) / len(rewards) # 0.5
|
||||
penalized = [r - r * 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_single_correct():
|
||||
"""Single correct rollout: bonus=0 (at its own mean), same as standard GRPO."""
|
||||
inputs = _make_group(rewards=[1.0, 0.0, 0.0, 0.0], completion_lengths=[100, 50, 200, 150])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_setup_advantage_fn_threads_max_seq_len():
|
||||
"""``setup_advantage_fn`` threads ``max_seq_len`` into the linear penalty denominator."""
|
||||
rewards = [1.0, 1.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30])
|
||||
fn = setup_advantage_fn(DefaultAdvantageConfig(length_penalty=LinearLengthPenaltyConfig(coef=1.0)), max_seq_len=100)
|
||||
result = fn(inputs)
|
||||
|
||||
assert result.advantages == pytest.approx([0.75, -0.25, -0.25, -0.25], abs=1e-6)
|
||||
pass_rate = sum(rewards) / len(rewards) # 1.0
|
||||
penalized = [1.0 - 1.0 * pass_rate * (length / 100) for length in (10, 30)]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_shorter_correct_higher_advantage():
|
||||
"""Among correct rollouts in a mixed group, shorter always gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 1.0, 0.0, 0.0], completion_lengths=[50, 100, 200, 80, 120])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_train_env_threads_max_seq_len_into_advantage_fn(monkeypatch):
|
||||
"""TrainEnv-built advantage funcs use orchestrator seq_len for length penalties."""
|
||||
|
||||
advs = result.advantages
|
||||
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 fake_env_init(self, config):
|
||||
self.config = config
|
||||
self._env = None
|
||||
self._env_client = None
|
||||
self._env_server_process = None
|
||||
|
||||
|
||||
def test_efficiency_zero_mean_per_group():
|
||||
"""Reward shaping preserves zero-mean advantages within each group."""
|
||||
mixed = default_advantage_fn(
|
||||
_make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20]),
|
||||
length_penalty=_TOKENS_COMPLETION,
|
||||
)
|
||||
all_correct = default_advantage_fn(
|
||||
_make_group(rewards=[1.0, 1.0, 1.0, 1.0], completion_lengths=[10, 20, 40, 80]),
|
||||
length_penalty=_TOKENS_COMPLETION,
|
||||
monkeypatch.setattr(Env, "__init__", fake_env_init)
|
||||
config = OrchestratorConfig(
|
||||
seq_len=100,
|
||||
advantage={"type": "default", "length_penalty": {"coef": 1.0}},
|
||||
)
|
||||
|
||||
assert sum(mixed.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
assert sum(all_correct.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
env = TrainEnv(config.train.env[0], max_seq_len=config.seq_len)
|
||||
assert env.advantage_fn is not None
|
||||
result = env.advantage_fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
|
||||
|
||||
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_amplification_bounded():
|
||||
"""Even with extreme length outliers, reward amplification is capped at 2x."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0], completion_lengths=[1, 10000, 5000])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
|
||||
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
|
||||
# Standard reward = 1, so amplification ≈ 2x
|
||||
# shaped_rewards ≈ [2, 1, 0], baseline ≈ 1, max advantage ≈ 1
|
||||
assert result.advantages[0] < 1.0 + 1e-3
|
||||
|
||||
|
||||
def test_efficiency_tokens_with_tool_response_weight():
|
||||
"""`tool_response_weight` shifts shaping onto tool-response tokens read from rollout metrics."""
|
||||
rollouts = [
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 200},
|
||||
def test_per_env_linear_advantage_uses_runtime_schema():
|
||||
config = OrchestratorConfig(
|
||||
seq_len=100,
|
||||
train={
|
||||
"env": [
|
||||
{
|
||||
"advantage": {
|
||||
"type": "default",
|
||||
"length_penalty": {"coef": 1.0},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 0},
|
||||
},
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 100},
|
||||
},
|
||||
]
|
||||
inputs = AdvantageInputs(rollouts=rollouts)
|
||||
|
||||
# completion tokens identical (10 each) → completion-only shaping is a no-op
|
||||
result_completion_only = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
assert result_completion_only.advantages == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
|
||||
|
||||
# tool-response only: costs are [200, 0, 100], mean=100, bonus is one-sided
|
||||
# so only the below-mean rollout (idx 1) gets amplified; the at/above-mean tie.
|
||||
result_tool_only = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
|
||||
advs = result_tool_only.advantages
|
||||
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_efficiency_fractional_weight_with_int_rewards():
|
||||
"""Fractional weights must not truncate when rollout rewards are emitted as ints."""
|
||||
rollouts_int = [
|
||||
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(7))}}]},
|
||||
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(11))}}]},
|
||||
{"reward": 0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(13))}}]},
|
||||
]
|
||||
rollouts_float = [{**r, "reward": float(r["reward"])} for r in rollouts_int]
|
||||
|
||||
fractional = TokensLengthPenaltyConfig(completion_weight=0.3, tool_response_weight=0.0)
|
||||
int_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_int), length_penalty=fractional)
|
||||
float_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_float), length_penalty=fractional)
|
||||
assert int_result.advantages == pytest.approx(float_result.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_zero_costs_falls_back_to_plain_grpo():
|
||||
"""When all effective costs are zero, shaping is a no-op (no NaNs from div-by-zero)."""
|
||||
# tool-only weights but no harness metric → all costs == 0
|
||||
rollouts = [
|
||||
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
{"reward": 0.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
]
|
||||
inputs = AdvantageInputs(rollouts=rollouts)
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
|
||||
expected = default_advantage_fn(inputs) # plain GRPO
|
||||
assert not any(math.isnan(a) for a in result.advantages)
|
||||
assert result.advantages == pytest.approx(expected.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_tokens_default_weights_match_completion_when_no_metric():
|
||||
"""Default TokensLengthPenaltyConfig (1,1) reduces to completion-only when rollouts lack the metric."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
|
||||
result_default = default_advantage_fn(inputs, length_penalty=TokensLengthPenaltyConfig())
|
||||
result_completion = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
assert result_default.advantages == pytest.approx(result_completion.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_turns_penalty():
|
||||
"""`TurnsLengthPenaltyConfig` shapes by trajectory turn count rather than token count."""
|
||||
inputs = _make_group(
|
||||
rewards=[1.0, 1.0, 0.0, 1.0],
|
||||
# token counts identical, but turns differ — turns penalty should still differentiate
|
||||
completion_lengths=[100, 100, 100, 100],
|
||||
num_turns=[1, 3, 2, 2],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_penalty=TurnsLengthPenaltyConfig())
|
||||
|
||||
# mean_correct_turns = (1+3+2)/3 = 2
|
||||
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
|
||||
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
|
||||
advantage = config.train.env[0].advantage
|
||||
assert isinstance(advantage, DefaultAdvantageConfig)
|
||||
assert isinstance(advantage.length_penalty, LinearLengthPenaltyConfig)
|
||||
|
||||
fn = setup_advantage_fn(advantage, max_seq_len=config.seq_len)
|
||||
result = fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
|
||||
|
||||
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
|
||||
|
||||
|
||||
def test_per_env_custom_advantage_uses_runtime_schema():
|
||||
config = OrchestratorConfig(
|
||||
train={
|
||||
"env": [
|
||||
{
|
||||
"advantage": {
|
||||
"type": "custom",
|
||||
"import_path": "tests.unit.orchestrator.test_advantage._dummy_custom_advantage",
|
||||
"kwargs": {"scale": 3.0},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
advantage = config.train.env[0].advantage
|
||||
assert isinstance(advantage, CustomAdvantageConfig)
|
||||
|
||||
fn = setup_advantage_fn(advantage)
|
||||
result = fn(_make_group(rewards=[1.0, 0.5], completion_lengths=[10, 20]))
|
||||
|
||||
assert result.advantages == pytest.approx([3.0, 1.5], abs=1e-6)
|
||||
|
||||
|
||||
def test_length_weighted_baseline():
|
||||
"""Length-weighted baseline uses sum(len_i * reward_i) / sum(len_i) instead of the plain mean."""
|
||||
rewards = [1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30, 60])
|
||||
result = default_advantage_fn(inputs, length_weighted_baseline=True)
|
||||
|
||||
baseline = (10 * 1.0 + 30 * 0.0 + 60 * 0.0) / (10 + 30 + 60) # 0.1
|
||||
assert result.advantages == pytest.approx([r - baseline for r in rewards], abs=1e-6)
|
||||
# Token-weighted mean of advantages is zero
|
||||
assert sum(length * adv for length, adv in zip((10, 30, 60), result.advantages)) == pytest.approx(0.0, abs=1e-5)
|
||||
|
||||
|
||||
def _train_rollouts(rewards: list[float]) -> list[TrainRollout]:
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from prime_rl.trainer.batch import prepare_batch, prepare_sample
|
||||
from prime_rl.transport.types import RoutedExperts, TrainingSample
|
||||
from prime_rl.trainer.batch import (
|
||||
pad_micro_batch,
|
||||
prepare_batch,
|
||||
prepare_sample,
|
||||
)
|
||||
from prime_rl.trainer.utils import build_bin_cost
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
|
||||
|
||||
|
||||
def _routed_experts(data, dtype=np.uint8):
|
||||
@@ -37,51 +44,80 @@ def make_training_example():
|
||||
return _make_training_example
|
||||
|
||||
|
||||
def test_training_sample_requires_env_name():
|
||||
with pytest.raises(TypeError, match="env_name"):
|
||||
TrainingSample(
|
||||
prompt_ids=[1, 2],
|
||||
prompt_mask=[False, False],
|
||||
completion_ids=[3, 4],
|
||||
completion_mask=[True, True],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
completion_temperatures=[1.0, 1.0],
|
||||
advantage=1.0,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("rollout_count", "num_train_workers", "expected_batches_per_worker"), [(4, 2, 2), (5, 2, 3), (7, 1, 7), (11, 4, 3)]
|
||||
)
|
||||
def test_prepare_batch_balances_micro_batches_across_workers(
|
||||
make_training_example, rollout_count, num_train_workers, expected_batches_per_worker
|
||||
):
|
||||
examples = [make_training_example() for i in range(rollout_count)]
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=4,
|
||||
num_train_workers=num_train_workers,
|
||||
idxs=[0] * rollout_count,
|
||||
num_loras=1,
|
||||
def make_sized_training_example(length: int, env_name: str = "test-env") -> TrainingSample:
|
||||
assert length >= 1
|
||||
prompt_len = length - 1
|
||||
return TrainingSample(
|
||||
prompt_ids=[1] * prompt_len,
|
||||
prompt_mask=[False] * prompt_len,
|
||||
completion_ids=[2],
|
||||
completion_mask=[True],
|
||||
completion_logprobs=[-0.1],
|
||||
completion_temperatures=[1.0],
|
||||
advantage=1.0,
|
||||
env_name=env_name,
|
||||
)
|
||||
|
||||
assert all(len(worker_batches) == expected_batches_per_worker for worker_batches in batches_per_gpu)
|
||||
|
||||
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
assert len(examples) <= len(flat_batches) < len(examples) + num_train_workers
|
||||
print(flat_batches)
|
||||
def _flatten_batches(batches_per_gpu):
|
||||
return [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
|
||||
# Verify real rollouts have expected non-zero advantages and loss mask
|
||||
for batch in flat_batches[: len(examples)]:
|
||||
print(batch)
|
||||
assert sum(1 for advantage in batch.advantages if advantage != 0.0) == 4
|
||||
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 2
|
||||
|
||||
# Verify padded batches have zero advantages and loss mask
|
||||
for batch in flat_batches[len(examples) :]:
|
||||
assert sum(1 for advantage in batch.advantages if advantage != 0.0) == 0
|
||||
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 0
|
||||
def _worker_token_sums(batches_per_gpu) -> list[int]:
|
||||
return [sum(len(batch.input_ids) for batch in worker_batches) for worker_batches in batches_per_gpu]
|
||||
|
||||
|
||||
def _has_loss_tokens(batch: MicroBatch) -> bool:
|
||||
return any(batch.loss_mask)
|
||||
|
||||
|
||||
def make_flops_config():
|
||||
return SimpleNamespace(
|
||||
hidden_size=16,
|
||||
num_attention_heads=2,
|
||||
num_key_value_heads=2,
|
||||
vocab_size=32,
|
||||
intermediate_size=64,
|
||||
num_hidden_layers=2,
|
||||
head_dim=8,
|
||||
)
|
||||
|
||||
|
||||
def test_randomized_packing_invariants():
|
||||
rng = np.random.default_rng(0)
|
||||
|
||||
for case_idx in range(80):
|
||||
seq_len = int(rng.choice([8, 16, 32, 64]))
|
||||
num_train_workers = int(rng.choice([1, 2, 4, 8]))
|
||||
num_samples = int(rng.integers(1, 65))
|
||||
lengths = [int(x) for x in rng.integers(1, seq_len + 1, size=num_samples)]
|
||||
examples = [make_sized_training_example(length, env_name=f"env-{case_idx}") for length in lengths]
|
||||
bin_cost = build_bin_cost(make_flops_config() if case_idx % 2 == 0 else None)
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=seq_len,
|
||||
num_train_workers=num_train_workers,
|
||||
idxs=[0] * len(examples),
|
||||
num_loras=1,
|
||||
bin_cost=bin_cost,
|
||||
)
|
||||
flat_batches = _flatten_batches(batches_per_gpu)
|
||||
real_batches = [batch for batch in flat_batches if _has_loss_tokens(batch)]
|
||||
dummy_batches = [batch for batch in flat_batches if not _has_loss_tokens(batch)]
|
||||
|
||||
assert all(len(worker_batches) == len(batches_per_gpu[0]) for worker_batches in batches_per_gpu)
|
||||
assert sorted(length for batch in real_batches for length in batch.sequence_lengths) == sorted(lengths)
|
||||
|
||||
for batch in flat_batches:
|
||||
assert len(batch.input_ids) <= seq_len
|
||||
assert sum(batch.sequence_lengths) == len(batch.input_ids)
|
||||
assert sum(batch.lora_num_tokens) == len(batch.input_ids)
|
||||
assert len(batch.env_names) == len(batch.input_ids)
|
||||
|
||||
for batch in dummy_batches:
|
||||
assert not any(batch.loss_mask)
|
||||
assert not any(batch.advantages)
|
||||
|
||||
|
||||
def test_prepare_batch_packs_different_temperatures(make_training_example):
|
||||
@@ -95,9 +131,10 @@ def test_prepare_batch_packs_different_temperatures(make_training_example):
|
||||
num_train_workers=1,
|
||||
idxs=[0, 0],
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
flat_batches = _flatten_batches(batches_per_gpu)
|
||||
# With per-token temperatures, samples can now be packed together
|
||||
assert len(flat_batches) == 1
|
||||
# Each sample has 4 tokens (2 prompt + 2 completion), so 8 total tokens
|
||||
@@ -107,14 +144,18 @@ def test_prepare_batch_packs_different_temperatures(make_training_example):
|
||||
# Second sample (4 tokens): all get temp 1.1
|
||||
assert flat_batches[0].temperatures[4:8] == [1.1, 1.1, 1.1, 1.1]
|
||||
assert flat_batches[0].env_names == ["env-a"] * 4 + ["env-b"] * 4
|
||||
assert flat_batches[0].sequence_lengths == [4, 4]
|
||||
|
||||
|
||||
def test_prepare_sample_propagates_training_mode(make_training_example):
|
||||
example = make_training_example(training_mode="sft")
|
||||
def test_pad_micro_batch_preserves_explicit_sequence_lengths(make_training_example):
|
||||
micro_batch = prepare_sample(make_training_example(), seq_len=16)
|
||||
|
||||
micro_batch = prepare_sample(example, seq_len=16)
|
||||
padded = pad_micro_batch(micro_batch, pad_to_multiple_of=6)
|
||||
|
||||
assert micro_batch.training_mode == "sft"
|
||||
assert len(padded.input_ids) == 6
|
||||
assert padded.sequence_lengths == [4, 2]
|
||||
assert sum(padded.sequence_lengths) == len(padded.input_ids)
|
||||
assert padded.loss_mask[-2:] == [False, False]
|
||||
|
||||
|
||||
def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
|
||||
@@ -127,33 +168,80 @@ def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
|
||||
num_train_workers=1,
|
||||
idxs=[0, 0],
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
flat_batches = _flatten_batches(batches_per_gpu)
|
||||
assert len(flat_batches) == 2
|
||||
assert {batch.training_mode for batch in flat_batches} == {"rl", "sft"}
|
||||
assert [batch.sequence_lengths for batch in flat_batches] == [[4], [4]]
|
||||
|
||||
|
||||
def test_prepare_sample_with_routed_experts():
|
||||
"""Routed experts are passed through prepare_sample and match input_ids length."""
|
||||
# 2 prompt + 2 completion = 4 tokens, 2 layers, topk=2
|
||||
routed_experts = [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[0, 2], [1, 3]], [[1, 0], [3, 2]]]
|
||||
routed_payload = _routed_experts(routed_experts)
|
||||
sample = TrainingSample(
|
||||
prompt_ids=[1, 2],
|
||||
prompt_mask=[False, False],
|
||||
completion_ids=[3, 4],
|
||||
completion_mask=[True, True],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
completion_temperatures=[1.0, 1.0],
|
||||
advantage=1.0,
|
||||
env_name="test-env",
|
||||
routed_experts=routed_payload,
|
||||
def test_split_to_align_avoids_dummy_micro_batches():
|
||||
examples = [make_sized_training_example(length) for length in [6, 6, 5, 5, 4, 4]]
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=12,
|
||||
num_train_workers=4,
|
||||
idxs=[0] * len(examples),
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
micro_batch = prepare_sample(sample, seq_len=8)
|
||||
assert micro_batch.routed_experts is not None
|
||||
assert micro_batch.routed_experts == routed_payload
|
||||
assert all(_has_loss_tokens(batch) for batch in _flatten_batches(batches_per_gpu))
|
||||
assert len(_flatten_batches(batches_per_gpu)) == 4
|
||||
|
||||
|
||||
def test_pack_first_then_balance_distributes_micro_batches_by_tokens_without_model_config():
|
||||
examples = [make_sized_training_example(length) for length in [100, 90, 80, 70]]
|
||||
|
||||
balanced = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=100,
|
||||
num_train_workers=2,
|
||||
idxs=[0] * len(examples),
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
assert _worker_token_sums(balanced) == [170, 170]
|
||||
|
||||
|
||||
def test_flop_aware_balancing_pairs_long_and_short_sequence_workloads():
|
||||
examples = [make_sized_training_example(length) for length in [32, 32, 16, 16, 16, 16]]
|
||||
bin_cost = build_bin_cost(make_flops_config())
|
||||
|
||||
balanced = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=32,
|
||||
num_train_workers=2,
|
||||
idxs=[0] * len(examples),
|
||||
num_loras=1,
|
||||
bin_cost=bin_cost,
|
||||
)
|
||||
|
||||
assert sorted([sorted(batch.sequence_lengths) for batch in balanced[0]]) == [[16, 16], [32]]
|
||||
assert sorted([sorted(batch.sequence_lengths) for batch in balanced[1]]) == [[16, 16], [32]]
|
||||
assert bin_cost([32]) > bin_cost([16, 16])
|
||||
|
||||
|
||||
def test_flop_aware_split_to_align_splits_heaviest_flop_bin():
|
||||
examples = [make_sized_training_example(length) for length in [20, 18, 9, 9, 8, 8, 8]]
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=64,
|
||||
num_train_workers=4,
|
||||
idxs=[0] * len(examples),
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(make_flops_config()),
|
||||
)
|
||||
|
||||
real_batches = [batch for batch in _flatten_batches(batches_per_gpu) if _has_loss_tokens(batch)]
|
||||
assert len(real_batches) == 4
|
||||
assert sorted(length for batch in real_batches for length in batch.sequence_lengths) == [8, 8, 8, 9, 9, 18, 20]
|
||||
assert sum(len(batch.sequence_lengths) > 1 for batch in real_batches) == 3
|
||||
|
||||
|
||||
def test_prepare_sample_truncates_routed_experts():
|
||||
@@ -177,20 +265,3 @@ def test_prepare_sample_truncates_routed_experts():
|
||||
assert micro_batch.routed_experts is not None
|
||||
assert micro_batch.routed_experts == expected_payload
|
||||
assert micro_batch.env_names == ["test-env"] * 3
|
||||
|
||||
|
||||
def test_prepare_sample_none_routed_experts():
|
||||
"""When routed_experts is None, micro_batch.routed_experts is None."""
|
||||
sample = TrainingSample(
|
||||
prompt_ids=[1, 2],
|
||||
prompt_mask=[False, False],
|
||||
completion_ids=[3, 4],
|
||||
completion_mask=[True, True],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
completion_temperatures=[1.0, 1.0],
|
||||
advantage=1.0,
|
||||
env_name="test-env",
|
||||
)
|
||||
|
||||
micro_batch = prepare_sample(sample, seq_len=8)
|
||||
assert micro_batch.routed_experts is None
|
||||
|
||||
@@ -167,6 +167,53 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
|
||||
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
|
||||
|
||||
|
||||
def test_trainer_enable_token_export_cli_flag():
|
||||
assert not cli(TrainerConfig, args=[]).enable_token_export
|
||||
assert cli(TrainerConfig, args=["--enable-token-export"]).enable_token_export
|
||||
|
||||
|
||||
def test_single_node_auto_inference_client_dp_rank_count_matches_local_dp():
|
||||
config = RLConfig.model_validate(
|
||||
{
|
||||
"trainer": {},
|
||||
"orchestrator": {},
|
||||
"inference": {"parallel": {"tp": 1}},
|
||||
"deployment": {
|
||||
"type": "single_node",
|
||||
"gpus_per_node": 4,
|
||||
"num_train_gpus": 2,
|
||||
"num_infer_gpus": 2,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert config.inference is not None
|
||||
assert config.inference.parallel.dp == 2
|
||||
assert config.orchestrator.student.client.dp_rank_count == 2
|
||||
|
||||
|
||||
def test_multi_node_auto_inference_client_dp_rank_count_uses_router_url():
|
||||
config = RLConfig.model_validate(
|
||||
{
|
||||
"trainer": {},
|
||||
"orchestrator": {},
|
||||
"inference": {"parallel": {"tp": 4}},
|
||||
"deployment": {
|
||||
"type": "multi_node",
|
||||
"gpus_per_node": 8,
|
||||
"num_train_nodes": 1,
|
||||
"num_infer_nodes": 2,
|
||||
},
|
||||
"slurm": {},
|
||||
}
|
||||
)
|
||||
|
||||
assert config.inference is not None
|
||||
assert config.inference.data_parallel_size_local == 2
|
||||
assert config.inference.parallel.dp == 2
|
||||
assert config.orchestrator.student.client.dp_rank_count == 1
|
||||
|
||||
|
||||
def test_orchestrator_vlm_requires_renderer():
|
||||
with pytest.raises(ValidationError, match="orchestrator.renderer must be set when model.vlm is set"):
|
||||
OrchestratorConfig.model_validate(
|
||||
|
||||
@@ -38,8 +38,8 @@ EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
|
||||
("PrimeIntellect/INTELLECT-3-FP8", "qwen3_coder", "deepseek_r1"),
|
||||
("PrimeIntellect/INTELLECT-3.1", "qwen3_coder", "deepseek_r1"),
|
||||
# NemotronH
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", None),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", None),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", "nemotron_v3"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", "nano_v3"),
|
||||
# StepFun
|
||||
("stepfun-ai/Step-3.5-Flash", "step3p5", "step3p5"),
|
||||
# Qwen3 dense
|
||||
|
||||
@@ -10,6 +10,7 @@ import prime_rl.trainer.runs as runs
|
||||
from prime_rl.configs.shared import FileSystemTransportConfig
|
||||
from prime_rl.trainer.rl.packer import MultiPacker
|
||||
from prime_rl.trainer.runs import setup_multi_run_manager
|
||||
from prime_rl.trainer.utils import build_bin_cost
|
||||
from prime_rl.trainer.world import reset_world
|
||||
from prime_rl.transport.types import TrainingSample
|
||||
|
||||
@@ -94,6 +95,7 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
||||
pad_to_multiple_of=1,
|
||||
tokenizer=None,
|
||||
config=FileSystemTransportConfig(),
|
||||
bin_cost=build_bin_cost(None),
|
||||
start_step=0,
|
||||
)
|
||||
|
||||
@@ -110,3 +112,6 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
||||
sender = sender_holder["sender"]
|
||||
assert len(sender.sent) == 1
|
||||
assert len(sender.sent[0][0]) == 1
|
||||
micro_batch = sender.sent[0][0][0]
|
||||
assert micro_batch.run_id == "run_test123"
|
||||
assert micro_batch.run_step == 0
|
||||
|
||||
@@ -11,7 +11,7 @@ supported-markers = [
|
||||
]
|
||||
|
||||
[options]
|
||||
exclude-newer = "2026-06-01T23:58:54.614773201Z"
|
||||
exclude-newer = "2026-06-10T23:37:49.383138959Z"
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
@@ -1234,6 +1234,7 @@ dependencies = [
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/c8/33/c97b2bcbe06e0f011eedee0f41d4060f6344901a53c2703acc3dd7429713/fastsafetensors-0.3.2.tar.gz", hash = "sha256:9e358fce238684613a5c3ebb7800c52c5b3270c0bb5e4ed2191ee8f3d0431de1", size = 70409, upload-time = "2026-05-22T05:39:34.787Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c9/bb/9f821eac9bddd41ea1c5cd9b6a597c002741f022ecf6f3ba5cfcc3e9c950/fastsafetensors-0.3.2-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:69f4d8cbd3b542e5ddf7fee8136cf35e1524f9c30e118f64a0e846dab7e8de6b", size = 1877989, upload-time = "2026-06-04T09:02:56.11Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/68/a31c1661adf4d1b5ec29470ff991bde9094e4f347b0e6d1af8ba6b560d32/fastsafetensors-0.3.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6a932d7166c9e17e48aca3e5503d326bc6fc73fce6dc985ae6bd2ccc0f308b14", size = 1907188, upload-time = "2026-05-22T05:39:30.242Z" },
|
||||
]
|
||||
|
||||
@@ -4013,7 +4014,9 @@ envs = [
|
||||
{ name = "opencode-science", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "opencode-swe", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "reverse-text", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "rlm-search", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "rlm-swe", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "rlm-uuid-ctf", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "science-env", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "simpleqa-verified", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "tau2-bench", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -4114,7 +4117,9 @@ requires-dist = [
|
||||
{ name = "reverse-text", marker = "extra == 'envs'", editable = "deps/verifiers/environments/reverse_text" },
|
||||
{ name = "rich", specifier = ">=14.0.0" },
|
||||
{ name = "ring-flash-attn", specifier = ">=0.1.8" },
|
||||
{ name = "rlm-search", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_search" },
|
||||
{ name = "rlm-swe", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_swe" },
|
||||
{ name = "rlm-uuid-ctf", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_uuid_ctf" },
|
||||
{ name = "science-env", marker = "extra == 'envs'", editable = "deps/research-environments/environments/science_env" },
|
||||
{ name = "setproctitle", specifier = ">=1.3.0" },
|
||||
{ name = "simpleqa-verified", marker = "extra == 'envs'", editable = "deps/research-environments/environments/simpleqa_verified" },
|
||||
@@ -4190,16 +4195,16 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-tunnel"
|
||||
version = "0.1.7"
|
||||
version = "0.1.9"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "pydantic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "tenacity", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/91/63/900dbb168a0f49dd9b6c510520a8c9b2b7ecb2c5863caac7757f12ea16e5/prime_tunnel-0.1.7.tar.gz", hash = "sha256:0fd296a78645c95c4474cf418321bac2ad6ba6816701e8823baf6ab718a68a5a", size = 13024, upload-time = "2026-05-20T06:38:40.444Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/36/de/0d17589b232708d1f5985372d1ca49e73493e0b08f860e6540d4885ce229/prime_tunnel-0.1.9.tar.gz", hash = "sha256:8d6c7fd7f5a98c47f50707edd606c4e7110e9dd1a08a1008b073be466408ac8d", size = 15162, upload-time = "2026-06-11T18:10:03.513Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/60/32/3270dba4c7c402372d25faf8f633f571fe2be8692d720e0eb717ed6ab44e/prime_tunnel-0.1.7-py3-none-any.whl", hash = "sha256:226a08ef9cc4c13503f4e1a687d4fa733ab72626725538b822edbaf8064c40fd", size = 14912, upload-time = "2026-05-20T06:38:38.986Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/50/2a/4b370d5d7cf7cbd98ce2714b7d877d2a184cc1b00d599df498aca04bce2d/prime_tunnel-0.1.9-py3-none-any.whl", hash = "sha256:9ad888e26ba4d81e96c643d9d27687ed4737c873f3b80ed3da8f92d6d7a2a615", size = 16274, upload-time = "2026-06-11T18:10:01.463Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4921,9 +4926,30 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/02/18ba0727a1c755c528d6a52b363d62c0b7a8e64cf961b3030c046107db4d/ring_flash_attn-0.1.8-py3-none-any.whl", hash = "sha256:296c929516c3b21f7bcdaeca44a99bb541779a7b63979eb0f67837dcb18a2bb9", size = 25437, upload-time = "2025-09-10T11:53:07.565Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rlm-search"
|
||||
version = "0.1.2"
|
||||
source = { editable = "deps/research-environments/environments/rlm_search" }
|
||||
dependencies = [
|
||||
{ name = "datasets", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "httpx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "openai", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "prime-sandboxes", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "verifiers", extra = ["packages"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets", specifier = ">=4.0.0" },
|
||||
{ name = "httpx" },
|
||||
{ name = "openai", specifier = ">=1.0" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.19" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev171" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rlm-swe"
|
||||
version = "0.4.4"
|
||||
version = "0.5.1"
|
||||
source = { editable = "deps/research-environments/environments/rlm_swe" }
|
||||
dependencies = [
|
||||
{ name = "multi-swe-bench", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -4937,6 +4963,23 @@ requires-dist = [
|
||||
{ name = "multi-swe-bench", specifier = ">=1.1.2" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.19" },
|
||||
{ name = "swebench", specifier = "==4.1.0" },
|
||||
{ name = "verifiers", extras = ["packages"], specifier = ">=0.1.15.dev17,<0.1.15.dev156" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rlm-uuid-ctf"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/research-environments/environments/rlm_uuid_ctf" }
|
||||
dependencies = [
|
||||
{ name = "datasets", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "prime-sandboxes", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "verifiers", extra = ["packages"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets", specifier = ">=4.0.0" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.21" },
|
||||
{ name = "verifiers", extras = ["packages"], specifier = ">=0.1.15.dev17" },
|
||||
]
|
||||
|
||||
@@ -6002,7 +6045,7 @@ requires-dist = [
|
||||
{ name = "pillow" },
|
||||
{ name = "prime-pydantic-config", extras = ["toml"] },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.25" },
|
||||
{ name = "prime-tunnel", specifier = ">=0.1.6" },
|
||||
{ name = "prime-tunnel", specifier = ">=0.1.8" },
|
||||
{ name = "pydantic", specifier = ">=2.11.9" },
|
||||
{ name = "pymupdf" },
|
||||
{ name = "python-dotenv", marker = "extra == 'browser'", specifier = ">=1.0.0" },
|
||||
|
||||
Reference in New Issue
Block a user