Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdb1480c66 | ||
|
|
f34efdbf49 | ||
|
|
9b47b777aa | ||
|
|
1877714656 | ||
|
|
77766bb59c | ||
|
|
1caebf8a1b | ||
|
|
db04385acf | ||
|
|
2bc136cf85 | ||
|
|
6bfbd64aef | ||
|
|
b453f40d8c | ||
|
|
1b028ca1d1 | ||
|
|
e96bbae2dd | ||
|
|
df2acf4874 | ||
|
|
5ff9abd8b5 | ||
|
|
5448f5a722 | ||
|
|
8a977ecc9c | ||
|
|
1ab29c0587 | ||
|
|
5e6b641574 | ||
|
|
16f5c7222b | ||
|
|
5c0a6dbdba | ||
|
|
dbe95b799a | ||
|
|
07e6bec87a | ||
|
|
9fede0ac78 | ||
|
|
d16981b533 | ||
|
|
b2b4f3f711 | ||
|
|
50aeb3c7d6 | ||
|
|
4beb553525 | ||
|
|
51dc60a895 | ||
|
|
a8f090b444 | ||
|
|
cdea189e3d | ||
|
|
d5f218f708 | ||
|
|
a03c70f55b | ||
|
|
e48a53853e | ||
|
|
f3c85a947a |
@@ -25,7 +25,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --extra flash-attn --extra envs --locked
|
||||
- name: Run tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **fp32 MoE routing enabled by default**: `trainer.model.moe_router_dtype` (new field) defaults to `"float32"` — custom-impl MoE router gates keep fp32 weights through forward/backward (exempt from the FSDP bf16 cast) and compute the gate GEMM and routing logits in fp32. `inference.enable_fp32_router_logits` (new field) defaults to `true` — DeepSeek-family models served by vLLM (incl. GLM-5.x) emit fp32 router logits via `out_dtype=float32` on the gate. Both change MoE numerics for existing runs (routing logits are no longer rounded to bf16; near-tie expert selections can differ). Set `moe_router_dtype = "bfloat16"` / `enable_fp32_router_logits = false` to restore the previous behavior. Non-MoE and HF-impl models are unaffected. (2026-07-04)
|
||||
- **`[[orchestrator.train.env]].ratio` now defaults to `1` and no longer accepts unset/`None`**: Each train env's sampling weight defaults to `1` (equal weight per env) instead of `None`. The `None`-for-all-envs mode — which sampled proportional to each env's dataset size (the "natural task distribution") — is removed, along with the all-or-none constraint (any subset of envs may now set `ratio`; the rest default to `1`). Multi-env configs that relied on the old default now sample each env equally rather than proportional to dataset size; set each env's `ratio` explicitly to restore a proportional (or any other) mix. (2026-07-02)
|
||||
- **`orchestrator.algo.length_penalty` restructured to a single `linear` shape; `tokens`/`turns` length penalties removed**: The `grpo`-family length penalty keeps the `[orchestrator.algo.length_penalty]` key but is collapsed to a single `type = "linear"` shape; the discriminated `type = "tokens" | "turns"` efficiency-shaping variants (and the `efficiency_shaping` helper) are removed. The linear penalty subtracts a `pass_rate`-scaled penalty from each reward before the GRPO baseline, summing three terms — `num_output_tokens_weight` × output tokens, `num_input_tokens_weight` × input (non-output) tokens, and `num_turns_weight` × turns — each normalized by the group's own max for that quantity. Field renames within the penalty: `coef` → `num_output_tokens_weight` (default `0.25`), `context_coef` → `num_input_tokens_weight` (default `0.1`), `turns_coef` → `num_turns_weight` (default `0.1`); the `gate_by_correctness` flag is removed. `extra="forbid"` rejects the old keys, so existing configs must migrate. (2026-06-29)
|
||||
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
|
||||
- **Memory-saving defaults enabled**: `trainer.model.ac`, `trainer.model.ac_offloading`, `trainer.model.compile`, `trainer.model.optim_cpu_offload`, and `trainer.model.fused_lm_head_token_chunk_size` are now enabled by default to provide sane memory-efficient defaults out of the box. Specifically: `ac` defaults to `ActivationCheckpointConfig()` (full mode), `ac_offloading` defaults to `ActivationOffloadingConfig()`, `compile` defaults to `CompileConfig()` (`fullgraph=false`), `optim_cpu_offload` defaults to `true`, and `fused_lm_head_token_chunk_size` defaults to `1024`. SFT training silently disables `fused_lm_head_token_chunk_size` (sets it to `"disabled"`). Configs using `max_concurrent_runs > 1` must explicitly set `optim_cpu_offload = false`. To disable any of these, set the field to `None` / `"None"` / `false` / `"disabled"` as appropriate.
|
||||
|
||||
@@ -8,3 +8,6 @@ gpu_memory_utilization = 0.7
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
max_model_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ id = "reverse-text"
|
||||
interval = 10
|
||||
resume_step = -1
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -16,3 +16,6 @@ freq = 1
|
||||
|
||||
[model.compile]
|
||||
fullgraph = false
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
# exp: GLM-4.5-Air (100B MoE) RL across our v1 SEARCH-domain envs — bring-your-own-search QA, run
|
||||
# through the rlm harness (its built-in `search` skill) on a prime sandbox. GRPO + linear length
|
||||
# penalty. 2 train + 4 infer nodes. Single run label (glm45air-search) for all envs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-search"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-search" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.0
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
|
||||
|
||||
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
|
||||
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
|
||||
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
|
||||
[[orchestrator.train.env]]
|
||||
name = "openseeker"
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "openseeker-v1"
|
||||
|
||||
[[orchestrator.train.env.taskset.judges]]
|
||||
id = "reference"
|
||||
name = "correct"
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
question_field = "question"
|
||||
choices = ["A", "B"]
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "redsearcher"
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
|
||||
|
||||
[[orchestrator.train.env.taskset.judges]]
|
||||
id = "reference"
|
||||
name = "correct"
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
question_field = "question"
|
||||
choices = ["A", "B"]
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Eval: BrowseComp held-out test, every 20 steps (incl. step 0) ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "browsecomp"
|
||||
num_examples = 500 # full set is 1266; cap eval at 500
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "browsecomp-v1"
|
||||
judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" }
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -1,7 +1,11 @@
|
||||
# v1 RL ablation: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, default (bash+edit) harness on
|
||||
# a prime sandbox runtime; eval on SWE-Bench Verified. Router replay is enabled
|
||||
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
|
||||
# enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe model, which supports routed_experts.
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
#
|
||||
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
@@ -10,19 +14,18 @@
|
||||
# configs/debug/v1/scaleswe.toml + GLM-4.5-Air model settings from the int5 opencode configs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 65536
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/triton-cache-$USER-$SLURM_JOB_ID"
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe"
|
||||
project_dir = "."
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -82,43 +85,49 @@ group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "scaleswe"
|
||||
taskset = { id = "scaleswe-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
taskset = { id = "scaleswe-v1", use_prime_registry = true }
|
||||
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, default (bash+edit) harness on prime ---
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
skip_first_step = false
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm_cache_$(whoami)"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/flashinfer-$(whoami)"
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -0,0 +1,181 @@
|
||||
# exp: GLM-4.5-Air (100B MoE) RL across our v1 TERMINAL-domain envs — agentic shell/sandbox tasks
|
||||
# run through the rlm harness (ipython-only) on a prime sandbox. Each task ships its own Docker image
|
||||
# (NEEDS_CONTAINER) injected into the sandbox; grading is host-side inside the container. GRPO +
|
||||
# linear length penalty. 2 train + 4 infer nodes. Single run label (glm45air-terminal) for all envs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-terminal"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-terminal" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "tmax"
|
||||
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "tmax-v1"
|
||||
|
||||
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Eval: swebench-verified (avg@1) + terminal-bench-2 (full, avg@4) every 20 steps, incl. step 0 ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
use_prime_registry = true
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "terminal-bench-2"
|
||||
group_size = 4 # avg@4
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "terminal-bench-2-v1"
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -1,4 +1,4 @@
|
||||
# GLM-5.2-FP8 16-node P/D, FULL STACK: mooncake + llm-d router, vLLM 0.23.
|
||||
# GLM-5.2-FP8 16-node P/D, FULL STACK: mooncake + llm-d router, vLLM 0.24.
|
||||
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
|
||||
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
|
||||
#
|
||||
@@ -31,9 +31,9 @@ num_bytes = 1_000_000_000_000
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 8
|
||||
decode_nodes_per_replica = 8
|
||||
num_decode_replicas = 1
|
||||
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
|
||||
@@ -10,8 +10,8 @@ reasoning_parser = "glm45"
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 4
|
||||
num_decode_nodes = 2
|
||||
prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 2
|
||||
gpus_per_node = 8
|
||||
|
||||
[slurm]
|
||||
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: a5efbb97e4...5904fa24aa
Vendored
+1
-1
Submodule deps/research-environments updated: de32ad4af2...3e3b5ac3d7
Vendored
+1
-1
Submodule deps/verifiers updated: 22d6333a00...fab50d5107
+1
-1
@@ -106,7 +106,7 @@ dropout = 0.0
|
||||
|
||||
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
|
||||
|
||||
LoRA is supported across SFT and RL. For RL, `weight_broadcast.type = "nccl"` is **not** supported with LoRA — use the default filesystem transport. To save the raw adapter alongside the merged HF weights:
|
||||
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
|
||||
|
||||
```toml
|
||||
[ckpt.weights]
|
||||
|
||||
+1
-1
@@ -157,7 +157,7 @@ At step $n = 1, 2, 3, \dots$:
|
||||
- **Trainer** produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$.
|
||||
- **Inference** produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\,n-1)}$.
|
||||
|
||||
Step indices are 0-indexed so the gap holds at startup — inference is exactly one step behind the trainer.
|
||||
Step indices are 1-indexed; policy versions are 0-indexed, with $\pi_0$ the base model. At step 1 inference samples from $\pi_0$.
|
||||
|
||||
## Loss
|
||||
|
||||
|
||||
@@ -151,10 +151,11 @@ Training environments are an array of tables — set one per env, optionally wit
|
||||
id = "math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
ratio = 3 # 75% of batches
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
ratio = 0.25 # 25% of batches; remaining 75% goes to math-env
|
||||
ratio = 1 # default — 25% of batches
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math-env"
|
||||
@@ -162,6 +163,8 @@ name = "gsm8k-eval"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
```
|
||||
|
||||
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
|
||||
|
||||
`args` is forwarded verbatim to the environment's `load_environment(**args)`.
|
||||
|
||||
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
|
||||
|
||||
+9
-11
@@ -128,41 +128,39 @@ This configuration will run 2 vLLM processes, each with `data_parallel_size_loca
|
||||
|
||||
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
|
||||
|
||||
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
|
||||
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and choosing how many nodes each prefill and decode replica spans.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
prefill_nodes_per_replica = 2
|
||||
decode_nodes_per_replica = 2
|
||||
```
|
||||
|
||||
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
|
||||
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode stages. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of role replicas you want to run.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 2
|
||||
decode_nodes_per_replica = 2
|
||||
num_decode_replicas = 1
|
||||
```
|
||||
|
||||
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
|
||||
Now each prefill replica spans 2 nodes and each decode replica spans 2 nodes. With 2 prefill replicas and 1 decode replica, one inference island spans 6 nodes.
|
||||
|
||||
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
|
||||
For RL runs, the top-level deployment can multiply that whole inference island by setting `deployment.num_infer_replicas`. `deployment.num_infer_nodes` is inferred from the nested inference deployment when you omit it.
|
||||
|
||||
```toml
|
||||
[deployment] # this is a top-level RL deployment, not inference.deployment!!
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
num_infer_nodes = 6 # this is per-replica
|
||||
|
||||
num_infer_replicas = 3
|
||||
```
|
||||
|
||||
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
|
||||
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
|
||||
|
||||
|
||||
## Router
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ A `prime-rl` RL run is three cooperating processes:
|
||||
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
|
||||
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
|
||||
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
+1
-1
@@ -208,7 +208,7 @@ uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_nodes = 1 # optional when inference.deployment defines the node topology
|
||||
gpus_per_node = 8 # default
|
||||
nodes_per_fsdp_group = 1 # optional — controls FSDP island size
|
||||
```
|
||||
|
||||
+3
-1
@@ -226,7 +226,7 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma
|
||||
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1` for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
|
||||
|
||||
```bash
|
||||
# First run: steps 0–10
|
||||
# First run: steps 1–10
|
||||
uv run rl @ rl.toml --max-steps 10 --ckpt
|
||||
|
||||
# Resume: continue to step 20
|
||||
@@ -307,6 +307,8 @@ uv run rl @ rl.toml --wandb \
|
||||
--no-trainer.wandb.log-extras.distributions
|
||||
```
|
||||
|
||||
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
|
||||
|
||||
### Platform Monitoring
|
||||
|
||||
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics, samples, and distributions to the platform dashboard. Bare flag uses defaults:
|
||||
|
||||
@@ -19,15 +19,14 @@ quantize_in_weight_transfer = true
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
num_infer_nodes = 16
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 1
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 8
|
||||
decode_nodes_per_replica = 8
|
||||
num_decode_replicas = 1
|
||||
# skip warmup for faster start in cost of some jit overhead early
|
||||
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
|
||||
|
||||
@@ -15,14 +15,13 @@ quantize_in_weight_transfer = true
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
num_infer_nodes = 8
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 2
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 4
|
||||
num_decode_nodes = 4
|
||||
prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "glm5-pd-disag"
|
||||
|
||||
@@ -274,25 +274,22 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
|
||||
|
||||
# Disaggregated prefill/decode inference. Each replica is split into separate
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
|
||||
# for request routing. Multi-replica: set ``num_prefill_replicas`` /
|
||||
# ``num_decode_replicas`` to run multiple independent vLLM instances within the
|
||||
# prefill / decode node groups. E.g. ``num_prefill_nodes=4, num_prefill_replicas=2``
|
||||
# creates two prefill vLLM instances each spanning 2 nodes (EP16 with 8 GPUs/node).
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a router for
|
||||
# request routing.
|
||||
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
type: Literal["disaggregated"] = "disaggregated"
|
||||
|
||||
num_prefill_nodes: int = Field(1, ge=1)
|
||||
"""Total prefill nodes."""
|
||||
prefill_nodes_per_replica: int = Field(1, ge=1)
|
||||
"""Nodes in each prefill vLLM instance."""
|
||||
|
||||
num_decode_nodes: int = Field(1, ge=1)
|
||||
"""Total decode nodes."""
|
||||
decode_nodes_per_replica: int = Field(1, ge=1)
|
||||
"""Nodes in each decode vLLM instance."""
|
||||
|
||||
num_prefill_replicas: int = Field(1, ge=1)
|
||||
"""Independent prefill vLLM instances. Must evenly divide ``num_prefill_nodes``."""
|
||||
"""Independent prefill vLLM instances."""
|
||||
|
||||
num_decode_replicas: int = Field(1, ge=1)
|
||||
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
|
||||
"""Independent decode vLLM instances."""
|
||||
|
||||
prefill_port: int = 8100
|
||||
"""Port for prefill vLLM instances."""
|
||||
@@ -312,24 +309,18 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
decode_vllm_overrides: dict[str, Any] = {}
|
||||
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
|
||||
|
||||
@property
|
||||
def num_prefill_nodes(self) -> int:
|
||||
return self.prefill_nodes_per_replica * self.num_prefill_replicas
|
||||
|
||||
@property
|
||||
def num_decode_nodes(self) -> int:
|
||||
return self.decode_nodes_per_replica * self.num_decode_replicas
|
||||
|
||||
@property
|
||||
def num_nodes(self) -> int:
|
||||
return self.num_prefill_nodes + self.num_decode_nodes
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_replicas_divide_nodes(self):
|
||||
if self.num_prefill_nodes % self.num_prefill_replicas != 0:
|
||||
raise ValueError(
|
||||
f"num_prefill_replicas ({self.num_prefill_replicas}) must evenly divide "
|
||||
f"num_prefill_nodes ({self.num_prefill_nodes})"
|
||||
)
|
||||
if self.num_decode_nodes % self.num_decode_replicas != 0:
|
||||
raise ValueError(
|
||||
f"num_decode_replicas ({self.num_decode_replicas}) must evenly divide "
|
||||
f"num_decode_nodes ({self.num_decode_nodes})"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeInferenceDeploymentConfig | MultiNodeInferenceDeploymentConfig | DisaggregatedInferenceDeploymentConfig,
|
||||
@@ -337,10 +328,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class InferenceExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class InferenceConfig(BaseConfig):
|
||||
server: ServerConfig = ServerConfig()
|
||||
|
||||
@@ -420,6 +407,9 @@ class InferenceConfig(BaseConfig):
|
||||
enable_fp32_lm_head: bool = True
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
|
||||
enable_fp32_router_logits: bool = True
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
|
||||
|
||||
vllm_extra: dict[str, Any] = {}
|
||||
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
|
||||
|
||||
@@ -436,8 +426,6 @@ class InferenceConfig(BaseConfig):
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: InferenceExperimentalConfig = InferenceExperimentalConfig()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_multi_node_requires_slurm(self):
|
||||
if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None:
|
||||
@@ -614,6 +602,10 @@ class InferenceConfig(BaseConfig):
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_lm_head"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
if self.enable_fp32_router_logits:
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_router_logits"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
|
||||
# Remove chat_template if not set (vLLM doesn't accept None)
|
||||
if namespace.chat_template is None:
|
||||
|
||||
@@ -50,7 +50,7 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
|
||||
class TrainSamplingConfig(BaseConfig):
|
||||
temperature: float = Field(1.0, ge=0)
|
||||
temperature: float = Field(1.0, ge=0, le=2.0)
|
||||
"""Sampling temperature."""
|
||||
|
||||
max_completion_tokens: int | None = Field(
|
||||
@@ -92,7 +92,7 @@ class TrainSamplingConfig(BaseConfig):
|
||||
|
||||
|
||||
class EvalSamplingConfig(BaseConfig):
|
||||
temperature: float | None = Field(None, ge=0)
|
||||
temperature: float | None = Field(None, ge=0, le=2.0)
|
||||
"""Sampling temperature. None defers to the inference server default."""
|
||||
|
||||
top_p: float | None = None
|
||||
@@ -157,11 +157,8 @@ class EnvConfig(vf.EnvServerConfig):
|
||||
address: str | None = None
|
||||
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
|
||||
|
||||
ratio: float | None = Field(None, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Times the env server retries a failed rollout before returning an error."""
|
||||
ratio: float = Field(1.0, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
@@ -248,13 +245,10 @@ class TrainConfig(BaseConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling and max_retries (the
|
||||
worker ``pool`` is configured per env, defaulting to elastic)."""
|
||||
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
|
||||
is configured per env, defaulting to elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
@@ -262,8 +256,6 @@ class TrainConfig(BaseConfig):
|
||||
else:
|
||||
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
|
||||
env.sampling = TrainSamplingConfig(**merged)
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -276,15 +268,6 @@ class TrainConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env_ratios(self):
|
||||
ratios = [env.ratio for env in self.env]
|
||||
if all(r is None for r in ratios):
|
||||
return self
|
||||
if any(r is None for r in ratios):
|
||||
raise ValueError("Either all envs must have a ratio or none of them. Got a mix of set and unset ratios.")
|
||||
return self
|
||||
|
||||
|
||||
class EvalConfig(BaseConfig):
|
||||
env: list[EvalEnvConfig] = Field(default_factory=list)
|
||||
@@ -299,9 +282,6 @@ class EvalConfig(BaseConfig):
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
"""Step interval at which to evaluate the model."""
|
||||
|
||||
@@ -311,7 +291,7 @@ class EvalConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, max_retries, num_examples,
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
|
||||
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
@@ -326,8 +306,6 @@ class EvalConfig(BaseConfig):
|
||||
env.group_size = self.group_size
|
||||
if "interval" not in env.model_fields_set:
|
||||
env.interval = self.interval
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -443,10 +421,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class OrchestratorExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class OrchestratorConfig(BaseConfig):
|
||||
algo: AlgoConfig = GRPOAlgoConfig()
|
||||
"""Training algorithm: sampling plus the per-token training signal (credit
|
||||
@@ -563,8 +537,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _env_to_train(cls, data: Any) -> Any:
|
||||
|
||||
@@ -46,10 +46,6 @@ from prime_rl.utils.validation import (
|
||||
)
|
||||
|
||||
|
||||
class RLExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
level: str | None = None
|
||||
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
|
||||
@@ -115,7 +111,7 @@ class SharedModelConfig(BaseConfig):
|
||||
|
||||
|
||||
class SharedWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["nccl", "filesystem"] = "filesystem"
|
||||
type: Literal["nccl", "filesystem"] = "nccl"
|
||||
"""Weight broadcast transport."""
|
||||
|
||||
port: int = 29501
|
||||
@@ -159,8 +155,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
num_train_nodes: int
|
||||
"""Training nodes."""
|
||||
|
||||
num_infer_nodes: int = Field(ge=0)
|
||||
"""Inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data)."""
|
||||
num_infer_nodes: int | None = Field(None, ge=0)
|
||||
"""Inference nodes per replica. If unset, inferred from ``inference.deployment``. Set to 0 to skip inference and orchestrator (requires fake data)."""
|
||||
|
||||
num_infer_replicas: int = Field(1, ge=1)
|
||||
"""Independent inference replicas. Total inference nodes = ``num_infer_nodes * num_infer_replicas``."""
|
||||
@@ -171,9 +167,13 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
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 infer_nodes_per_replica(self) -> int:
|
||||
return self.num_infer_nodes or 0
|
||||
|
||||
@property
|
||||
def total_infer_nodes(self) -> int:
|
||||
return self.num_infer_nodes * self.num_infer_replicas
|
||||
return self.infer_nodes_per_replica * self.num_infer_replicas
|
||||
|
||||
|
||||
DeploymentConfig: TypeAlias = Annotated[
|
||||
@@ -234,23 +234,49 @@ class RLConfig(BaseConfig):
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: RLExperimentalConfig = RLExperimentalConfig()
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_infer_nodes(self):
|
||||
if self.deployment.type != "multi_node":
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
inferred_nodes = 0
|
||||
elif self.inference.deployment.type == "multi_node":
|
||||
inferred_nodes = self.inference.deployment.num_nodes
|
||||
elif self.inference.deployment.type == "disaggregated":
|
||||
inferred_nodes = self.inference.deployment.num_nodes
|
||||
else:
|
||||
inferred_nodes = 1
|
||||
|
||||
if self.deployment.num_infer_nodes is None:
|
||||
self.deployment.num_infer_nodes = inferred_nodes
|
||||
elif (
|
||||
self.inference is not None
|
||||
and self.inference.deployment.type == "multi_node"
|
||||
and self.deployment.num_infer_nodes != inferred_nodes
|
||||
):
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
|
||||
f"inference.deployment.num_nodes ({inferred_nodes}) for multi-node inference."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
if self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
if self.deployment.num_infer_nodes > 0 and not self.inference:
|
||||
num_infer_nodes = self.deployment.infer_nodes_per_replica
|
||||
if num_infer_nodes > 0 and not self.inference:
|
||||
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
|
||||
if self.deployment.num_infer_nodes == 0 and self.inference:
|
||||
if num_infer_nodes == 0 and self.inference:
|
||||
raise ValueError(
|
||||
"Cannot configure inference with num_infer_nodes = 0. "
|
||||
"Either set num_infer_nodes > 0 or remove the inference config."
|
||||
)
|
||||
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
if num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
raise ValueError(
|
||||
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
|
||||
"since no orchestrator or inference server will be running."
|
||||
@@ -310,29 +336,38 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weight_broadcast(self):
|
||||
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference."""
|
||||
if self.weight_broadcast is not None:
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
inference_world_size=inference_world_size,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference.
|
||||
|
||||
Defaults to NCCL broadcast when no ``weight_broadcast`` is configured. Falls back to
|
||||
filesystem when LoRA is enabled (not yet supported with NCCL) or when no inference
|
||||
server is configured (NCCL requires a running inference pool).
|
||||
"""
|
||||
if self.weight_broadcast is None:
|
||||
if self.trainer.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig(type="filesystem")
|
||||
else:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
inference_world_size=inference_world_size,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
@@ -537,7 +572,7 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
|
||||
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
|
||||
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
total_infer_gpus = self.deployment.infer_nodes_per_replica * self.deployment.gpus_per_node
|
||||
expected_global_world_size = self.inference.parallel.dp * inference_tp
|
||||
if expected_global_world_size != total_infer_gpus:
|
||||
raise ValueError(
|
||||
@@ -599,12 +634,11 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
infer_deploy = self.inference.deployment
|
||||
expected_infer_nodes = infer_deploy.num_prefill_nodes + infer_deploy.num_decode_nodes
|
||||
if self.deployment.num_infer_nodes != expected_infer_nodes:
|
||||
expected_infer_nodes = infer_deploy.num_nodes
|
||||
if self.deployment.infer_nodes_per_replica != expected_infer_nodes:
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
|
||||
f"inference.deployment.num_prefill_nodes ({infer_deploy.num_prefill_nodes}) + "
|
||||
f"inference.deployment.num_decode_nodes ({infer_deploy.num_decode_nodes}) = {expected_infer_nodes}"
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal the derived "
|
||||
f"disaggregated inference nodes per replica ({expected_infer_nodes})."
|
||||
)
|
||||
|
||||
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
|
||||
@@ -167,10 +167,6 @@ SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class SFTExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class SFTConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
@@ -243,8 +239,6 @@ class SFTConfig(BaseConfig):
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: SFTExperimentalConfig = SFTExperimentalConfig()
|
||||
|
||||
### Pre-validation normalization
|
||||
|
||||
@model_validator(mode="before")
|
||||
|
||||
@@ -58,6 +58,9 @@ class SlurmConfig(BaseConfig):
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
|
||||
|
||||
shared_fs: bool = True
|
||||
"""Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun."""
|
||||
|
||||
@property
|
||||
def template_vars(self) -> dict:
|
||||
"""Common template variables for all SLURM templates."""
|
||||
@@ -71,6 +74,7 @@ class SlurmConfig(BaseConfig):
|
||||
"time": self.time,
|
||||
"pre_run_command": self.pre_run_command,
|
||||
"cleanup_grace_period": self.cleanup_grace_period,
|
||||
"shared_fs": self.shared_fs,
|
||||
}
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -171,6 +171,9 @@ class ModelConfig(BaseModelConfig):
|
||||
reduce_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""dtype for gradient/parameter reductions."""
|
||||
|
||||
moe_router_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""Compute dtype for MoE router gates. ``float32`` (default) keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
|
||||
|
||||
moe_use_grouped_mm: bool = True
|
||||
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
|
||||
|
||||
@@ -649,7 +652,7 @@ class TrainerConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
|
||||
# TODO: Support this
|
||||
# TODO: Support NCCL broadcast with LoRA
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
return self
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
@@ -38,19 +37,3 @@ def rsetattr(obj: Any, attr_path: str, value: Any) -> None:
|
||||
return setattr(obj, attr_path, value)
|
||||
parent_path, attr = attr_path.rsplit(".", 1)
|
||||
setattr(rgetattr(obj, parent_path), attr, value)
|
||||
|
||||
|
||||
def get_all_fields(model: BaseModel | type) -> list[str]:
|
||||
if isinstance(model, BaseModel):
|
||||
model_cls = model.__class__
|
||||
else:
|
||||
model_cls = model
|
||||
|
||||
fields = []
|
||||
for name, field in model_cls.model_fields.items():
|
||||
field_type = field.annotation
|
||||
fields.append(name)
|
||||
if field_type is not None and hasattr(field_type, "model_fields"):
|
||||
sub_fields = get_all_fields(field_type)
|
||||
fields.extend(f"{name}.{sub}" for sub in sub_fields)
|
||||
return fields
|
||||
|
||||
@@ -317,14 +317,11 @@ def validate_shared_weight_broadcast(
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
if (
|
||||
inference
|
||||
and trainer.weight_broadcast.type != orchestrator.weight_broadcast.type != inference.weight_broadcast.type
|
||||
):
|
||||
raise ValueError(
|
||||
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
|
||||
)
|
||||
elif trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
|
||||
if trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
|
||||
raise ValueError(
|
||||
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
|
||||
)
|
||||
if inference is not None and inference.weight_broadcast.type != trainer.weight_broadcast.type:
|
||||
raise ValueError(
|
||||
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
|
||||
)
|
||||
|
||||
+17
-14
@@ -19,9 +19,10 @@ dependencies = [
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers==5.6.2",
|
||||
"vllm>=0.23.0",
|
||||
"vllm>=0.24.0",
|
||||
"mooncake-transfer-engine>=0.3.10.post2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.6.4",
|
||||
"pyzmq>=27.1.0",
|
||||
@@ -54,7 +55,7 @@ orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
@@ -72,13 +73,13 @@ envs = [
|
||||
"alphabet-sort",
|
||||
"alphabet-sort-v1",
|
||||
"apex-shortlist-v1",
|
||||
"arxivmath-v1",
|
||||
"browsecomp-v1",
|
||||
"code-golf-v1",
|
||||
"color-codeword-v1",
|
||||
"deepdive-v1",
|
||||
"deepwiki-v1",
|
||||
"forth-lang-v1",
|
||||
"general-agent",
|
||||
"general-agent-v1",
|
||||
"glossary-v1",
|
||||
"gpqa-v1",
|
||||
@@ -112,7 +113,7 @@ envs = [
|
||||
"redsearcher-v1",
|
||||
"reverse-text",
|
||||
"reverse-text-v1",
|
||||
"rlm-search",
|
||||
"s1-deepresearch-v1",
|
||||
"scaleswe-v1",
|
||||
"simpleqa-v1",
|
||||
"simpleqa-verified-v1",
|
||||
@@ -121,6 +122,7 @@ envs = [
|
||||
"swelego-v1",
|
||||
"tau2-bench-v1",
|
||||
"terminal-bench-2-v1",
|
||||
"tmax-v1",
|
||||
"unscramble-v1",
|
||||
"uuid-ctf-v1",
|
||||
"verbatim-copy-v1",
|
||||
@@ -245,13 +247,13 @@ aime26-v1 = { path = "deps/research-environments/environments/aime26_v1", editab
|
||||
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
|
||||
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
|
||||
apex-shortlist-v1 = { path = "deps/research-environments/environments/apex_shortlist_v1", editable = true }
|
||||
arxivmath-v1 = { path = "deps/research-environments/environments/arxivmath_v1", editable = true }
|
||||
browsecomp-v1 = { path = "deps/research-environments/environments/browsecomp_v1", editable = true }
|
||||
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
|
||||
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
|
||||
deepdive-v1 = { path = "deps/research-environments/environments/deepdive_v1", editable = true }
|
||||
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
|
||||
forth-lang-v1 = { path = "deps/research-environments/environments/forth_lang_v1", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
|
||||
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
|
||||
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
|
||||
@@ -281,19 +283,20 @@ openthoughts-tblite-v1 = { path = "deps/research-environments/environments/opent
|
||||
papersearchqa-v1 = { path = "deps/research-environments/environments/papersearchqa_v1", editable = true }
|
||||
patterned-needle-in-haystack-v1 = { path = "deps/research-environments/environments/patterned_needle_in_haystack_v1", editable = true }
|
||||
prolog-v1 = { path = "deps/research-environments/environments/prolog_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/research-environments/environments/swe/r2e_gym_v1", editable = true }
|
||||
redsearcher-v1 = { path = "deps/research-environments/environments/redsearcher_v1", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_v1", editable = true }
|
||||
s1-deepresearch-v1 = { path = "deps/research-environments/environments/s1_deepresearch_v1", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/swe/scaleswe_v1", editable = true }
|
||||
simpleqa-v1 = { path = "deps/research-environments/environments/simpleqa_v1", editable = true }
|
||||
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_v1", editable = true }
|
||||
swebench-pro-v1 = { path = "deps/research-environments/environments/swebench_pro_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", editable = true }
|
||||
swebench-pro-v1 = { path = "deps/research-environments/environments/swe/swebench_pro_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/research-environments/environments/swe/swebench_verified_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/research-environments/environments/swe/swelego_v1", editable = true }
|
||||
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", editable = true }
|
||||
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
|
||||
tmax-v1 = { path = "deps/research-environments/environments/tmax_v1", editable = true }
|
||||
unscramble-v1 = { path = "deps/research-environments/environments/unscramble_v1", editable = true }
|
||||
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
|
||||
verbatim-copy-v1 = { path = "deps/research-environments/environments/verbatim_copy_v1", editable = true }
|
||||
@@ -306,13 +309,13 @@ wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
|
||||
@@ -34,6 +34,8 @@ Default cadence: **1 hour** (researcher can override). At each check-in:
|
||||
**Notes**: anything unusual (errors, restarts, hangs). Omit if nothing notable.
|
||||
```
|
||||
|
||||
In W&B, each project auto-gets an **"overview" saved view** (train / eval / stability / performance sections) on its first run — use it for a quick check instead of the auto-generated default workspace.
|
||||
|
||||
### Restarting a run
|
||||
|
||||
**Never restart unless the researcher explicitly asked.** Confirm the exact restart command and the conditions that warrant one.
|
||||
@@ -56,7 +58,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the output dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
|
||||
- `{output_dir}/configs/` — resolved TOMLs (`rl.toml` has the full picture).
|
||||
- `{output_dir}/logs/` — see below.
|
||||
- `{output_dir}/rollouts/step_N/` — saved rollouts.
|
||||
- `{output_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
|
||||
|
||||
### Logs
|
||||
|
||||
@@ -128,21 +130,28 @@ curl -s http://localhost:8000/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
|
||||
```
|
||||
|
||||
### Rollouts
|
||||
### Traces
|
||||
|
||||
```
|
||||
{output_dir}/rollouts/step_N/
|
||||
├── train_rollouts.jsonl # all train rollouts (vf.RolloutOutput, trajectory excluded)
|
||||
├── eval_rollouts.jsonl # only present when eval ran
|
||||
└── train_rollouts.bin # binary batch consumed by the trainer
|
||||
{output_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
|
||||
{output_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
```
|
||||
|
||||
JSONL files of `vf.Trace` records (training tensors excluded). `all` gets every completed
|
||||
rollout the moment it arrives — errored, filtered, and never-batched ones included — so it's
|
||||
crash-durable; `effective` gets the clean subset that went into the step's train batch (eval:
|
||||
the non-errored epoch cohort; multiple eval envs share the step file). Each record carries
|
||||
`kind`, `env_name`, `group_id`, `policy_version`, and `eval_step`, plus `runtime` (config +
|
||||
provisioned resource id, e.g. the sandbox id).
|
||||
|
||||
```bash
|
||||
wc -l {output_dir}/rollouts/step_42/train_rollouts.jsonl
|
||||
head -1 {output_dir}/rollouts/step_42/train_rollouts.jsonl | python -m json.tool
|
||||
jq '.reward' {output_dir}/rollouts/step_42/train_rollouts.jsonl
|
||||
wc -l {output_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
|
||||
jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.errors != []) | {id, env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The binary batches consumed by the trainer still live at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
A few warnings are normal. Escalate when errors are persistent, growing, or hit a large fraction of rollouts.
|
||||
|
||||
@@ -76,6 +76,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
template_vars.update(
|
||||
num_prefill_nodes=config.deployment.num_prefill_nodes,
|
||||
num_decode_nodes=config.deployment.num_decode_nodes,
|
||||
prefill_nodes_per_replica=config.deployment.prefill_nodes_per_replica,
|
||||
decode_nodes_per_replica=config.deployment.decode_nodes_per_replica,
|
||||
num_prefill_replicas=config.deployment.num_prefill_replicas,
|
||||
num_decode_replicas=config.deployment.num_decode_replicas,
|
||||
prefill_port=config.deployment.prefill_port,
|
||||
|
||||
@@ -410,6 +410,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
num_prefill_nodes=infer_deploy.num_prefill_nodes,
|
||||
num_decode_nodes=infer_deploy.num_decode_nodes,
|
||||
prefill_nodes_per_replica=infer_deploy.prefill_nodes_per_replica,
|
||||
decode_nodes_per_replica=infer_deploy.decode_nodes_per_replica,
|
||||
num_prefill_replicas=infer_deploy.num_prefill_replicas,
|
||||
num_decode_replicas=infer_deploy.num_decode_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
@@ -441,11 +443,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
orchestrator_output_dir=config.orchestrator.output_dir,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.num_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
|
||||
infer_nodes_per_replica=config.deployment.num_infer_nodes,
|
||||
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
|
||||
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
|
||||
inference_tp=config.inference.parallel.tp if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
@@ -496,7 +498,7 @@ def rl_slurm(config: RLConfig):
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
|
||||
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
|
||||
|
||||
has_infer = config.deployment.num_infer_nodes > 0
|
||||
has_infer = config.deployment.infer_nodes_per_replica > 0
|
||||
log_message = format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
|
||||
+173
-226
@@ -3,20 +3,19 @@ import torch
|
||||
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
|
||||
|
||||
|
||||
def transformers_v5_compat():
|
||||
"""vLLM general plugin: patch transformers v5 config attrs that vLLM still expects.
|
||||
def apply_shared_vllm_patches():
|
||||
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
|
||||
|
||||
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
|
||||
in every vLLM process, including spawned workers.
|
||||
in every vLLM process, including spawned workers. Note vLLM swallows plugin
|
||||
load failures (``load_plugins_by_group`` logs and continues), so a broken
|
||||
entry-point target silently skips ALL of these patches.
|
||||
"""
|
||||
from transformers import Qwen3VLMoeTextConfig
|
||||
|
||||
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
_patch_lora_key_prefix()
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_qwen3_coder_param_newline_trim()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
@@ -100,6 +99,91 @@ def monkey_patch_nano_v3_reasoning_parser():
|
||||
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
|
||||
|
||||
|
||||
def monkey_patch_qwen3_coder_param_newline_trim():
|
||||
"""Restore vLLM 0.23's single-newline trim for qwen3_coder tool parameters.
|
||||
|
||||
vLLM 0.24's parser engine applies a full ``.strip()`` to every parameter
|
||||
value in ``_qwen3_arg_converter``; 0.23's ``Qwen3CoderToolParser`` trimmed
|
||||
exactly one leading and one trailing newline. A full strip corrupts
|
||||
whitespace-significant string parameters (str_replace-style
|
||||
``old_str``/``new_str``, file content with an indented first line, values
|
||||
with intentional trailing newlines), silently changing tool execution and
|
||||
rewards for agentic runs. Copy of ``_qwen3_arg_converter`` with only the
|
||||
trim changed. Also covers ``nemotron_v3``, which reuses ``qwen3_config``.
|
||||
"""
|
||||
import json
|
||||
|
||||
from vllm.parser import qwen3
|
||||
|
||||
def _trim_one_newline(value: str) -> str:
|
||||
if value.startswith("\n"):
|
||||
value = value[1:]
|
||||
if value.endswith("\n"):
|
||||
value = value[:-1]
|
||||
return value
|
||||
|
||||
def _patched_arg_converter(raw_args: str, partial: bool) -> str:
|
||||
params: dict[str, object] = {}
|
||||
|
||||
for match in qwen3._PARAM_RE.finditer(raw_args):
|
||||
name = match.group(1)
|
||||
value = match.group(2)
|
||||
## START PATCHED CODE (upstream: value.strip())
|
||||
params[name] = _trim_one_newline(value)
|
||||
## END PATCHED CODE
|
||||
|
||||
if partial:
|
||||
remaining = qwen3._PARAM_RE.sub("", raw_args)
|
||||
m = qwen3._PARTIAL_PARAM_RE.search(remaining)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
value = m.group(2)
|
||||
if name:
|
||||
## START PATCHED CODE (upstream: value.strip())
|
||||
params[name] = _trim_one_newline(value)
|
||||
## END PATCHED CODE
|
||||
|
||||
return json.dumps(params, ensure_ascii=False)
|
||||
|
||||
qwen3._qwen3_arg_converter = _patched_arg_converter
|
||||
# qwen3_config captures the converter when first built; drop any cached configs.
|
||||
qwen3.qwen3_config.cache_clear()
|
||||
|
||||
|
||||
def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
"""Keep the literal ``</think>`` in MiniMax-M2 content on tool-calling turns.
|
||||
|
||||
prime-rl serves MiniMax-M2 with ``reasoning=minimax_m2_append_think``, which
|
||||
returns content as ``<think>`` + the full completion so think tags round-trip
|
||||
through multi-turn re-serialization. vLLM 0.24's minimax_m2 parser engine
|
||||
added a ``(CONTENT, THINK_END) -> no-events`` transition that silently
|
||||
swallows the ``</think>`` (0.23's regex tool parser passed it through
|
||||
untouched), and it also ``.strip()``s content whenever tool calls are
|
||||
present. Drop the transition — the engine emits unmatched terminals as plain
|
||||
state content — and disable the content strip.
|
||||
"""
|
||||
import dataclasses
|
||||
import functools
|
||||
|
||||
from vllm.parser import minimax_m2
|
||||
from vllm.parser.engine.parser_engine_config import ParserState
|
||||
|
||||
original_config = minimax_m2.minimax_m2_config
|
||||
|
||||
@functools.cache
|
||||
def _patched_config():
|
||||
config = original_config()
|
||||
transitions = dict(config.transitions)
|
||||
del transitions[(ParserState.CONTENT, "THINK_END")]
|
||||
return dataclasses.replace(
|
||||
config,
|
||||
transitions=transitions,
|
||||
strip_content_whitespace_with_tools=False,
|
||||
)
|
||||
|
||||
minimax_m2.minimax_m2_config = _patched_config
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
@@ -185,7 +269,7 @@ def monkey_patch_strip_routed_experts_from_chat():
|
||||
def _patch_qwen35_moe_lora_format():
|
||||
"""Force Qwen3.5-MoE onto vLLM's 2D per-expert LoRA format.
|
||||
|
||||
vLLM 0.23.0 defaults ``Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = True``,
|
||||
vLLM 0.24.0 still defaults ``Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = True``,
|
||||
which makes the LoRA loader expect 3D stacked-expert adapters
|
||||
(``base_layer.lora_{A,B}.weight`` / ``lora_{A,B}.weight``, experts folded into the
|
||||
rank dim; see ``_stack_moe_lora_weights``). Our trainer instead emits the 2D
|
||||
@@ -206,16 +290,23 @@ def _patch_qwen35_moe_lora_format():
|
||||
|
||||
|
||||
def _patch_lora_key_prefix():
|
||||
"""Patch vLLM's LoRA loading to handle keys without base_model.model. prefix.
|
||||
"""Accept both bare-suffix and fully-qualified expert module names in LoRA adapters.
|
||||
|
||||
This is a copy of the upstream patch: https://github.com/vllm-project/vllm/pull/38522
|
||||
We can remove this patch once that PR makes it into a release.
|
||||
Copy of vLLM 0.24.0's ``LoRAModel.from_local_checkpoint`` with one change: the
|
||||
``.experts`` branch of ``check_unexpected_modules`` accepts either the bare suffix
|
||||
(``down_proj``) or the qualified per-expert name (``experts.N.down_proj``), where
|
||||
upstream only accepts the qualified form. Our trainer's 2D per-expert adapters
|
||||
(Qwen3.5-MoE) carry names whose qualified form is not in the expected set while
|
||||
the bare suffix is; Qwen3-30B-A3B adapters go the other way. Upstream fix
|
||||
vllm-project/vllm#38522 was closed unmerged, so this stays.
|
||||
"""
|
||||
from vllm.lora.lora_model import (
|
||||
LoRAModel,
|
||||
MoEEPLoadSpec,
|
||||
PEFTHelper,
|
||||
TensorizerConfig,
|
||||
WeightsMapper,
|
||||
_is_remote_expert_key,
|
||||
get_lora_id,
|
||||
is_base_embedding_weights,
|
||||
os,
|
||||
@@ -236,6 +327,7 @@ def _patch_lora_key_prefix():
|
||||
weights_mapper: WeightsMapper | None = None,
|
||||
tensorizer_config_dict: dict | None = None,
|
||||
skip_prefixes: list[str] | None = None,
|
||||
moe_ep_spec: MoEEPLoadSpec | None = None,
|
||||
) -> "LoRAModel":
|
||||
"""Create a LoRAModel from a local checkpoint.
|
||||
|
||||
@@ -251,6 +343,11 @@ def _patch_lora_key_prefix():
|
||||
skip_prefixes: List of module name prefixes to skip during loading.
|
||||
Models can define this to skip modules not used in inference
|
||||
(e.g., MTP layers). Format: ["mtp."]
|
||||
moe_ep_spec: When 2D FusedMoE LoRA modules are present with
|
||||
expert parallelism enabled, the (ep_rank, local, global)
|
||||
slicing metadata shared across all MoE layers. Non-local
|
||||
expert weights are skipped at read time instead of being
|
||||
loaded and discarded later.
|
||||
|
||||
Returns:
|
||||
Loaded LoRA Model.
|
||||
@@ -275,22 +372,13 @@ def _patch_lora_key_prefix():
|
||||
continue
|
||||
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
|
||||
# Case for expert lora weights.
|
||||
# For standard MoE models the name ends in "...experts",
|
||||
# so expert_idx+1 yields "experts" which is in
|
||||
# expected_lora_modules.
|
||||
# For Qwen 3.5 MoE (and similar models) the expert index
|
||||
# is embedded: "...experts.N.down_proj". Taking everything
|
||||
# after ".experts" gives "experts.N.down_proj" which is
|
||||
# never in the expected set even though "down_proj" is.
|
||||
# Qwen3-30B-A3B goes the other way: the expected set
|
||||
# contains the fully-qualified per-expert name
|
||||
# ("experts.N.down_proj") but not the bare suffix.
|
||||
# Accept either form.
|
||||
## START PATCHED CODE (upstream only accepts the qualified form)
|
||||
if ".experts" in module_name:
|
||||
expert_suffix = module_name.split(".")[-1]
|
||||
experts_qualified = "experts" + module_name.split(".experts", 1)[-1]
|
||||
if expert_suffix not in expected_lora_modules and experts_qualified not in expected_lora_modules:
|
||||
unexpected_modules.append(module_name)
|
||||
## END PATCHED CODE
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
unexpected_modules.append(module_name)
|
||||
@@ -307,11 +395,15 @@ def _patch_lora_key_prefix():
|
||||
from tensorizer import TensorDeserializer
|
||||
|
||||
tensorizer_config = TensorizerConfig(**tensorizer_config_dict)
|
||||
lora_tensor_path = os.path.join(tensorizer_config.tensorizer_dir, "adapter_model.tensors")
|
||||
tensorizer_dir = tensorizer_config.tensorizer_dir
|
||||
if tensorizer_dir is None:
|
||||
raise ValueError("tensorizer_dir must be set in tensorizer config.")
|
||||
lora_tensor_path = os.path.join(tensorizer_dir, "adapter_model.tensors")
|
||||
tensorizer_args = tensorizer_config._construct_tensorizer_args()
|
||||
tensors = TensorDeserializer(
|
||||
lora_tensor_path,
|
||||
dtype=tensorizer_config.dtype,
|
||||
device=device,
|
||||
**tensorizer_args.deserialization_kwargs,
|
||||
)
|
||||
check_unexpected_modules(tensors)
|
||||
@@ -328,11 +420,18 @@ def _patch_lora_key_prefix():
|
||||
# Load tensors if there are only expected modules.
|
||||
check_unexpected_modules(f)
|
||||
for module in f.keys(): # noqa
|
||||
if moe_ep_spec is not None and _is_remote_expert_key(module, moe_ep_spec):
|
||||
continue
|
||||
tensors[module] = f.get_tensor(module)
|
||||
elif os.path.isfile(lora_bin_file_path) or os.path.isfile(lora_pt_file_path):
|
||||
lora_file_path = lora_bin_file_path if os.path.isfile(lora_bin_file_path) else lora_pt_file_path
|
||||
tensors = torch.load(lora_file_path, map_location=device, weights_only=True)
|
||||
check_unexpected_modules(tensors)
|
||||
if moe_ep_spec is not None:
|
||||
# `.bin`/`.pt` adapters can't be lazy-loaded, but pruning
|
||||
# the dict here still frees the non-local expert tensors
|
||||
# before the dtype cast / pin_memory work that follows.
|
||||
tensors = {k: v for k, v in tensors.items() if not _is_remote_expert_key(k, moe_ep_spec)}
|
||||
else:
|
||||
raise ValueError(f"{lora_dir} doesn't contain tensors")
|
||||
|
||||
@@ -350,177 +449,6 @@ def _patch_lora_key_prefix():
|
||||
LoRAModel.from_local_checkpoint = classmethod(_patched_from_local_checkpoint)
|
||||
|
||||
|
||||
# Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
|
||||
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
def monkey_patch_load_lora_adapter():
|
||||
from http import HTTPStatus
|
||||
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.openai.models.serving import (
|
||||
OpenAIServingModels,
|
||||
create_error_response,
|
||||
)
|
||||
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
async def _patched_load_lora_adapter(
|
||||
self: OpenAIServingModels, request: LoadLoRAAdapterRequest, base_model_name: str | None = None
|
||||
) -> ErrorResponse | str:
|
||||
lora_name = request.lora_name
|
||||
|
||||
# Ensure atomicity based on the lora name
|
||||
async with self.lora_resolver_lock[lora_name]:
|
||||
lora_path = request.lora_path
|
||||
## START PATCHED CODE
|
||||
if lora_name in self.lora_requests:
|
||||
lora_request = self.lora_requests[lora_name]
|
||||
lora_request.lora_path = lora_path
|
||||
else:
|
||||
unique_id = self.lora_id_counter.inc(1)
|
||||
lora_request = LoRARequest(lora_name=lora_name, lora_int_id=unique_id, lora_path=lora_path)
|
||||
## END PATCHED CODE
|
||||
if base_model_name is not None and self.is_base_model(base_model_name):
|
||||
lora_request.base_model_name = base_model_name
|
||||
|
||||
# Validate that the adapter can be loaded into the engine
|
||||
# This will also preload it for incoming requests
|
||||
try:
|
||||
await self.engine_client.add_lora(lora_request)
|
||||
except Exception as e:
|
||||
error_type = "BadRequestError"
|
||||
status_code = HTTPStatus.BAD_REQUEST
|
||||
if "No adapter found" in str(e):
|
||||
error_type = "NotFoundError"
|
||||
status_code = HTTPStatus.NOT_FOUND
|
||||
|
||||
return create_error_response(message=str(e), err_type=error_type, status_code=status_code)
|
||||
|
||||
self.lora_requests[lora_name] = lora_request
|
||||
logger.info("Loaded new LoRA adapter: name '%s', path '%s'", lora_name, lora_path)
|
||||
return f"Success: LoRA adapter '{lora_name}' added successfully."
|
||||
|
||||
OpenAIServingModels.load_lora_adapter = _patched_load_lora_adapter
|
||||
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
def monkey_patch_LRUCacheWorkerLoRAManager():
|
||||
from vllm.lora.worker_manager import LoRARequest, LRUCacheLoRAModelManager, LRUCacheWorkerLoRAManager
|
||||
|
||||
# The dunder is intended. It's a private method that we're patching.
|
||||
def _patched__apply_adapters(self: LRUCacheWorkerLoRAManager, lora_requests: set[LoRARequest]) -> None:
|
||||
loras_map = {lora_request.lora_int_id: lora_request for lora_request in lora_requests if lora_request}
|
||||
if len(loras_map) > self._adapter_manager.lora_slots:
|
||||
raise RuntimeError(
|
||||
f"Number of requested LoRAs ({len(loras_map)}) is greater "
|
||||
"than the number of GPU LoRA slots "
|
||||
f"({self._adapter_manager.lora_slots})."
|
||||
)
|
||||
for lora in loras_map.values():
|
||||
## START PATCHED CODE
|
||||
self.add_adapter(lora, force_load=False)
|
||||
## END PATCHED CODE
|
||||
|
||||
def _patched_add_adapter(
|
||||
self: LRUCacheWorkerLoRAManager, lora_request: LoRARequest, force_load: bool = True
|
||||
) -> bool:
|
||||
# Note that this method is not thread-safe. It may be invoked multiple
|
||||
# times for the same adapter when using multiple API servers.
|
||||
# This is ok because it's currently only called from
|
||||
# the single-threaded core engine loop.
|
||||
|
||||
## START PATCHED CODE
|
||||
if lora_request.lora_int_id not in self.list_adapters() or force_load:
|
||||
## END PATCHED CODE
|
||||
# Load the new adapter first to ensure it is actually valid, before
|
||||
# evicting any existing adapters.
|
||||
# This may cause the # of loaded lora adapters to very temporarily
|
||||
# exceed `--max-cpu-loras`.
|
||||
lora = self._load_adapter(lora_request)
|
||||
## START PATCHED CODE
|
||||
self._adapter_manager.remove_adapter(lora.id)
|
||||
## END PATCHED CODE
|
||||
|
||||
# Loading succeeded, now check if we will exceed cache capacity and
|
||||
# evict if the oldest adapter if so
|
||||
if len(self._adapter_manager) + 1 > self._adapter_manager.capacity:
|
||||
assert isinstance(self._adapter_manager, LRUCacheLoRAModelManager)
|
||||
self._adapter_manager.remove_oldest_adapter()
|
||||
# Then add the new adapter to the cache
|
||||
loaded = self._adapter_manager.add_adapter(lora)
|
||||
else:
|
||||
# If the lora is already loaded, just touch it to
|
||||
# update its position in the caches
|
||||
loaded = self._adapter_manager.get_adapter(lora_request.lora_int_id) is not None
|
||||
self._adapter_manager.activate_adapter(lora_request.lora_int_id)
|
||||
return loaded
|
||||
|
||||
LRUCacheWorkerLoRAManager._apply_adapters = _patched__apply_adapters
|
||||
LRUCacheWorkerLoRAManager.add_adapter = _patched_add_adapter
|
||||
|
||||
|
||||
# Monkeypatch WorkerLoRAManager._load_adapter to skip the per-module regex
|
||||
# warning loop. On wide MoE models (Qwen3.5-35B-A3B) it spends minutes
|
||||
# recompiling regex patterns inside is_supported_lora_module — purely to emit
|
||||
# logger.warning_once about modules that will be ignored. Adapter validity is
|
||||
# already enforced by from_local_checkpoint, so dropping the warnings is safe.
|
||||
def monkey_patch_skip_lora_module_warnings():
|
||||
from vllm.exceptions import LoRAAdapterNotFoundError
|
||||
from vllm.lora.lora_model import LoRAModel
|
||||
from vllm.lora.peft_helper import PEFTHelper
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.lora.utils import get_adapter_absolute_path
|
||||
from vllm.lora.worker_manager import WorkerLoRAManager
|
||||
|
||||
def _patched_load_adapter(self: WorkerLoRAManager, lora_request: LoRARequest) -> LoRAModel:
|
||||
try:
|
||||
supported_lora_modules = self._adapter_manager.supported_lora_modules
|
||||
packed_modules_mapping = self._adapter_manager.packed_modules_mapping
|
||||
expected_lora_lst: list[str] = []
|
||||
for module in supported_lora_modules:
|
||||
if module in packed_modules_mapping:
|
||||
expected_lora_lst.extend(packed_modules_mapping[module])
|
||||
else:
|
||||
expected_lora_lst.append(module)
|
||||
if module == "experts":
|
||||
expected_lora_lst.append(module)
|
||||
expected_lora_modules = set(expected_lora_lst)
|
||||
lora_path = get_adapter_absolute_path(lora_request.lora_path)
|
||||
|
||||
peft_helper = PEFTHelper.from_local_dir(
|
||||
lora_path,
|
||||
self.max_position_embeddings,
|
||||
lora_request.tensorizer_config_dict,
|
||||
)
|
||||
peft_helper.validate_legal(self.lora_config)
|
||||
|
||||
model = self._adapter_manager.model
|
||||
hf_to_vllm_mapper = getattr(model, "hf_to_vllm_mapper", None)
|
||||
lora_skip_prefixes = getattr(model, "lora_skip_prefixes", None)
|
||||
|
||||
lora = self._lora_model_cls.from_local_checkpoint(
|
||||
lora_path,
|
||||
expected_lora_modules,
|
||||
peft_helper=peft_helper,
|
||||
lora_model_id=lora_request.lora_int_id,
|
||||
device="cpu",
|
||||
dtype=self.lora_config.lora_dtype,
|
||||
model_vocab_size=self.vocab_size,
|
||||
tensorizer_config_dict=lora_request.tensorizer_config_dict,
|
||||
weights_mapper=hf_to_vllm_mapper,
|
||||
skip_prefixes=lora_skip_prefixes,
|
||||
)
|
||||
except FileNotFoundError as e:
|
||||
raise LoRAAdapterNotFoundError(lora_request.lora_name, lora_request.lora_path) from e
|
||||
|
||||
return lora
|
||||
|
||||
WorkerLoRAManager._load_adapter = _patched_load_adapter
|
||||
|
||||
|
||||
# Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
def monkey_patch_tokenize_params_validation():
|
||||
"""
|
||||
@@ -608,7 +536,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
asserts inputs are float16/bfloat16. Qwen3 MoE doesn't have this
|
||||
problem because its gate uses the model dtype.
|
||||
Fix: rebuild the gate as GateLinear with a bf16 weight (out_dtype=float32
|
||||
keeps fp32 router logits). vLLM 0.23.0's own forward already drops the
|
||||
keeps fp32 router logits). vLLM 0.24.0's own forward already drops the
|
||||
float32 input cast. FusedMoE also has router_logits_dtype=float32, so
|
||||
routing precision is preserved inside the expert dispatch.
|
||||
|
||||
@@ -634,7 +562,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
_original_init(self, config, quant_config, prefix)
|
||||
from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear
|
||||
|
||||
# vLLM 0.23.0 builds the gate as GateLinear with a float32 weight; rebuild it
|
||||
# vLLM 0.24.0 builds the gate as GateLinear with a float32 weight; rebuild it
|
||||
# with a bf16 weight (model dtype) so the LoRA Triton kernel's float16/bfloat16
|
||||
# assertion passes, keeping out_dtype=float32 so router logits stay fp32 (the
|
||||
# GateLinear bf16xbf16->fp32 path).
|
||||
@@ -646,19 +574,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
prefix=f"{prefix}.gate",
|
||||
)
|
||||
|
||||
def _patched_forward(self, hidden_states):
|
||||
from vllm.distributed import tensor_model_parallel_all_reduce
|
||||
|
||||
num_tokens, hidden_dim = hidden_states.shape
|
||||
hidden_states = hidden_states.view(-1, hidden_dim)
|
||||
router_logits, _ = self.gate(hidden_states)
|
||||
final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=router_logits)
|
||||
if self.tp_size > 1:
|
||||
final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)
|
||||
return final_hidden_states.view(num_tokens, hidden_dim)
|
||||
|
||||
MiniMaxM2MoE.__init__ = _patched_init
|
||||
MiniMaxM2MoE.forward = _patched_forward
|
||||
|
||||
# --- Adapter key remapping (only read by vLLM's LoRA adapter loader) ---
|
||||
MiniMaxM2ForCausalLM.hf_to_vllm_mapper = WeightsMapper(
|
||||
@@ -703,23 +619,15 @@ def monkey_patch_no_moe_lora():
|
||||
Otherwise, the oracle will always try to pick TritonExperts.
|
||||
For blackwells, we want TRTLLMFlashInfer.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig, logger
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig
|
||||
|
||||
original_post_init = FusedMoEConfig.__post_init__
|
||||
|
||||
def _patched__post_init__(self: FusedMoEConfig):
|
||||
if self.dp_size > 1:
|
||||
logger.debug_once("Using FusedMoEConfig::max_num_tokens=%d", self.max_num_tokens)
|
||||
|
||||
assert self.max_num_tokens > 0
|
||||
|
||||
if self.router_logits_dtype is None:
|
||||
self.router_logits_dtype = self.in_dtype
|
||||
|
||||
if self.hidden_dim_unpadded is None:
|
||||
self.hidden_dim_unpadded = self.hidden_dim
|
||||
if self.intermediate_size_per_partition_unpadded is None:
|
||||
self.intermediate_size_per_partition_unpadded = self.intermediate_size_per_partition
|
||||
|
||||
# Disable LoRA for MoE layers
|
||||
original_post_init(self)
|
||||
# Disable LoRA for MoE layers. `is_lora_enabled` is only read later during
|
||||
# kernel selection (modular_kernel / unquantized oracle), never inside
|
||||
# `__post_init__`, so flipping it after the original runs is sufficient.
|
||||
self.is_lora_enabled = False
|
||||
|
||||
FusedMoEConfig.__post_init__ = _patched__post_init__
|
||||
@@ -787,12 +695,51 @@ def monkey_patch_fp32_lm_head():
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_fp32_router_logits():
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
|
||||
|
||||
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
|
||||
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
|
||||
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
|
||||
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
|
||||
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
|
||||
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
|
||||
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
|
||||
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
|
||||
|
||||
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
|
||||
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
|
||||
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
|
||||
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
|
||||
branch, whose kernel wants matching dtypes).
|
||||
"""
|
||||
import torch
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_original_init = DeepseekV2MoE.__init__
|
||||
|
||||
def _patched_init(self, *args, **kwargs):
|
||||
_original_init(self, *args, **kwargs)
|
||||
additional_config = get_current_vllm_config().additional_config or {}
|
||||
if not additional_config.get("fp32_router_logits", False):
|
||||
return
|
||||
if self.gate.out_dtype is None:
|
||||
self.gate.set_out_dtype(torch.float32)
|
||||
|
||||
DeepseekV2MoE.__init__ = _patched_init
|
||||
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
|
||||
|
||||
The coordinator child process is spawned on the DP-rank-0 API server while
|
||||
every engine-core rank on the node is importing and loading weights, so its
|
||||
own spawn-time re-import can take well over 30s under that CPU/IO
|
||||
own spawn-time re-import can exceed the hard-coded timeout under that CPU/IO
|
||||
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
|
||||
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
|
||||
"""
|
||||
|
||||
@@ -2,7 +2,6 @@ import logging.config
|
||||
import os
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli
|
||||
|
||||
|
||||
def setup_vllm_env(config: InferenceConfig):
|
||||
@@ -11,7 +10,8 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Force the V1 GPU model runner. vLLM 0.23.0 routes dense Llama/Mistral/Qwen3 to the
|
||||
# Force the V1 GPU model runner. vLLM 0.24.0 routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe; the 0.23 MoE/quantized guard was removed) to the
|
||||
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
|
||||
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
|
||||
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
|
||||
@@ -20,6 +20,12 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
# "required"/named and strict tools — a sampling distribution the trainer never
|
||||
# sees. Keep it off so rollout logprobs stay faithful for importance ratios.
|
||||
os.environ.setdefault("VLLM_ENFORCE_STRICT_TOOL_CALLING", "0")
|
||||
|
||||
deep_gemm_enabled = "1" if config.use_deep_gemm else "0"
|
||||
os.environ["VLLM_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
os.environ["VLLM_MOE_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
@@ -41,17 +47,3 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
os.environ["VLLM_CONFIGURE_LOGGING"] = "1"
|
||||
os.environ["VLLM_LOGGING_CONFIG_PATH"] = str(config_path)
|
||||
logging.config.dictConfig(build_dict_config(config.log.level))
|
||||
|
||||
|
||||
def main():
|
||||
config = cli(InferenceConfig)
|
||||
setup_vllm_env(config)
|
||||
|
||||
# We import here to be able to set environment variables before importing vLLM
|
||||
from prime_rl.inference.vllm.server import server # pyright: ignore
|
||||
|
||||
server(config, vllm_extra=config.vllm_extra)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -22,7 +22,6 @@ logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_dp_coordinator_startup_timeout,
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
@@ -32,9 +31,6 @@ from prime_rl.inference.patches import (
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
|
||||
monkey_patch_harmony_stop_token_propagation()
|
||||
# NOTE: Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
|
||||
# May be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
monkey_patch_load_lora_adapter()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
@@ -50,7 +46,7 @@ monkey_patch_vllm_padded_input_scrub()
|
||||
# routed_experts from chat responses since the server-wide enable flag has no
|
||||
# per-request toggle.
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
# NOTE: vLLM hard-codes a 30s DP coordinator startup timeout, which the rank-0
|
||||
# NOTE: vLLM hard-codes a 120s DP coordinator startup timeout, which the rank-0
|
||||
# API server blows through when all engine-core ranks on the node are loading
|
||||
# weights concurrently (multi-node disaggregated deployments).
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
@@ -97,9 +93,29 @@ async def update_weights(request: Request):
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter."""
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter.
|
||||
|
||||
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
|
||||
changes per policy version; the name is constant, see orchestrator.lora_name).
|
||||
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``,
|
||||
so we force it here — that makes the worker re-read the new weights during
|
||||
``add_lora``, reusing the existing ``lora_int_id``.
|
||||
|
||||
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
|
||||
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
|
||||
every generation request; left ``True`` it would force a disk reload on each
|
||||
scheduler step. The orchestrator awaits this endpoint before dispatching
|
||||
rollouts for the new version, so the reset always lands before generation.
|
||||
The reset runs regardless of success/error: vLLM only stores the adapter on
|
||||
success today, but resetting whatever is stored keeps us correct even if a
|
||||
future version were to leave a ``load_inplace=True`` request behind on error.
|
||||
"""
|
||||
handler = models(raw_request)
|
||||
lora_request.load_inplace = True
|
||||
response = await handler.load_lora_adapter(lora_request)
|
||||
stored = handler.lora_requests.get(lora_request.lora_name)
|
||||
if stored is not None:
|
||||
stored.load_inplace = False
|
||||
if isinstance(response, ErrorResponse):
|
||||
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
|
||||
return {"status": "ok"}
|
||||
@@ -150,7 +166,6 @@ async def custom_init_app_state(
|
||||
"""
|
||||
await init_app_state(engine_client, state, args, supported_tasks)
|
||||
|
||||
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
|
||||
state.liveness_timeout_seconds = args.liveness_timeout_seconds
|
||||
|
||||
# Swap in our ServingTokens subclass for /inference/v1/generate so the
|
||||
|
||||
@@ -3,19 +3,13 @@ import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_LRUCacheWorkerLoRAManager,
|
||||
monkey_patch_fp32_router_logits,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
monkey_patch_skip_lora_module_warnings,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
monkey_patch_LRUCacheWorkerLoRAManager()
|
||||
# Skip the per-module regex warning loop in WorkerLoRAManager._load_adapter
|
||||
# (minutes-long stall on wide MoE models like Qwen3.5-35B-A3B)
|
||||
monkey_patch_skip_lora_module_warnings()
|
||||
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
# Disable LoRA on MoE layers so vLLM picks better kernels (e.g. TRTLLMFlashInfer on Blackwell)
|
||||
@@ -27,3 +21,6 @@ else:
|
||||
|
||||
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
|
||||
monkey_patch_fp32_lm_head()
|
||||
|
||||
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
|
||||
monkey_patch_fp32_router_logits()
|
||||
|
||||
@@ -24,42 +24,6 @@ else:
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nccl")
|
||||
|
||||
# NemotronH mixer.D is dropped by vLLM's layerwise online-reload path (left uninitialized).
|
||||
_RELOAD_CORRUPTED_SUFFIXES = (".mixer.D",)
|
||||
|
||||
|
||||
def _restore_reload_corrupted_params(model: Module, received: dict[str, torch.Tensor]) -> None:
|
||||
"""Work around a vLLM layerwise-reload bug for NemotronH (present through vLLM 0.23.0).
|
||||
|
||||
The online reload drops the weight load for every Mamba layer's ``mixer.D`` (the SSD skip
|
||||
connection), leaving it as uninitialized ``empty_strided`` memory -- it reads back as garbage
|
||||
(NaN/inf) and the logits go NaN after a weight update. Root cause: ``mixer.A`` is loaded with
|
||||
``composed_weight_loader`` (an extra in-place transform copy), so the reload element counter
|
||||
double-counts ``A`` and finalizes the layer before ``D`` (loaded last) is loaded. The received
|
||||
broadcast value is correct, so restore D from it via the param's own ``weight_loader``.
|
||||
|
||||
Fixed upstream by vllm-project/vllm#44814 (merged 2026-06-10) but NOT in the pinned 0.23.0
|
||||
release; remove this shim once we bump to a vLLM release that includes it.
|
||||
"""
|
||||
|
||||
def _layer_key(name: str) -> str:
|
||||
index = name.find("layers.")
|
||||
return name[index:] if index >= 0 else name
|
||||
|
||||
received_by_key = {_layer_key(name): tensor for name, tensor in received.items()}
|
||||
for name, param in model.named_parameters():
|
||||
if not name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
|
||||
continue
|
||||
tensor = received_by_key.get(_layer_key(name))
|
||||
if tensor is None:
|
||||
continue
|
||||
tensor = tensor.to(device=param.device)
|
||||
weight_loader = getattr(param, "weight_loader", None)
|
||||
if weight_loader is not None:
|
||||
weight_loader(param, tensor)
|
||||
elif tensor.shape == param.shape:
|
||||
param.data.copy_(tensor.to(param.dtype))
|
||||
|
||||
|
||||
def receive_integer(communicator: PyNcclCommunicator) -> int:
|
||||
"""Receive an integer from the trainer master rank using NCCL communicator."""
|
||||
@@ -184,20 +148,9 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
# vLLM's layerwise reload drops NemotronH mixer.D's weight load (see
|
||||
# _restore_reload_corrupted_params). Capture the correct received value to restore after.
|
||||
received_reload_fix: dict[str, torch.Tensor] = {}
|
||||
|
||||
def _capture_reload_fix(weights):
|
||||
for name, tensor in weights:
|
||||
if name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
|
||||
received_reload_fix[name] = tensor.detach().to("cpu", copy=True)
|
||||
yield name, tensor
|
||||
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
_capture_reload_fix(state_iter),
|
||||
state_iter,
|
||||
self.model_runner.model_config,
|
||||
self.vllm_config,
|
||||
)
|
||||
_restore_reload_corrupted_params(model, received_reload_fix)
|
||||
|
||||
@@ -5,6 +5,7 @@ from torch.nn import Module
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
|
||||
from vllm.model_executor.model_loader.weight_utils import remap_moe_expert_weights
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
|
||||
|
||||
@@ -47,20 +48,20 @@ def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_p
|
||||
return physical_to_logical
|
||||
|
||||
|
||||
def _build_expert_source_indices(module) -> torch.Tensor | None:
|
||||
if module._expert_map is None:
|
||||
def _build_expert_source_indices(routed_experts, router) -> torch.Tensor | None:
|
||||
if routed_experts._expert_map is None:
|
||||
return None
|
||||
|
||||
physical_indices = torch.where(module._expert_map >= 0)[0]
|
||||
local_indices = module._expert_map[physical_indices]
|
||||
physical_indices = torch.where(routed_experts._expert_map >= 0)[0]
|
||||
local_indices = routed_experts._expert_map[physical_indices]
|
||||
physical_indices = physical_indices[local_indices.argsort()]
|
||||
|
||||
eplb_layer_state = getattr(module, "eplb_state", None)
|
||||
eplb_layer_state = getattr(router, "eplb_state", None)
|
||||
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
|
||||
if logical_to_physical_map is None:
|
||||
return physical_indices
|
||||
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, module.global_num_experts)
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, routed_experts.global_num_experts)
|
||||
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
|
||||
if (logical_indices < 0).any():
|
||||
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
|
||||
@@ -70,14 +71,23 @@ def _build_expert_source_indices(module) -> torch.Tensor | None:
|
||||
|
||||
|
||||
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
|
||||
"""Map FusedMoE module names to source expert indices local to this worker."""
|
||||
from vllm.model_executor.layers.fused_moe.layer import FusedMoE
|
||||
"""Map MoE module names to source expert indices local to this worker.
|
||||
|
||||
vLLM 0.24 turned ``FusedMoE`` into a factory returning a ``MoERunner`` and
|
||||
split the state that used to live on the ``FusedMoE`` module: the expert map
|
||||
(``_expert_map`` / ``global_num_experts``) now lives on
|
||||
``MoERunner.routed_experts`` (a ``RoutedExperts``), and the EPLB state on
|
||||
``MoERunner.router``. Keying by the ``MoERunner`` name prefix-matches the
|
||||
nested ``routed_experts.*`` weight params after ``load_weights_kernel``
|
||||
remaps incoming flat names via ``remap_moe_expert_weights``.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe import MoERunner
|
||||
|
||||
source_indices_by_module: dict[str, torch.Tensor] = {}
|
||||
for module_name, module in model.named_modules():
|
||||
if not isinstance(module, FusedMoE):
|
||||
if not isinstance(module, MoERunner):
|
||||
continue
|
||||
source_indices = _build_expert_source_indices(module)
|
||||
source_indices = _build_expert_source_indices(module.routed_experts, module.router)
|
||||
if source_indices is None:
|
||||
continue
|
||||
source_indices_by_module[module_name] = source_indices
|
||||
@@ -94,7 +104,10 @@ def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Te
|
||||
skipped: list[str] = []
|
||||
shape_mismatches: list[str] = []
|
||||
|
||||
for name, tensor in state_iter:
|
||||
# The trainer emits pre-0.24 flat kernel names (``...experts.w13_weight``); since
|
||||
# vLLM 0.24 the expert params are nested (``...experts.routed_experts.w13_weight``).
|
||||
# ``remap_moe_expert_weights`` is upstream's compat shim for exactly this transition.
|
||||
for name, tensor in remap_moe_expert_weights(state_iter, params):
|
||||
if name not in params:
|
||||
skipped.append(name)
|
||||
continue
|
||||
|
||||
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Callable
|
||||
|
||||
from prime_rl.configs.algorithm import EchoAlgoConfig
|
||||
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
from prime_rl.orchestrator.trajectories import iter_trainable_branches
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -55,7 +56,9 @@ class EchoAlgorithm(GRPOAlgorithm):
|
||||
(role tags, separators, tool-response wraps) is excluded. Nodes without
|
||||
attribution (the default renderer, or relay turns with no token ids)
|
||||
fall back to weighting the whole non-sampled span."""
|
||||
trainable_branches = [branch for branch in rollout.branches if any(branch.sampled_mask)]
|
||||
# Same branch selection as ``trace_to_samples``, so the zip with ``rollout.samples``
|
||||
# stays aligned when fork dedup drops a branch.
|
||||
trainable_branches = [branch for branch, _ in iter_trainable_branches(rollout)]
|
||||
filter_masks = self._filter_masks(rollout, trainable_branches) if self.filter_fn is not None else None
|
||||
for sample_idx, (sample, branch) in enumerate(zip(rollout.samples, trainable_branches)):
|
||||
weights = [0.0] * len(sample.token_ids)
|
||||
|
||||
@@ -75,7 +75,7 @@ from prime_rl.utils.client import init_nccl_broadcast
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
|
||||
from prime_rl.utils.pathing import get_log_dir, get_trace_path
|
||||
from prime_rl.utils.usage_reporter import UsageReporter
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
@@ -165,6 +165,8 @@ class Orchestrator:
|
||||
# Trigger timestamps so eval success logs can report epoch duration
|
||||
self.eval_triggered_at = {}
|
||||
self.consecutive_empty_batches = 0
|
||||
self.gate_closed_at = None
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.component_tasks = []
|
||||
|
||||
# Optional attributes — ``setup()`` populates them when the relevant
|
||||
@@ -222,6 +224,8 @@ class Orchestrator:
|
||||
tokenizer=self.tokenizer,
|
||||
run_config=config,
|
||||
keep_full_history=config.bench,
|
||||
train_env_names=[env.resolved_name for env in config.train.env],
|
||||
eval_env_names=[env.resolved_name for env in config.eval.env] if config.eval is not None else [],
|
||||
)
|
||||
|
||||
if config.heartbeat is not None:
|
||||
@@ -305,17 +309,21 @@ class Orchestrator:
|
||||
|
||||
if self.resume_step is not None and self.ckpt_manager is not None:
|
||||
self.ckpt_manager.load(self.progress, step=self.resume_step)
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, self.progress.step, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
config.output_dir, self.resume_step, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.progress.step)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.resume_step)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = self.progress.step
|
||||
self.policy.version = self.resume_step
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
@@ -361,7 +369,7 @@ class Orchestrator:
|
||||
inference=self.policy_inference,
|
||||
observers=[self.dispatcher, self],
|
||||
lora_name=self.lora_name,
|
||||
ckpt_step=self.progress.step,
|
||||
ckpt_step=self.policy.version,
|
||||
)
|
||||
# Single periodic logger for the whole pipeline. It's the only
|
||||
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
|
||||
@@ -407,11 +415,11 @@ class Orchestrator:
|
||||
asyncio.create_task(self.watcher.start(), name="watcher"),
|
||||
]
|
||||
|
||||
# Default step-0 base-model eval — fires before any train rollouts
|
||||
# unless ``eval.skip_first_step=True`` (or this is a resume)
|
||||
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
|
||||
# step, unless ``eval.skip_first_step=True`` (or this is a resume)
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
|
||||
# Anchor step-time clock so step 0 measures startup → first batch
|
||||
# Anchor step-time clock so the first step measures startup → first batch
|
||||
self.last_batch_at = time.perf_counter()
|
||||
|
||||
# ``clean_exit`` stays False if ``main_loop`` raises (signal-driven
|
||||
@@ -428,7 +436,11 @@ class Orchestrator:
|
||||
else:
|
||||
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
|
||||
self.monitor.save_final_summary()
|
||||
if self.ckpt_manager is not None:
|
||||
# ``progress.step`` points at the next (unshipped) step; the last finished step is
|
||||
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
|
||||
# first ship).
|
||||
if self.ckpt_manager is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info("Writing final checkpoint")
|
||||
self.ckpt_manager.save(self.progress, step=self.progress.step)
|
||||
await self.stop()
|
||||
@@ -453,6 +465,18 @@ class Orchestrator:
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
|
||||
# Every completed rollout — errored, filtered, or never batched — lands in the
|
||||
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
|
||||
# Train rollouts belong to the batch window currently collecting (``progress.step``),
|
||||
# eval rollouts to the step whose eval triggered them.
|
||||
step = rollout.eval_step if rollout.kind == "eval" else self.progress.step
|
||||
assert step is not None
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
[rollout.to_record()],
|
||||
get_trace_path(self.config.output_dir, step, rollout.kind, "all"),
|
||||
)
|
||||
|
||||
if rollout.kind == "eval":
|
||||
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
|
||||
eval_batch = self.eval_sink.add(rollout)
|
||||
@@ -481,9 +505,7 @@ class Orchestrator:
|
||||
step_time = (now - self.last_batch_at) if self.last_batch_at is not None else 0.0
|
||||
self.last_batch_at = now
|
||||
|
||||
save_ckpt_time = await self.maybe_save_ckpt(step)
|
||||
|
||||
if config.max_steps is not None and step >= config.max_steps:
|
||||
if config.max_steps is not None and step > config.max_steps:
|
||||
self.draining = True
|
||||
self.dispatcher.disable_train_scheduling()
|
||||
n_cancelled = await self.dispatcher.cancel_inflight_train_rollouts()
|
||||
@@ -514,20 +536,23 @@ class Orchestrator:
|
||||
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
|
||||
)
|
||||
|
||||
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); to_record
|
||||
# drops the per-node training tensors — they're for training, not the rollout record, and
|
||||
# can't round-trip json (raw numpy bytes).
|
||||
rollout_dicts = [r.to_record() for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), step)
|
||||
await asyncio.to_thread(save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl")
|
||||
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
|
||||
# at ship time; the full arrival window already streamed into ``all`` on arrival.
|
||||
# to_record drops the per-node training tensors — they're for training, not the rollout
|
||||
# record, and can't round-trip json (raw numpy bytes).
|
||||
effective = batch.rollouts.effective
|
||||
records = [r.to_record() for r in effective]
|
||||
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
|
||||
|
||||
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
|
||||
self.progress.step += 1
|
||||
self.update_dispatch_gate()
|
||||
# Checkpoint the step we just shipped (resume point: continue at step + 1).
|
||||
save_ckpt_time = await self.maybe_save_ckpt(step)
|
||||
trim_process_memory()
|
||||
|
||||
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
|
||||
# full arrival window (errored + filtered included); ``.effective`` is the clean subset.
|
||||
effective = batch.rollouts.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
|
||||
@@ -554,6 +579,7 @@ class Orchestrator:
|
||||
"progress/total_tasks": self.progress.total_problems,
|
||||
"time/step": step_time,
|
||||
"time/save_ckpt": save_ckpt_time,
|
||||
"time/wait_for_policy": self.wait_for_policy_time,
|
||||
"step": step,
|
||||
}
|
||||
for env_name, env_pool in batch.rollouts.by_env().items():
|
||||
@@ -565,6 +591,7 @@ class Orchestrator:
|
||||
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
|
||||
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
|
||||
self.monitor.log(metrics, step=step)
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.monitor.log_samples(effective.rollouts, step=step)
|
||||
self.monitor.log_distributions(
|
||||
distributions={
|
||||
@@ -592,7 +619,6 @@ class Orchestrator:
|
||||
self.log_train_batch(batch, step=step, step_time=step_time)
|
||||
|
||||
self.train_sink.reset_pre_filter_stats()
|
||||
self.progress.step += 1
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
trim_process_memory()
|
||||
|
||||
@@ -726,12 +752,13 @@ class Orchestrator:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
|
||||
return
|
||||
|
||||
rollout_dicts = [r.to_record() for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(self.config.output_dir), batch.step)
|
||||
# The non-errored subset lands in the per-step ``effective`` trace file on epoch
|
||||
# completion (multiple eval envs share the step file — each epoch appends its cohort
|
||||
# once, and every record carries ``env_name``); the full returned cohort already
|
||||
# streamed into ``all`` on arrival.
|
||||
records = [r.to_record() for r in batch.rollouts.effective]
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
rollout_dicts,
|
||||
step_path / f"eval_rollouts_{batch.env_name}.jsonl",
|
||||
save_rollouts, records, get_trace_path(self.config.output_dir, batch.step, "eval", "effective")
|
||||
)
|
||||
self.monitor.log_eval_samples(batch.rollouts, env_name=batch.env_name, step=batch.step)
|
||||
policy_versions = {r.policy_version for r in batch.rollouts}
|
||||
@@ -764,19 +791,13 @@ class Orchestrator:
|
||||
)
|
||||
|
||||
async def maybe_save_ckpt(self, step: int) -> float:
|
||||
"""Save the checkpoint if we're at an interval boundary. Returns
|
||||
"""Checkpoint the step just shipped if it's an interval boundary. Returns
|
||||
elapsed time (0.0 when no save happened)."""
|
||||
if self.ckpt_manager is None or self.config.ckpt is None or not self.config.ckpt.interval:
|
||||
return 0.0
|
||||
if step <= 0:
|
||||
return 0.0
|
||||
# Skip only the drain-entry step (step == max_steps, which never ships):
|
||||
# it would double-save with the final checkpoint in ``start()`` (also at
|
||||
# progress.step == max_steps). The last *shipped* step (max_steps - 1) is
|
||||
# NOT skipped — the trainer saves there (its is_last_step is max_steps),
|
||||
# so the orchestrator must too or resume from that interval ckpt breaks.
|
||||
near_end = self.config.max_steps is not None and step >= self.config.max_steps
|
||||
if near_end:
|
||||
# The final step's checkpoint is written once in ``start()``'s teardown; skip it here so
|
||||
# we don't double-save. This mirrors the trainer (its is_last_step skips the in-loop save).
|
||||
if self.config.max_steps is not None and step >= self.config.max_steps:
|
||||
return 0.0
|
||||
if step % self.config.ckpt.interval != 0:
|
||||
return 0.0
|
||||
@@ -786,22 +807,37 @@ class Orchestrator:
|
||||
return time.perf_counter() - t
|
||||
|
||||
def update_dispatch_gate(self) -> None:
|
||||
"""Pause/resume the dispatcher based on how far the orchestrator's
|
||||
next batch would run ahead of ``policy.version``. Called from two
|
||||
sites: after shipping a batch (step advances) and from
|
||||
``on_new_version`` (policy advances)."""
|
||||
lead = (self.progress.step + 1) - self.policy.version
|
||||
"""Pause/resume the dispatcher based on how far the in-flight batch runs
|
||||
ahead of ``policy.version``. ``progress.step`` is always the batch being
|
||||
collected — advanced right after shipping — so both call sites (ship time
|
||||
here, policy update in ``on_new_version``) share one lead formula. Steps
|
||||
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
|
||||
count is ``progress.step - 1``."""
|
||||
lead = (self.progress.step - 1) - self.policy.version
|
||||
# The trainer skips the final NCCL weight broadcast (inference group is
|
||||
# torn down), so policy.version never reaches the last step. Without this
|
||||
# the gate deadlocks waiting for a version that will never be published.
|
||||
# The last batch uses the penultimate policy anyway, so let it through.
|
||||
building_final_batch_nccl = (
|
||||
self.config.weight_broadcast.type == "nccl"
|
||||
and self.config.max_steps is not None
|
||||
and self.progress.step >= self.config.max_steps - 1
|
||||
)
|
||||
gate = self.dispatcher.dispatch_allowed
|
||||
was_set = gate.is_set()
|
||||
if lead > TARGET_LAG:
|
||||
if lead > TARGET_LAG and not building_final_batch_nccl:
|
||||
if was_set:
|
||||
get_logger().info(
|
||||
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
|
||||
)
|
||||
self.gate_closed_at = time.perf_counter()
|
||||
gate.clear()
|
||||
else:
|
||||
if not was_set:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
if self.gate_closed_at is not None:
|
||||
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
|
||||
self.gate_closed_at = None
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""TrainSource: weighted round-robin across train envs, infinite pull.
|
||||
|
||||
Weights default to configured ``ratio`` (when every env sets one) or to
|
||||
per-env dataset size. ``next_example`` reshuffles on cursor exhaustion."""
|
||||
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
|
||||
per env). ``next_example`` reshuffles on cursor exhaustion."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -37,11 +37,7 @@ class TrainSource:
|
||||
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
|
||||
|
||||
self.env_names = [e.name for e in self.envs]
|
||||
configured_ratios = [e.config.ratio for e in self.envs]
|
||||
if all(r is not None for r in configured_ratios):
|
||||
self.weights: list[float] = [float(r) for r in configured_ratios] # type: ignore[arg-type]
|
||||
else:
|
||||
self.weights = [float(len(self.examples[name])) for name in self.env_names]
|
||||
self.weights: list[float] = [float(e.config.ratio) for e in self.envs]
|
||||
|
||||
def next_example(self, available_permits: int) -> dict | None:
|
||||
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
|
||||
|
||||
@@ -15,6 +15,8 @@ the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
|
||||
import numpy as np
|
||||
import verifiers.v1 as vf
|
||||
|
||||
@@ -64,6 +66,29 @@ def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExp
|
||||
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
|
||||
|
||||
|
||||
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
|
||||
"""Yield each branch that yields a training sample, with its trainable-token mask.
|
||||
|
||||
The mask is `branch.sampled_mask` except that a sampled node shared by several branches
|
||||
(a mid-trajectory fork) is trainable only in the first branch containing it; later
|
||||
branches carry its tokens as context (mask False). Branches left with no trainable
|
||||
tokens are skipped, so consumers pairing branches with `trace_to_samples` output
|
||||
(e.g. echo's observation weighting) must filter through here to stay aligned.
|
||||
"""
|
||||
trained_nodes: set[int] = set()
|
||||
for branch in trace.branches:
|
||||
mask: list[bool] = []
|
||||
for node in branch.nodes:
|
||||
if node.sampled and any(node.mask) and id(node) in trained_nodes:
|
||||
mask.extend([False] * len(node.mask))
|
||||
else:
|
||||
if node.sampled and any(node.mask):
|
||||
trained_nodes.add(id(node))
|
||||
mask.extend(node.mask)
|
||||
if any(mask):
|
||||
yield branch, mask
|
||||
|
||||
|
||||
def trace_to_samples(
|
||||
trace: vf.Trace,
|
||||
*,
|
||||
@@ -75,17 +100,14 @@ def trace_to_samples(
|
||||
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
|
||||
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
|
||||
the trainable (model-sampled) tokens, the context tokens between completions stay masked
|
||||
out. On a rollout error the whole completion is masked out. A branch carrying images also
|
||||
gets `mm_kwargs` (the concatenated pixel tensors) and `mm_token_type_ids` (the renderer's
|
||||
`mm_token_type_id_map` applied to the branch tokens). Branches with no sampled tokens
|
||||
(e.g. an openai client carrying none) yield nothing.
|
||||
out. Errored rollouts are dropped upstream (`TrainSink.process_rollout`), so no error
|
||||
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
|
||||
pixel tensors) and `mm_token_type_ids` (the renderer's `mm_token_type_id_map` applied to
|
||||
the branch tokens). Branches with no sampled tokens (e.g. an openai client carrying none)
|
||||
yield nothing.
|
||||
"""
|
||||
has_error = trace.has_error
|
||||
samples: list[TrainingSample] = []
|
||||
for branch in trace.branches:
|
||||
mask = branch.sampled_mask
|
||||
if not any(mask):
|
||||
continue
|
||||
for branch, mask in iter_trainable_branches(trace):
|
||||
token_ids = branch.token_ids
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
@@ -97,7 +119,7 @@ def trace_to_samples(
|
||||
samples.append(
|
||||
TrainingSample(
|
||||
token_ids=token_ids,
|
||||
mask=[m and not has_error for m in mask],
|
||||
mask=mask,
|
||||
logprobs=branch.logprobs,
|
||||
temperatures=[], # filled by TrainSink.process_group
|
||||
env_name=env_name,
|
||||
@@ -108,6 +130,6 @@ def trace_to_samples(
|
||||
)
|
||||
if not samples:
|
||||
get_logger().warning(
|
||||
f"No trainable samples (error={has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
|
||||
f"No trainable samples (error={trace.has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
|
||||
)
|
||||
return samples
|
||||
|
||||
@@ -27,9 +27,9 @@ class Policy:
|
||||
|
||||
@dataclass
|
||||
class Progress:
|
||||
"""Persistent counters; ``step`` is the trainer-aligned step."""
|
||||
"""Persistent counters; ``step`` is the trainer-aligned step (1-indexed)."""
|
||||
|
||||
step: int = 0
|
||||
step: int = 1
|
||||
total_tokens: int = 0
|
||||
total_samples: int = 0
|
||||
total_problems: int = 0
|
||||
@@ -73,8 +73,8 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
"""A completed rollout: the env's typed ``vf.Trace`` *is* the rollout — prime-rl's
|
||||
orchestration metadata lives on it directly (set by the dispatcher once the rollout
|
||||
returns), so there's no wrapper. Train vs eval is the ``kind`` discriminator. All metadata
|
||||
fields are ``exclude=True``, so dumping a Rollout yields a plain trace — the on-disk
|
||||
``results.jsonl`` is unchanged.
|
||||
fields are ``exclude=True``, so dumping a Rollout yields a plain trace on the wire;
|
||||
:meth:`to_record` adds the small metadata fields back for the on-disk trace files.
|
||||
|
||||
It is also the single currency the scoring hooks receive: a hook reads the trace
|
||||
directly (``rollout.reward``, ``rollout.nodes``, ``rollout.num_turns``) and writes
|
||||
@@ -98,6 +98,19 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
|
||||
eval_step: int | None = Field(default=None, exclude=True)
|
||||
|
||||
def to_record(self) -> dict:
|
||||
"""The plain trace record plus the orchestration metadata (excluded from the pydantic
|
||||
dump), so a record stays fully placeable — kind, env, policy — even when trace files
|
||||
are merged or read away from their paths. ``eval_step`` is the eval trigger step (None
|
||||
for train rollouts)."""
|
||||
return super().to_record() | {
|
||||
"kind": self.kind,
|
||||
"env_name": self.env_name,
|
||||
"group_id": str(self.group_id),
|
||||
"policy_version": self.policy_version,
|
||||
"eval_step": self.eval_step,
|
||||
}
|
||||
|
||||
def assign_advantages(self, values: float | list[float]) -> None:
|
||||
"""Write the rl advantage stream: a scalar broadcast over the
|
||||
rollout's trainable (mask-True) tokens (0.0 elsewhere), or a per-token
|
||||
|
||||
@@ -8,7 +8,6 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import orjson
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.utils.client import setup_inference_pool
|
||||
@@ -51,14 +50,15 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
return renderer, inference_pool
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[dict], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
|
||||
def save_rollouts(rollouts: list[dict], path: Path) -> None:
|
||||
"""Append rollouts (Trace record dicts, already JSON-serializable) to a JSONL file.
|
||||
The trace streams are append-only: ``all`` grows one rollout at a time as they
|
||||
complete, ``effective`` one batch at a time on finalize."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "wb") as f:
|
||||
with open(path, "ab") as f:
|
||||
for rollout in rollouts:
|
||||
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
|
||||
f.write(orjson.dumps(row, default=str, option=opts))
|
||||
f.write(orjson.dumps(rollout, default=str, option=opts))
|
||||
|
||||
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
@@ -94,16 +94,6 @@ def trim_process_memory() -> None:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
|
||||
|
||||
|
||||
def get_tool_response_len(trace: vf.Trace) -> int:
|
||||
"""Total tool-response tokens consumed across the whole rollout, read from a
|
||||
harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`, deduped
|
||||
across turns/branches/sub-RLMs). Returns 0 when no such metric is present."""
|
||||
for key, value in (trace.metrics or {}).items():
|
||||
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
return 0
|
||||
|
||||
|
||||
def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_timeout: int | None = None) -> Path:
|
||||
"""Get the weight directory for a given checkpoint step.
|
||||
|
||||
|
||||
@@ -34,8 +34,8 @@ export NUM_DECODE_NODES={{ num_decode_nodes }}
|
||||
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
|
||||
export NUM_DECODE_REPLICAS={{ num_decode_replicas }}
|
||||
export NODES_PER_REPLICA=$((NUM_PREFILL_NODES + NUM_DECODE_NODES))
|
||||
export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
|
||||
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
export ROUTER_PORT={{ router.port }}
|
||||
@@ -61,7 +61,17 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras
|
||||
{% endif %}
|
||||
|
||||
# Print inference URLs
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
|
||||
@@ -41,8 +41,8 @@ export NUM_PREFILL_NODES={{ num_prefill_nodes }}
|
||||
export NUM_DECODE_NODES={{ num_decode_nodes }}
|
||||
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
|
||||
export NUM_DECODE_REPLICAS={{ num_decode_replicas }}
|
||||
export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
|
||||
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
{%- if router.type == "llm-d" %}
|
||||
@@ -144,7 +144,17 @@ echo "MASTER_PORT=${MASTER_PORT}"
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras
|
||||
{% endif %}
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
|
||||
@@ -48,9 +48,17 @@ echo "MASTER_PORT=${MASTER_PORT}"
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Install environment as local package
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
cd $PROJECT_DIR && uv sync --all-extras
|
||||
{% endif %}
|
||||
|
||||
|
||||
{% if pre_run_command %}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
max_num = -1
|
||||
for key in state_dict:
|
||||
if not key.startswith(layer_prefix):
|
||||
continue
|
||||
layer_num_str = key[len(layer_prefix) :].split(".")[0]
|
||||
if layer_num_str.isdigit():
|
||||
max_num = max(max_num, int(layer_num_str))
|
||||
return max_num + 1
|
||||
@@ -45,7 +45,7 @@ from prime_rl.trainer.models.layers.checkpointing import (
|
||||
)
|
||||
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE, TokenChoiceTopKRouter
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.weights import (
|
||||
load_state_dict,
|
||||
@@ -351,6 +351,29 @@ def freeze_moe_router(model: nn.Module) -> None:
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
|
||||
|
||||
def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
"""Cast MoE router gates to fp32 so routing runs in fp32 in forward and backward.
|
||||
|
||||
The FSDP bf16 cast exemption is applied separately in `setup_fsdp`.
|
||||
"""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_routers = 0
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
mlp.router.to(torch.float32)
|
||||
if isinstance(mlp.router, TokenChoiceTopKRouter):
|
||||
mlp.router.fp32_gate = True
|
||||
num_routers += 1
|
||||
|
||||
# No-op for non-MoE and HF-impl models: moe_router_dtype='float32' is the default,
|
||||
# so absence of custom-impl MoE routers is the common case, not an error.
|
||||
if num_routers > 0:
|
||||
logger.info(f"Running {num_routers} MoE router gates in fp32")
|
||||
|
||||
|
||||
def freeze_sparse_indexer(model: nn.Module) -> None:
|
||||
"""Freeze DSA sparse-attention indexer parameters.
|
||||
|
||||
@@ -681,6 +704,17 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
|
||||
block_mlp.experts.set_gradient_divide_factor(parallel_dims.fsdp_gradient_divide_factor)
|
||||
|
||||
if config.moe_router_dtype == "float32" and isinstance(block_mlp, (MoE, LatentMoE)):
|
||||
# Own FSDP unit with an fp32 policy so the gate weight is not cast to
|
||||
# bf16 for forward and its gradients reduce in fp32.
|
||||
fully_shard(
|
||||
block_mlp.router,
|
||||
mesh=hsdp_mesh,
|
||||
mp_policy=MixedPrecisionPolicy(param_dtype=torch.float32, reduce_dtype=torch.float32),
|
||||
offload_policy=offload_policy,
|
||||
reshard_after_forward=config.reshard_after_forward,
|
||||
)
|
||||
|
||||
fully_shard(
|
||||
transformer_block,
|
||||
mesh=hsdp_mesh,
|
||||
@@ -734,7 +768,11 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
if next_transformer_block is not None:
|
||||
next_mlp = getattr(next_transformer_block, "mlp", None)
|
||||
if next_mlp is not None and isinstance(next_mlp, (MoE, LatentMoE)):
|
||||
transformer_block.set_modules_to_forward_prefetch([next_transformer_block, next_mlp.experts])
|
||||
prefetch_modules = [next_transformer_block]
|
||||
if isinstance(next_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(next_mlp.router)
|
||||
prefetch_modules.append(next_mlp.experts)
|
||||
transformer_block.set_modules_to_forward_prefetch(prefetch_modules)
|
||||
else:
|
||||
transformer_block.set_modules_to_forward_prefetch([next_transformer_block])
|
||||
elif language_model.norm is not None and model.lm_head is not None:
|
||||
@@ -755,7 +793,10 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
if prev_transformer_block is not None:
|
||||
prev_mlp = getattr(prev_transformer_block, "mlp", None)
|
||||
if prev_mlp is not None and isinstance(prev_mlp, (MoE, LatentMoE)):
|
||||
transformer_block.set_modules_to_backward_prefetch([prev_transformer_block, prev_mlp.experts])
|
||||
prefetch_modules = [prev_transformer_block, prev_mlp.experts]
|
||||
if isinstance(prev_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(prev_mlp.router)
|
||||
transformer_block.set_modules_to_backward_prefetch(prefetch_modules)
|
||||
else:
|
||||
transformer_block.set_modules_to_backward_prefetch([prev_transformer_block])
|
||||
elif embed_module is not None:
|
||||
@@ -1111,6 +1152,9 @@ def setup_model(
|
||||
if config.freeze_moe_router:
|
||||
freeze_moe_router(model)
|
||||
|
||||
if config.moe_router_dtype == "float32":
|
||||
apply_fp32_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.
|
||||
|
||||
@@ -8,6 +8,7 @@ from transformers.models.auto.auto_factory import _BaseAutoModelClass, _LazyAuto
|
||||
from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
|
||||
from transformers.models.llama.configuration_llama import LlamaConfig
|
||||
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
||||
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
|
||||
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
@@ -20,6 +21,7 @@ from prime_rl.trainer.models.llama import LlamaForCausalLM
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
|
||||
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
|
||||
|
||||
@@ -31,6 +33,7 @@ AutoConfig.register("laguna", LagunaConfig, exist_ok=True)
|
||||
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
|
||||
AutoConfig.register("nemotron_h", NemotronHConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5_text", Qwen3_5TextConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
|
||||
# GptOssConfig is just HF's class - already registered by transformers, no override needed.
|
||||
|
||||
@@ -44,6 +47,7 @@ _CUSTOM_CAUSAL_LM_MAPPING.register(LagunaConfig, LagunaForCausalLM, exist_ok=Tru
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(NemotronHConfig, NemotronHForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5TextConfig, Qwen3_5ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(GptOssConfig, GptOssForCausalLM, exist_ok=True)
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import re
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def get_num_experts_from_state_dict(state_dict: dict[str, Tensor], layer_idx: int) -> int:
|
||||
"""Get the number of experts from the HF state dict for a given layer."""
|
||||
@@ -122,26 +124,15 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> Non
|
||||
del state_dict[key]
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum layer number from the state dict."""
|
||||
max_layer = -1
|
||||
for key in state_dict.keys():
|
||||
match = re.search(r"model\.layers\.(\d+)\.", key)
|
||||
if match:
|
||||
layer_idx = int(match.group(1))
|
||||
max_layer = max(max_layer, layer_idx)
|
||||
return max_layer
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]) -> None:
|
||||
"""Convert all MoE layers from HF format to TT format in-place."""
|
||||
max_layer = get_max_layer_num(state_dict)
|
||||
for layer_idx in range(max_layer + 1):
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for layer_idx in range(num_layers):
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]) -> None:
|
||||
"""Convert all MoE layers from TT format to HF format in-place."""
|
||||
max_layer = get_max_layer_num(state_dict)
|
||||
for layer_idx in range(max_layer + 1):
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for layer_idx in range(num_layers):
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
|
||||
@@ -19,6 +19,11 @@ from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
@@ -30,21 +35,6 @@ from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_varlen_func = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_3_varlen_func = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_4_varlen_func = None # type: ignore
|
||||
|
||||
from .configuration_afmoe import AfmoeConfig
|
||||
from .converting_afmoe import (
|
||||
convert_hf_layer_to_tt,
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
|
||||
|
||||
def _is_moe_layer(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
|
||||
"""Check if a layer is an MoE layer by looking for the router gate weight."""
|
||||
return f"model.layers.{layer_idx}.mlp.gate.weight" in state_dict
|
||||
|
||||
@@ -185,7 +185,6 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
|
||||
"""
|
||||
# NOTE: We don't use weight scale in this kernel as it produces higher KL mismatch for some reason
|
||||
# This is not a problem result-wise, as it is a constant multiplier
|
||||
_weight_scale = weight_scale
|
||||
S_q, H, D = q.shape
|
||||
S_k = k.shape[0]
|
||||
device = q.device
|
||||
|
||||
@@ -15,10 +15,6 @@ def ceil_div(x: int, y: int) -> int:
|
||||
return (x + y - 1) // y
|
||||
|
||||
|
||||
def align(x: int, y: int) -> int:
|
||||
return ceil_div(x, y) * y
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Layout building
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
return max(int(key.split(".")[2]) for key in state_dict if key.startswith("model.layers.")) + 1
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def _pop_first(state_dict: dict[str, Tensor], keys: tuple[str, ...]) -> Tensor | None:
|
||||
|
||||
@@ -340,3 +340,7 @@ def substitute_ring_attn(
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
|
||||
|
||||
Qwen3_5MoeGatedFlashAttention._compute_attention = _ring_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
|
||||
|
||||
Qwen3_5GatedFlashAttention._compute_attention = _ring_compute_attention
|
||||
|
||||
@@ -77,7 +77,6 @@ class BCFeedForward(nn.Module):
|
||||
self.w3 = nn.Parameter(torch.empty(hidden_dim, dim))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
# return torch.matmul(self.w2, F.silu(torch.matmul(self.w1, x.T)) * torch.matmul(self.w3, x.T))
|
||||
return torch.matmul(F.silu(torch.matmul(x, self.w1.T)) * torch.matmul(x, self.w3.T), self.w2.T)
|
||||
|
||||
def init_weights(self, init_std: float):
|
||||
@@ -427,6 +426,9 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
self.route_norm = route_norm
|
||||
self.route_scale = route_scale
|
||||
self.force_balanced = False
|
||||
# Set via model.moe_router_dtype='float32': the gate weight is kept in fp32
|
||||
# (exempt from FSDP bf16 casting) and the gate GEMM runs in fp32.
|
||||
self.fp32_gate = False
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None, routed_experts: torch.Tensor | None = None
|
||||
@@ -453,7 +455,7 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
assert routed_experts is None or routed_experts.shape[-1] == self.top_k, (
|
||||
f"routed_experts shape: {routed_experts.shape}, top_k: {self.top_k}"
|
||||
)
|
||||
scores = self.gate(x)
|
||||
scores = self.gate(x.to(torch.float32)) if self.fp32_gate else self.gate(x)
|
||||
|
||||
# By default, sigmoid or softmax is performed in float32 to avoid loss explosion
|
||||
if self.score_func == "sigmoid":
|
||||
|
||||
@@ -115,34 +115,3 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
||||
q_embed = torch.cat([q_embed, q_pass], dim=-1)
|
||||
k_embed = torch.cat([k_embed, k_pass], dim=-1)
|
||||
return q_embed, k_embed
|
||||
|
||||
|
||||
def apply_rotary_pos_emb_interleave(q, k, cos, sin, unsqueeze_dim=1):
|
||||
"""Interleaved RoPE: converts from [r0, i0, r1, i1, ...] layout before applying rotation.
|
||||
|
||||
Args:
|
||||
q (`torch.Tensor`): The query tensor.
|
||||
k (`torch.Tensor`): The key tensor.
|
||||
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
||||
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
||||
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
||||
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
||||
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
||||
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
||||
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
||||
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
||||
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
||||
Returns:
|
||||
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
||||
"""
|
||||
cos = cos.unsqueeze(unsqueeze_dim)
|
||||
sin = sin.unsqueeze(unsqueeze_dim)
|
||||
|
||||
b, h, s, d = q.shape
|
||||
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
||||
b, h, s, d = k.shape
|
||||
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
||||
|
||||
q_embed = (q * cos) + (rotate_half(q) * sin)
|
||||
k_embed = (k * cos) + (rotate_half(k) * sin)
|
||||
return q_embed, k_embed
|
||||
|
||||
@@ -189,6 +189,10 @@ def substitute_ulysses_attn(
|
||||
|
||||
Qwen3_5MoeGatedFlashAttention._compute_attention = _ulysses_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
|
||||
|
||||
Qwen3_5GatedFlashAttention._compute_attention = _ulysses_compute_attention
|
||||
|
||||
|
||||
def substitute_hf_ulysses_attn(process_group: dist.ProcessGroup) -> None:
|
||||
"""Patch HF's `_flash_attention_forward` to use Ulysses all-to-all + local FA2.
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .modeling_qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5Model, Qwen3_5PreTrainedModel
|
||||
|
||||
__all__ = ["Qwen3_5ForCausalLM", "Qwen3_5Model", "Qwen3_5PreTrainedModel"]
|
||||
@@ -0,0 +1,305 @@
|
||||
import functools
|
||||
from typing import Optional, Union
|
||||
|
||||
import torch
|
||||
from torch import Tensor, nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import (
|
||||
Qwen3_5PreTrainedModel as HFQwen3_5PreTrainedModel,
|
||||
)
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
Qwen3_5MoeGatedAttentionConfig,
|
||||
Qwen3_5MoeGatedDeltaNet,
|
||||
Qwen3_5MoeGatedFlashAttention,
|
||||
Qwen3_5MoeGatedSDPAAttention,
|
||||
Qwen3_5MoeRMSNorm,
|
||||
Qwen3_5MoeRotaryEmbedding,
|
||||
normalize_qwen3_5_attn_implementation,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
class Qwen3_5GatedSDPAAttention(Qwen3_5MoeGatedSDPAAttention):
|
||||
pass
|
||||
|
||||
|
||||
class Qwen3_5GatedFlashAttention(Qwen3_5MoeGatedFlashAttention):
|
||||
pass
|
||||
|
||||
|
||||
QWEN35_ATTN_IMPL2CLASS = {
|
||||
"sdpa": Qwen3_5GatedSDPAAttention,
|
||||
"flash_attention_2": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=2),
|
||||
"flash_attention_3": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=3),
|
||||
"fa4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
|
||||
}
|
||||
|
||||
|
||||
def _get_gated_attention(config: Qwen3_5TextConfig) -> nn.Module:
|
||||
attn_config = Qwen3_5MoeGatedAttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
attention_bias=config.attention_bias,
|
||||
attention_dropout=config.attention_dropout,
|
||||
)
|
||||
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(config._attn_implementation)
|
||||
config._attn_implementation = attn_impl
|
||||
|
||||
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
|
||||
raise ValueError(
|
||||
f"Qwen3.5 attention does not support '{config._attn_implementation}'. "
|
||||
f"Supported implementations: {supported}."
|
||||
)
|
||||
|
||||
return QWEN35_ATTN_IMPL2CLASS[attn_impl](attn_config)
|
||||
|
||||
|
||||
def _create_rotary_emb(config: Qwen3_5TextConfig) -> Qwen3_5MoeRotaryEmbedding:
|
||||
return Qwen3_5MoeRotaryEmbedding(config)
|
||||
|
||||
|
||||
class Qwen3_5DecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: Qwen3_5TextConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_type = config.layer_types[layer_idx]
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
self.linear_attn = Qwen3_5MoeGatedDeltaNet(config)
|
||||
elif self.layer_type == "full_attention":
|
||||
self.self_attn = _get_gated_attention(config)
|
||||
else:
|
||||
raise ValueError(f"Unsupported Qwen3.5 layer type: {self.layer_type}")
|
||||
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.FloatTensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
hidden_states = self.linear_attn(hidden_states, cu_seqlens=cu_seqlens)
|
||||
else:
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
|
||||
config_class = Qwen3_5TextConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["Qwen3_5DecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_flex_attn = False
|
||||
_supports_attention_backend = True
|
||||
_can_compile_fullgraph = False
|
||||
_can_record_outputs = {
|
||||
"hidden_states": Qwen3_5DecoderLayer,
|
||||
}
|
||||
|
||||
def _check_and_adjust_attn_implementation(
|
||||
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
|
||||
) -> str:
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
|
||||
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
|
||||
raise ValueError(
|
||||
f"Qwen3.5 attention does not support '{attn_implementation}'. Supported implementations: {supported}."
|
||||
)
|
||||
return attn_impl
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
|
||||
class Qwen3_5Model(Qwen3_5PreTrainedModel):
|
||||
def __init__(self, config: Qwen3_5TextConfig):
|
||||
config._attn_implementation = normalize_qwen3_5_attn_implementation(config._attn_implementation)
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.layers = nn.ModuleList(
|
||||
[Qwen3_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
)
|
||||
self.norm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.rotary_emb = _create_rotary_emb(config)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
self.post_init()
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
) -> BaseModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
flash_attn_enabled = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
|
||||
if flash_attn_enabled:
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
cu_seqlens = None
|
||||
max_seqlen = None
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for decoder_layer in self.layers:
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_checkpoint_conversion_mapping = {}
|
||||
_tp_plan = {"lm_head": "colwise_gather_output"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config, **kwargs):
|
||||
super().__init__(config, **kwargs)
|
||||
self.model = Qwen3_5Model(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
return self.model.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.model.embed_tokens = value
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[Cache] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
temperature: Union[torch.Tensor, None] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
assert use_cache is None, "use_cache is not supported for custom qwen3_5 for now"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom qwen3_5 for now"
|
||||
|
||||
if position_ids is None:
|
||||
if inputs_embeds is not None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
elif input_ids is not None:
|
||||
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
|
||||
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
return self.lm_head(
|
||||
hidden_states[:, slice_indices, :],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
temperature=temperature,
|
||||
)
|
||||
|
||||
def init_buffers_post_meta(self):
|
||||
lm_rope = self.model.rotary_emb
|
||||
if hasattr(lm_rope, "rope_init_fn"):
|
||||
inv_freq, lm_rope.attention_scaling = lm_rope.rope_init_fn(lm_rope.config, lm_rope.inv_freq.device)
|
||||
lm_rope.inv_freq.copy_(inv_freq)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Qwen3_5ForCausalLM",
|
||||
"Qwen3_5GatedFlashAttention",
|
||||
"Qwen3_5Model",
|
||||
"Qwen3_5PreTrainedModel",
|
||||
]
|
||||
@@ -1,10 +1,7 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
|
||||
@@ -16,6 +16,11 @@ from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, logging
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
|
||||
@@ -30,22 +35,6 @@ from .converting_qwen3_5_moe import (
|
||||
)
|
||||
from .mrope import build_qwen3_5_mrope_position_ids
|
||||
|
||||
# Flash attention imports
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_varlen_func = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_3_varlen_func = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_4_varlen_func = None # type: ignore
|
||||
|
||||
# Flash linear attention imports (for GatedDeltaNet fast path)
|
||||
try:
|
||||
from causal_conv1d import causal_conv1d_fn
|
||||
@@ -562,6 +551,14 @@ QWEN35MOE_ATTN_IMPL2CLASS = {
|
||||
}
|
||||
|
||||
|
||||
def normalize_qwen3_5_attn_implementation(attn_impl: str) -> str:
|
||||
if attn_impl == "eager":
|
||||
return "sdpa"
|
||||
if attn_impl == "kernels-community/vllm-flash-attn3":
|
||||
return "flash_attention_3"
|
||||
return attn_impl
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Decoder layer
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -578,9 +575,8 @@ def _get_gated_attention(config: Qwen3_5MoeConfig) -> nn.Module:
|
||||
attention_dropout=config.attention_dropout,
|
||||
)
|
||||
|
||||
attn_impl = config._attn_implementation
|
||||
if attn_impl == "eager":
|
||||
attn_impl = "sdpa"
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(config._attn_implementation)
|
||||
config._attn_implementation = attn_impl
|
||||
|
||||
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
|
||||
@@ -794,6 +790,17 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
"hidden_states": Qwen3_5MoeDecoderLayer,
|
||||
}
|
||||
|
||||
def _check_and_adjust_attn_implementation(
|
||||
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
|
||||
) -> str:
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
|
||||
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
|
||||
raise ValueError(
|
||||
f"Qwen3.5-MoE attention does not support '{attn_implementation}'. Supported implementations: {supported}."
|
||||
)
|
||||
return attn_impl
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
@@ -830,6 +837,7 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
|
||||
def __init__(self, config: Qwen3_5MoeConfig):
|
||||
config._attn_implementation = normalize_qwen3_5_attn_implementation(config._attn_implementation)
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
|
||||
@@ -242,88 +242,6 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
|
||||
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
def load_balancing_loss_func(
|
||||
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
|
||||
num_experts: Optional[int] = None,
|
||||
top_k=2,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
) -> Union[torch.Tensor, int]:
|
||||
r"""
|
||||
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
||||
|
||||
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
|
||||
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
||||
experts is too unbalanced.
|
||||
|
||||
Args:
|
||||
gate_logits:
|
||||
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
||||
shape [batch_size X sequence_length, num_experts].
|
||||
num_experts:
|
||||
Number of experts
|
||||
top_k:
|
||||
The number of experts to route per-token, can be also interpreted as the `top-k` routing
|
||||
parameter.
|
||||
attention_mask (`torch.Tensor`, *optional*):
|
||||
The attention_mask used in forward function
|
||||
shape [batch_size X sequence_length] if not None.
|
||||
|
||||
Returns:
|
||||
The auxiliary loss.
|
||||
"""
|
||||
if gate_logits is None or not isinstance(gate_logits, tuple):
|
||||
return 0
|
||||
|
||||
if isinstance(gate_logits, tuple):
|
||||
compute_device = gate_logits[0].device
|
||||
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
|
||||
|
||||
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
|
||||
|
||||
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
|
||||
|
||||
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
|
||||
|
||||
if attention_mask is None:
|
||||
# Compute the percentage of tokens routed to each experts
|
||||
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
|
||||
|
||||
# Compute the average probability of routing to these experts
|
||||
router_prob_per_expert = torch.mean(routing_weights, dim=0)
|
||||
else:
|
||||
batch_size, sequence_length = attention_mask.shape
|
||||
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
|
||||
|
||||
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
|
||||
expert_attention_mask = (
|
||||
attention_mask[None, :, :, None, None]
|
||||
.expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
|
||||
.reshape(-1, top_k, num_experts)
|
||||
.to(compute_device)
|
||||
)
|
||||
|
||||
# Compute the percentage of tokens routed to each experts
|
||||
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
|
||||
expert_attention_mask, dim=0
|
||||
)
|
||||
|
||||
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
|
||||
router_per_expert_attention_mask = (
|
||||
attention_mask[None, :, :, None]
|
||||
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
|
||||
.reshape(-1, num_experts)
|
||||
.to(compute_device)
|
||||
)
|
||||
|
||||
# Compute the average probability of routing to these experts
|
||||
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
|
||||
router_per_expert_attention_mask, dim=0
|
||||
)
|
||||
|
||||
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
|
||||
return overall_loss * num_experts
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
|
||||
@@ -116,7 +116,9 @@ class MultiCheckpointManager:
|
||||
scheduler: "MultiLoRAScheduler",
|
||||
) -> None:
|
||||
for idx in self.multi_run_manager.used_idxs:
|
||||
step = self.multi_run_manager.progress[idx].step
|
||||
# pack() already advanced progress to the next step, so the step just finished
|
||||
# (and its broadcasts/step_{step} weights) is progress - 1.
|
||||
step = self.multi_run_manager.progress[idx].step - 1
|
||||
if not self._should_save(idx, step):
|
||||
continue
|
||||
|
||||
|
||||
@@ -37,9 +37,6 @@ class PerfCounter:
|
||||
self.gpu_peak_flops = self._get_peak_flops(torch.cuda.get_device_name(torch.device("cuda")))
|
||||
else:
|
||||
self.gpu_peak_flops = 0
|
||||
# If not tie_word_embeddings, we exclude the embedding parameters from the total number of parameters
|
||||
# If tie_word_embeddings, the embedding parameters are already excluded (shared with the LM head)
|
||||
self.num_params = self._get_num_params(model, exclude_embedding=not model.config.tie_word_embeddings)
|
||||
self.num_flop_per_token = self._get_num_flop_per_token(model.config, seq_len=seq_len)
|
||||
|
||||
def count_tokens(self, tokens: int) -> None:
|
||||
@@ -209,23 +206,6 @@ class PerfCounter:
|
||||
|
||||
return flop_per_token
|
||||
|
||||
def _get_num_params(self, model: nn.Module, exclude_embedding: bool = False) -> int:
|
||||
num_params = sum(p.numel() for p in model.parameters())
|
||||
if exclude_embedding:
|
||||
if hasattr(model.lm_head, "weight"):
|
||||
num_params -= model.lm_head.weight.numel()
|
||||
elif hasattr(model.lm_head, "base_layer"): # MultiLoRAModule
|
||||
num_params -= model.lm_head.base_layer.weight.numel()
|
||||
return num_params
|
||||
|
||||
def _count_trainable_params(self) -> int:
|
||||
"""Count trainable parameters (LoRA adapters + modules_to_save)."""
|
||||
trainable_params = 0
|
||||
for param in self.model.parameters():
|
||||
if param.requires_grad:
|
||||
trainable_params += param.numel()
|
||||
return trainable_params
|
||||
|
||||
def _count_lora_adapter_params(self) -> int:
|
||||
"""Count LoRA adapter parameters (sum of lora_A and lora_B across all MultiLoRAModules)."""
|
||||
params = 0
|
||||
|
||||
@@ -68,9 +68,11 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
# TODO: Broadcast ready to update in sync, then we dont need to gather on not ready
|
||||
if self.world.is_master:
|
||||
try:
|
||||
# pack() already advanced progress to the next step, so the model we just
|
||||
# trained — policy v(step-1) — broadcasts to broadcasts/step_{step-1}.
|
||||
save_dir = get_step_path(
|
||||
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
|
||||
self.multi_run_manager.progress[idx].step,
|
||||
self.multi_run_manager.progress[idx].step - 1,
|
||||
)
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -112,6 +114,6 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
for idx in self.multi_run_manager.used_idxs:
|
||||
maybe_clean(
|
||||
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
|
||||
self.multi_run_manager.progress[idx].step,
|
||||
self.multi_run_manager.progress[idx].step - 1,
|
||||
interval_to_keep,
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from typing import Callable, Generator, cast
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
from torch.distributed.tensor import DTensor
|
||||
@@ -11,19 +12,18 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
from vllm.distributed.utils import StatelessProcessGroup
|
||||
|
||||
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.utils import get_world
|
||||
from prime_rl.trainer.weights import get_max_layer_num
|
||||
from prime_rl.utils.client import NCCL_READY_MARKER
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
|
||||
from prime_rl.utils.pathing import sync_wait_for_path
|
||||
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
|
||||
from prime_rl.utils.vlm import get_layer_prefix
|
||||
|
||||
NCCL_READY_MARKER = "NCCL_READY"
|
||||
|
||||
|
||||
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
|
||||
"""Broadcast an integer to a process group using NCCL communicator."""
|
||||
@@ -201,7 +201,7 @@ class NCCLWeightBroadcast(WeightBroadcast):
|
||||
# `_compute_notified_runs` is a pure function of SPMD-replicated state on
|
||||
# multi_run_manager, so every trainer rank derives the same list. Only
|
||||
# the master touches the filesystem to notify the orchestrator, but all
|
||||
# ranks must wait on NCCL_READY before entering the broadcast path:
|
||||
# ranks must wait for the inference pool before entering the broadcast path:
|
||||
# the broadcast preparation (DTensor resolution, quantization) enqueues
|
||||
# collectives on non-master ranks, and if those ranks start prep before
|
||||
# the orchestrator has paused inference, the collectives sit unmatched
|
||||
@@ -209,7 +209,9 @@ class NCCLWeightBroadcast(WeightBroadcast):
|
||||
notified_runs = self._compute_notified_runs()
|
||||
if self.world.is_master:
|
||||
self._notify_orchestrator(notified_runs)
|
||||
self._wait_for_nccl_ready(notified_runs)
|
||||
self._wait_for_nccl_ready(notified_runs)
|
||||
if self.world.world_size > 1:
|
||||
dist.barrier()
|
||||
self.nccl_broadcast_sender.broadcast_weights(model, step)
|
||||
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
|
||||
|
||||
@@ -225,9 +227,11 @@ class NCCLWeightBroadcast(WeightBroadcast):
|
||||
if not self.multi_run_manager.ready_to_update[idx]:
|
||||
continue
|
||||
try:
|
||||
# pack() already advanced progress to the next step, so the model we just
|
||||
# trained — policy v(step-1) — broadcasts to broadcasts/step_{step-1}.
|
||||
save_dir = get_step_path(
|
||||
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
|
||||
self.multi_run_manager.progress[idx].step,
|
||||
self.multi_run_manager.progress[idx].step - 1,
|
||||
)
|
||||
notified_runs.append((idx, save_dir))
|
||||
except FileNotFoundError:
|
||||
|
||||
@@ -5,7 +5,6 @@ from typing import TypedDict
|
||||
import torch
|
||||
from jaxtyping import Bool, Float, Int
|
||||
from torch import Tensor
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.trainer import FakeDataLoaderConfig
|
||||
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
|
||||
@@ -183,7 +182,6 @@ class DataLoader:
|
||||
dp_world_size: int,
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
config: TransportConfig,
|
||||
):
|
||||
@@ -193,7 +191,6 @@ class DataLoader:
|
||||
self.packer: BasePacker = setup_packer(
|
||||
dp_world_size=dp_world_size,
|
||||
seq_len=seq_len,
|
||||
tokenizer=tokenizer,
|
||||
transport_config=config,
|
||||
pad_to_multiple_of=pad_to_multiple_of,
|
||||
bin_cost=bin_cost,
|
||||
|
||||
@@ -63,20 +63,6 @@ def compute_entropy(shifted_logits: Float[Tensor, "batch seq vocab"]) -> Float[T
|
||||
return entropy
|
||||
|
||||
|
||||
@jaxtyped(typechecker=typechecker)
|
||||
def shift_logits(
|
||||
logits: Float[Tensor, "batch seq vocab"], left_pad_logit: Float[Tensor, "batch 1 vocab"] | None = None
|
||||
) -> Float[Tensor, "batch seq vocab"]:
|
||||
"""Removes final token logits and adds a left pad logit for the first token."""
|
||||
# We drop the last logit because it corresponds to the next token that will be sampled but is not here yet
|
||||
batch, seq, vocab = logits.shape
|
||||
logits = logits[:, :-1, :] # (batch, seq-1, vocab)
|
||||
if left_pad_logit is None:
|
||||
left_pad_logit = torch.zeros(batch, 1, vocab, device=logits.device, dtype=logits.dtype) # (batch, 1, vocab)
|
||||
logits = torch.cat([left_pad_logit, logits], dim=1) # (batch, seq, vocab)
|
||||
return logits
|
||||
|
||||
|
||||
def shift_tensor_left(t: Float[Tensor, "batch seq"]) -> Float[Tensor, "batch seq"]:
|
||||
"""Shifts the tensor one token to the left.
|
||||
|
||||
|
||||
@@ -6,8 +6,6 @@ from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Sequence
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.trainer.batch import prepare_batch
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.transport import (
|
||||
@@ -31,7 +29,6 @@ class BasePacker(ABC):
|
||||
dp_world_size: int,
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
@@ -41,7 +38,6 @@ class BasePacker(ABC):
|
||||
self.dp_world_size = dp_world_size
|
||||
self.seq_len = seq_len
|
||||
self.pad_to_multiple_of = pad_to_multiple_of
|
||||
self.tokenizer = tokenizer
|
||||
self.bin_cost = bin_cost
|
||||
self.receiver = setup_training_batch_receiver(config)
|
||||
shutil.rmtree(get_rollout_dir(self.multi_run_manager.output_dir), ignore_errors=True)
|
||||
@@ -85,12 +81,11 @@ class SinglePacker(BasePacker):
|
||||
dp_world_size: int,
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
):
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, config, bin_cost, start_step)
|
||||
assert self.multi_run_manager.max_runs == 1, "SinglePacker only supports one run"
|
||||
|
||||
def pack(self):
|
||||
@@ -132,12 +127,11 @@ class MultiPacker(BasePacker):
|
||||
dp_world_size: int,
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
):
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, config, bin_cost, start_step)
|
||||
# Per-run buffer: stores (TrainingSample, step) tuples
|
||||
self.buffers: list[deque[tuple[TrainingSample, int]]] = [
|
||||
deque() for _ in range(self.multi_run_manager.max_runs)
|
||||
@@ -351,17 +345,12 @@ def setup_packer(
|
||||
dp_world_size: int,
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
transport_config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
) -> BasePacker:
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
if multi_run_manager.max_runs == 1:
|
||||
return SinglePacker(
|
||||
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
|
||||
)
|
||||
return SinglePacker(dp_world_size, seq_len, pad_to_multiple_of, transport_config, bin_cost, start_step)
|
||||
else:
|
||||
return MultiPacker(
|
||||
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
|
||||
)
|
||||
return MultiPacker(dp_world_size, seq_len, pad_to_multiple_of, transport_config, bin_cost, start_step)
|
||||
|
||||
@@ -222,6 +222,8 @@ def train(config: TrainerConfig):
|
||||
progress = Progress()
|
||||
if checkpoint_step is not None:
|
||||
ckpt_manager.load(checkpoint_step, model, [optimizer], scheduler, progress)
|
||||
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
|
||||
progress.step += 1
|
||||
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
|
||||
|
||||
logger.info(
|
||||
@@ -239,7 +241,6 @@ def train(config: TrainerConfig):
|
||||
parallel_dims.get_mesh("dp").size(),
|
||||
config.model.seq_len,
|
||||
config.model.cp,
|
||||
tokenizer,
|
||||
build_bin_cost(model.config),
|
||||
config.rollout_transport,
|
||||
)
|
||||
@@ -249,7 +250,6 @@ def train(config: TrainerConfig):
|
||||
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
|
||||
|
||||
logger.info(f"Starting training loop (max_steps={config.max_steps or 'infinite'})")
|
||||
is_first_step = True
|
||||
maybe_record_function = nullcontext
|
||||
if config.trace_path:
|
||||
logger.info(f"Tracing to {config.trace_path}")
|
||||
@@ -262,73 +262,6 @@ def train(config: TrainerConfig):
|
||||
gc_handler.run(progress.step)
|
||||
is_last_step = config.max_steps is not None and progress.step == config.max_steps
|
||||
|
||||
# Broadcast weights every step except:
|
||||
# - step 0: nothing has changed yet, the orchestrator has the base model.
|
||||
# - the final NCCL broadcast: with a 1-step async barrier the orchestrator's last step
|
||||
# uses the trainer's penultimate ckpt, so the trainer's last broadcast has no receiver
|
||||
# (the inference NCCL group has been torn down). Filesystem broadcast still writes the
|
||||
# final step so we can resume from the broadcast directory.
|
||||
if weight_broadcast is None:
|
||||
broadcast_weights_time = 0
|
||||
else:
|
||||
nccl_broadcast_unused = (
|
||||
config.weight_broadcast.type == "nccl"
|
||||
and config.max_steps is not None
|
||||
and progress.step >= config.max_steps - 1
|
||||
)
|
||||
if progress.step > 0 and not nccl_broadcast_unused:
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
|
||||
if config.weight_broadcast.type == "filesystem":
|
||||
interval_to_keep = config.ckpt and config.ckpt.interval
|
||||
weight_broadcast.maybe_clean(interval_to_keep)
|
||||
else:
|
||||
broadcast_weights_time = 0
|
||||
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
|
||||
for idx in multi_run_manager.used_idxs:
|
||||
multi_run_manager.ready_to_update[idx] = False
|
||||
|
||||
if config.max_concurrent_runs > 1:
|
||||
# Multi-run: Save per-run checkpoints using each run's orchestrator config.
|
||||
# Trainer-level ckpt config can be set by the combined rl entrypoint,
|
||||
# but MultiCheckpointManager has a different save signature.
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(optimizer, scheduler)
|
||||
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
|
||||
ckpt_manager.maybe_clean()
|
||||
elif (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
and not (is_first_step or is_last_step)
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
# Single-run: Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
|
||||
# Break if we have reached the maximum number of steps
|
||||
if config.max_steps is not None and progress.step >= config.max_steps:
|
||||
break
|
||||
|
||||
logger.debug(f"Starting training step {progress.step}")
|
||||
step_start_time = time.perf_counter()
|
||||
|
||||
@@ -621,6 +554,69 @@ def train(config: TrainerConfig):
|
||||
current_lr = optimizer.get_current_lr()
|
||||
forward_backward_time = time.perf_counter() - forward_backward_start_time
|
||||
|
||||
# Broadcast the model just produced (policy v{progress.step}) so the orchestrator can
|
||||
# sample its next step from it. Skip the final NCCL broadcasts: with a 1-step async barrier
|
||||
# the orchestrator's last step uses the trainer's penultimate ckpt, so they have no receiver
|
||||
# (the inference NCCL group is torn down). Filesystem broadcast still writes them so we can
|
||||
# resume from the broadcast directory.
|
||||
if weight_broadcast is None:
|
||||
broadcast_weights_time = 0
|
||||
else:
|
||||
nccl_broadcast_unused = (
|
||||
config.weight_broadcast.type == "nccl"
|
||||
and config.max_steps is not None
|
||||
and progress.step >= config.max_steps - 1
|
||||
)
|
||||
if not nccl_broadcast_unused:
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
|
||||
if config.weight_broadcast.type == "filesystem":
|
||||
interval_to_keep = config.ckpt and config.ckpt.interval
|
||||
weight_broadcast.maybe_clean(interval_to_keep)
|
||||
else:
|
||||
broadcast_weights_time = 0
|
||||
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
|
||||
for idx in multi_run_manager.used_idxs:
|
||||
multi_run_manager.ready_to_update[idx] = False
|
||||
|
||||
# Checkpoint the step we just finished (model = policy v{progress.step}).
|
||||
if config.max_concurrent_runs > 1:
|
||||
# Multi-run: save per-run checkpoints every step (interval-gated inside
|
||||
# MultiCheckpointManager); there is no after-loop final save for multi-run.
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(optimizer, scheduler)
|
||||
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
|
||||
ckpt_manager.maybe_clean()
|
||||
elif (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
# the last step is written once after the loop (final ckpt), so skip it here
|
||||
and not is_last_step
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
# Single-run: Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
|
||||
# Optionally, dump memory snapshot
|
||||
if memory_profiler is not None:
|
||||
memory_profiler.step()
|
||||
@@ -738,13 +734,14 @@ def train(config: TrainerConfig):
|
||||
run_stats=run_stats,
|
||||
)
|
||||
|
||||
progress.step += 1
|
||||
is_first_step = False
|
||||
|
||||
# Send heartbeat if configured
|
||||
if heart is not None:
|
||||
heart.beat()
|
||||
|
||||
if is_last_step:
|
||||
break
|
||||
progress.step += 1
|
||||
|
||||
if config.trace_path:
|
||||
prof.__exit__(None, None, None)
|
||||
config.trace_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -20,7 +20,7 @@ if TYPE_CHECKING:
|
||||
|
||||
@dataclass
|
||||
class Progress:
|
||||
step: int = 0
|
||||
step: int = 1
|
||||
total_tokens: int = 0
|
||||
total_samples: int = 0
|
||||
|
||||
@@ -278,16 +278,17 @@ class MultiRunManager:
|
||||
|
||||
# Set progress based on resume_step config (match orchestrator behavior)
|
||||
self.progress[new_id] = Progress()
|
||||
# ``step_S`` means step S finished; resume continues at S+1.
|
||||
if config.ckpt is None or config.ckpt.resume_step is None:
|
||||
self.progress[new_id].step = 0
|
||||
self.progress[new_id].step = 1
|
||||
elif config.ckpt.resume_step == -1:
|
||||
ckpt_dir = self.get_run_dir(new_id) / "checkpoints"
|
||||
# In multi-run, the trainer writes STABLE after saving LoRA weights to the run's checkpoint dir.
|
||||
# In single-run, only the orchestrator writes checkpoints here (trainer has its own dir), so no STABLE exists.
|
||||
steps = get_stable_ckpt_steps(ckpt_dir) if self.max_runs > 1 else get_all_ckpt_steps(ckpt_dir)
|
||||
self.progress[new_id].step = max(steps) if steps else 0
|
||||
self.progress[new_id].step = max(steps) + 1 if steps else 1
|
||||
else:
|
||||
self.progress[new_id].step = config.ckpt.resume_step
|
||||
self.progress[new_id].step = config.ckpt.resume_step + 1
|
||||
|
||||
# Store the parsed config
|
||||
self.config[new_id] = config
|
||||
|
||||
@@ -215,6 +215,9 @@ def train(config: SFTConfig):
|
||||
dataloader=dataloader if not config.ckpt.skip_dataloader else None,
|
||||
)
|
||||
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
|
||||
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
|
||||
if not config.ckpt.skip_progress:
|
||||
progress.step += 1
|
||||
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
|
||||
if config.ckpt.skip_scheduler:
|
||||
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
|
||||
@@ -347,37 +350,6 @@ def train(config: SFTConfig):
|
||||
gc_handler.run(progress.step)
|
||||
is_last_step = config.max_steps is not None and progress.step == config.max_steps
|
||||
|
||||
if (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
and not (is_first_step or is_last_step)
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
# Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
|
||||
# Break if we have reached the maximum number of steps
|
||||
if config.max_steps is not None and progress.step >= config.max_steps:
|
||||
break
|
||||
|
||||
memory_profiler = (
|
||||
MemoryProfiler(progress.step, config.memory_profiler_path) if config.memory_profiler_path else None
|
||||
)
|
||||
@@ -482,6 +454,35 @@ def train(config: SFTConfig):
|
||||
current_lr = optimizer.param_groups[0]["lr"]
|
||||
scheduler.step()
|
||||
|
||||
# Checkpoint the step we just finished. The last step's checkpoint is written once after
|
||||
# the loop, so skip it here to avoid a double-save.
|
||||
if (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
and not is_last_step
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
# Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
|
||||
# Optionally, dump memory snapshot
|
||||
if memory_profiler is not None:
|
||||
memory_profiler.step()
|
||||
@@ -585,12 +586,15 @@ def train(config: SFTConfig):
|
||||
monitor.log({**moe_log_metrics, "step": progress.step}, step=progress.step)
|
||||
|
||||
is_first_step = False
|
||||
progress.step += 1
|
||||
|
||||
# Send heartbeat if configured
|
||||
if heart is not None:
|
||||
heart.beat()
|
||||
|
||||
if is_last_step:
|
||||
break
|
||||
progress.step += 1
|
||||
|
||||
if config.trace_path:
|
||||
prof.__exit__(None, None, None)
|
||||
config.trace_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -24,26 +24,6 @@ from prime_rl.trainer.lora import (
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
PYTORCH_WRAPPER_PREFIXES = ["_fsdp_wrapped_module.", "_orig_module.", "_checkpoint_wrapped_module."]
|
||||
|
||||
|
||||
def _strip_pytorch_wrapper_prefix(key: str) -> str:
|
||||
for prefix in PYTORCH_WRAPPER_PREFIXES:
|
||||
key = key.replace(prefix, "")
|
||||
return key
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
max_num = -1
|
||||
for key in state_dict:
|
||||
if not key.startswith(layer_prefix):
|
||||
continue
|
||||
layer_num_str = key[len(layer_prefix) :].split(".")[0]
|
||||
if layer_num_str.isdigit():
|
||||
max_num = max(max_num, int(layer_num_str))
|
||||
return max_num + 1
|
||||
|
||||
|
||||
def load_state_dict_keys(save_dir: Path) -> list[str]:
|
||||
"""Load only the key names from safetensor files without reading tensor data."""
|
||||
@@ -152,35 +132,3 @@ def gather_weights_on_master(
|
||||
cpu_state = clean_lora_state_dict(cpu_state)
|
||||
|
||||
return cpu_state
|
||||
|
||||
|
||||
def get_adapter_state_dict(model: nn.Module, is_master: bool) -> dict[str, Tensor]:
|
||||
"""Get adapter weights with clean keys for PEFT compatibility."""
|
||||
lora_state = {}
|
||||
|
||||
named_params = {_strip_pytorch_wrapper_prefix(key): value for key, value in model.named_parameters()}
|
||||
for key, value in model.state_dict().items():
|
||||
param = named_params.get(key)
|
||||
if param is None or not param.requires_grad:
|
||||
continue
|
||||
|
||||
if isinstance(value, DTensor):
|
||||
value = value.full_tensor()
|
||||
|
||||
if is_master:
|
||||
clean_key = next(iter(get_fqns(model, key)))
|
||||
clean_key = clean_key.replace(".base_layer.", ".")
|
||||
|
||||
# Add PEFT-expected prefix
|
||||
peft_key = f"base_model.model.{clean_key}"
|
||||
|
||||
# Add .weight suffix for LoRA parameters if missing
|
||||
if ("lora_A" in peft_key or "lora_B" in peft_key) and not peft_key.endswith(".weight"):
|
||||
peft_key = f"{peft_key}.weight"
|
||||
|
||||
lora_state[peft_key] = value.to("cpu", non_blocking=False)
|
||||
|
||||
torch.distributed.barrier()
|
||||
if is_master and len(lora_state) == 0:
|
||||
raise ValueError("The LoRA state dict is empty. Something went wrong.")
|
||||
return lora_state
|
||||
|
||||
@@ -10,14 +10,6 @@ class IncrementalTokenizationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def common_prefix_len(a: list[int], b: list[int]) -> int:
|
||||
max_len = min(len(a), len(b))
|
||||
for idx in range(max_len):
|
||||
if a[idx] != b[idx]:
|
||||
return idx
|
||||
return max_len
|
||||
|
||||
|
||||
def normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
|
||||
if messages is None:
|
||||
return []
|
||||
|
||||
@@ -407,8 +407,9 @@ async def update_weights(
|
||||
weight update, then resumes. This ensures all DP workers are idle and can
|
||||
participate in the collective weight transfer.
|
||||
|
||||
Note: The server-side /update_weights endpoint automatically resets the prefix cache
|
||||
to invalidate any cached KV states computed with the old weights.
|
||||
Note: the prefix cache is intentionally not reset on weight update. The orchestrator
|
||||
salts the prefix cache per weight version (``cache_salt`` in the sampling request, see
|
||||
``orchestrator/envs.py``), so KV computed under old weights is never reused.
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
@@ -470,8 +471,9 @@ LORA_LOAD_TOTAL_TIMEOUT_S = 120.0
|
||||
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
|
||||
"""Make a HTTP post request to the vLLM server to load a LoRA adapter.
|
||||
|
||||
Uses our wrapper endpoint that also resets the prefix cache to invalidate
|
||||
KV states computed with old weights.
|
||||
Uses our wrapper around vLLM's /v1/load_lora_adapter. The prefix cache is not reset
|
||||
here; the orchestrator salts it per weight version (see ``orchestrator/envs.py``) so
|
||||
KV computed under old weights is never reused.
|
||||
|
||||
Retries with exponential backoff if the adapter files are not found,
|
||||
which can happen due to NFS propagation delays.
|
||||
|
||||
@@ -155,34 +155,6 @@ def gather_for_cp_wo_grad(t: torch.Tensor, cp_world_size: int, cp_group: dist.Pr
|
||||
return torch.cat(empty_like_t, dim=1)
|
||||
|
||||
|
||||
def get_padding_logit_from_prev_cp_rank(
|
||||
logits: torch.Tensor, cp_rank: int, cp_world_size: int, cp_group: dist.ProcessGroup
|
||||
) -> torch.Tensor | None:
|
||||
"""
|
||||
Get the padding logit from the previous context parallel rank.
|
||||
Args:
|
||||
logits: The logits tensor.
|
||||
cp_rank: The rank of the current process.
|
||||
cp_world_size: The number of processes in the context parallel group.
|
||||
cp_group: The context parallel group.
|
||||
Returns:
|
||||
The padding logit from the previous context parallel rank.
|
||||
"""
|
||||
last_logit = logits[:, -1, :].unsqueeze(1)
|
||||
|
||||
all_rank_last_logits = [
|
||||
torch.zeros(1, 1, logits.shape[2], dtype=logits.dtype, device=logits.device) for _ in range(cp_world_size)
|
||||
]
|
||||
|
||||
dist.all_gather(all_rank_last_logits, last_logit, group=cp_group)
|
||||
|
||||
prev_cp_rank = cp_rank - 1
|
||||
if prev_cp_rank >= 0:
|
||||
return all_rank_last_logits[prev_cp_rank]
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def setup_cp_params(
|
||||
input_ids: torch.Tensor,
|
||||
position_ids: torch.Tensor,
|
||||
|
||||
@@ -43,7 +43,7 @@ class Heartbeat:
|
||||
|
||||
Non-blocking guarantee: This method never blocks the training loop. The HTTP
|
||||
request runs in a daemon thread, so even if the server is slow/unresponsive
|
||||
(up to the 2s timeout), training continues uninterrupted. The lock is held only
|
||||
(up to the 1s timeout), training continues uninterrupted. The lock is held only
|
||||
briefly (microseconds) to check/set flags atomically.
|
||||
"""
|
||||
with self._lock:
|
||||
|
||||
@@ -38,6 +38,8 @@ def setup_monitor(
|
||||
*,
|
||||
prime_config: PrimeMonitorConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
train_env_names: list[str] = [],
|
||||
eval_env_names: list[str] = [],
|
||||
# Backward compatibility: support old 'config' keyword argument
|
||||
config: WandbWithExtrasConfig | None = None,
|
||||
) -> Monitor:
|
||||
@@ -65,6 +67,8 @@ def setup_monitor(
|
||||
tokenizer=tokenizer,
|
||||
run_config=run_config,
|
||||
keep_full_history=keep_full_history,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from verifiers.v1.push import trace_to_sample
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig
|
||||
@@ -325,36 +326,29 @@ class PrimeMonitor(Monitor):
|
||||
)
|
||||
|
||||
def _rollouts_to_parquet_bytes(self, rollouts: list[Rollout], step: int) -> bytes | None:
|
||||
"""Convert rollouts to Parquet bytes for upload. One row per rollout, built from the
|
||||
message graph: the conversation is the unit (no prompt/completion split — meaningless in
|
||||
a multi-turn branch), so `completion` carries the main (last) branch's full message list
|
||||
and `trajectory` carries one message list per branch (`trace.branches`)."""
|
||||
"""Convert rollouts to Parquet bytes for upload. One row per rollout. The conversation
|
||||
is the unit (no prompt/completion split — meaningless mid-branch): `completion` is the
|
||||
last branch's messages and `trajectory` is one message list per branch. Shares
|
||||
`verifiers.v1.push.trace_to_sample` with verifiers' eval `--push`, so a training-run
|
||||
sample and an eval sample land on the platform identically; the RFT-only columns
|
||||
(run/step/advantage/problem_id/env_name) are layered on here."""
|
||||
now = datetime.now(timezone.utc)
|
||||
rows = []
|
||||
|
||||
for sample_id, rollout in enumerate(rollouts):
|
||||
branches = rollout.branches
|
||||
if not branches:
|
||||
sample = trace_to_sample(rollout, rollout_number=sample_id + 1)
|
||||
trajectory = sample["trajectory"]
|
||||
if not trajectory: # no branches (e.g. a rollout that errored before any message)
|
||||
continue
|
||||
main_messages = [m.model_dump(mode="json") for m in branches[-1].messages]
|
||||
advantage = rollout.scalar_advantage()
|
||||
trajectory = [{**branch, "advantage": advantage} for branch in trajectory]
|
||||
|
||||
task_idx = rollout.task.idx
|
||||
example_id = sample["example_id"]
|
||||
try:
|
||||
problem_id = int(task_idx) if task_idx is not None else sample_id
|
||||
problem_id = int(example_id) if example_id is not None else sample_id
|
||||
except (TypeError, ValueError):
|
||||
problem_id = sample_id
|
||||
|
||||
trajectory_data = [
|
||||
{
|
||||
"messages": [m.model_dump(mode="json") for m in branch.messages],
|
||||
"reward": rollout.reward,
|
||||
"advantage": rollout.scalar_advantage(),
|
||||
"num_input_tokens": branch.num_input_tokens,
|
||||
"num_output_tokens": branch.num_output_tokens,
|
||||
}
|
||||
for branch in branches
|
||||
]
|
||||
|
||||
rows.append(
|
||||
{
|
||||
"run_id": self.run_id,
|
||||
@@ -363,18 +357,18 @@ class PrimeMonitor(Monitor):
|
||||
"problem_id": problem_id,
|
||||
"sample_id": sample_id,
|
||||
"prompt": "",
|
||||
"completion": json.dumps(main_messages),
|
||||
"trajectory": json.dumps(trajectory_data),
|
||||
"completion": json.dumps(sample["completion"]),
|
||||
"trajectory": json.dumps(trajectory),
|
||||
"answer": "",
|
||||
"env_name": rollout.env_name,
|
||||
"task": rollout.task.model_dump_json(),
|
||||
"task": json.dumps(sample["task"]),
|
||||
"info": json.dumps(rollout.info),
|
||||
"reward": rollout.reward,
|
||||
"advantage": rollout.scalar_advantage(),
|
||||
"metrics": json.dumps(rollout.metrics),
|
||||
"timing": rollout.timing.model_dump_json(),
|
||||
"num_input_tokens": branches[-1].num_input_tokens,
|
||||
"num_output_tokens": branches[-1].num_output_tokens,
|
||||
"reward": sample["reward"],
|
||||
"advantage": advantage,
|
||||
"metrics": json.dumps(sample["metrics"]),
|
||||
"timing": json.dumps(sample["timing"]),
|
||||
"num_input_tokens": trajectory[-1]["num_input_tokens"],
|
||||
"num_output_tokens": trajectory[-1]["num_output_tokens"],
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -2,15 +2,20 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import wandb
|
||||
import wandb_workspaces.reports.v2 as wr
|
||||
import wandb_workspaces.workspaces as ws
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from wandb.errors import CommError
|
||||
from wandb.sdk.mailbox.mailbox_handle import ServerResponseError
|
||||
from wandb_gql import gql
|
||||
|
||||
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
@@ -48,6 +53,8 @@ class WandbMonitor(Monitor):
|
||||
tokenizer: PreTrainedTokenizer | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
train_env_names: list[str] = [],
|
||||
eval_env_names: list[str] = [],
|
||||
):
|
||||
self.config = config
|
||||
self.logger = get_logger()
|
||||
@@ -82,11 +89,13 @@ class WandbMonitor(Monitor):
|
||||
x_update_finish_state=primary,
|
||||
)
|
||||
self.logger.info(f"Using shared W&B mode ({label=}, {primary=})")
|
||||
is_online = True
|
||||
else:
|
||||
run_id = None
|
||||
primary = False
|
||||
mode = os.environ.get("WANDB_MODE", "offline" if config.offline else "online")
|
||||
settings = wandb.Settings(mode=mode)
|
||||
is_online = mode == "online"
|
||||
|
||||
retryable_errors = (CommError, ServerResponseError) if shared_mode else (CommError,)
|
||||
|
||||
@@ -129,6 +138,22 @@ class WandbMonitor(Monitor):
|
||||
|
||||
wandb.define_metric("*", step_metric="step")
|
||||
|
||||
# Provision the curated "overview" saved view once per project (the run's primary process
|
||||
# in shared mode, else the single master). Best-effort: a workspaces/API failure must never
|
||||
# take down training.
|
||||
if is_online and (primary if shared_mode else True):
|
||||
try:
|
||||
url = ensure_overview_view(
|
||||
self.wandb.entity,
|
||||
self.wandb.project,
|
||||
train_envs=train_env_names,
|
||||
eval_envs=eval_env_names,
|
||||
)
|
||||
if url:
|
||||
self.logger.info(f"Created W&B overview view - {url}")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to create W&B overview view - {e}")
|
||||
|
||||
# Optionally, initialize sample logging attributes
|
||||
if config is not None and isinstance(config, WandbWithExtrasConfig) and config.log_extras:
|
||||
if config.log_extras.samples:
|
||||
@@ -262,3 +287,162 @@ class WandbMonitor(Monitor):
|
||||
dir_path.mkdir(parents=True, exist_ok=True)
|
||||
with open(dir_path / filename, "w") as f:
|
||||
json.dump(wandb.summary._as_dict(), f)
|
||||
|
||||
|
||||
# --- curated "overview" saved view -------------------------------------------------------------
|
||||
# prime-rl logs many metrics; the default workspace auto-generates a panel per key, which buries the
|
||||
# few that matter. These build a named saved view grouping the important metrics into sections, so a
|
||||
# new project gets a usable overview without hand-picking panels. Panels are untitled — each shows
|
||||
# its raw metric name.
|
||||
|
||||
OVERVIEW_NAME = "overview"
|
||||
|
||||
# Per-rollout metrics (under "<scope>/all/") shown for BOTH train and eval. Only the reward metric
|
||||
# differs — train uses "reward/mean", eval uses "avg@k" — and each section builder prepends its own.
|
||||
COMMON_METRICS = [
|
||||
"has_error/mean",
|
||||
"is_truncated/mean",
|
||||
"num_total_tokens/mean",
|
||||
"num_turns/mean",
|
||||
"num_branches/mean",
|
||||
]
|
||||
|
||||
STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"]
|
||||
|
||||
PERFORMANCE_METRICS = [
|
||||
"perf/mfu",
|
||||
"time/step",
|
||||
"time/wait_for_batch",
|
||||
"time/wait_for_policy",
|
||||
"inference/agg/throughput",
|
||||
"inference/agg/running_requests",
|
||||
"inference/agg/waiting_requests",
|
||||
"inference/agg/kv_cache_usage_mean",
|
||||
"inference/agg/prefix_cache_hit_rate",
|
||||
]
|
||||
|
||||
# Dense grid: more, smaller panels per row and enough rows that sections don't paginate.
|
||||
COLUMNS = 4
|
||||
ROWS = 6
|
||||
|
||||
|
||||
def line_panels(metrics: Sequence[str], regexes: Sequence[str]) -> list[wr.LinePlot]:
|
||||
# inference/* is logged against wall time (step_metric="_timestamp") → "WallTime" (== W&B's
|
||||
# "_timestamp"); everything else on "step" (prime-rl's logged training step, not internal "Step").
|
||||
# x is set per-panel because LinePlot defaults it to "Step", which overrides the workspace x_axis.
|
||||
return [wr.LinePlot(x="WallTime" if m.startswith("inference/") else "step", y=[m]) for m in metrics] + [
|
||||
wr.LinePlot(x="step", metric_regex=r) for r in regexes
|
||||
]
|
||||
|
||||
|
||||
def section(name: str, metrics: Sequence[str] = (), regexes: Sequence[str] = ()) -> ws.Section:
|
||||
return ws.Section(
|
||||
name=name,
|
||||
is_open=True,
|
||||
panels=line_panels(metrics, regexes),
|
||||
layout_settings=ws.SectionLayoutSettings(columns=COLUMNS, rows=ROWS),
|
||||
)
|
||||
|
||||
|
||||
def train_section(name: str, scope: str) -> ws.Section:
|
||||
return section(name, metrics=[f"{scope}/all/reward/mean"] + [f"{scope}/all/{m}" for m in COMMON_METRICS])
|
||||
|
||||
|
||||
def eval_section(name: str, env_pattern: str) -> ws.Section:
|
||||
# Same metrics as train, but eval's reward is "avg@k" (dynamic k → regex). Everything is a regex so
|
||||
# one section can also serve any env (env_pattern=".*"). Only the "all" subset, like train.
|
||||
return section(
|
||||
name,
|
||||
regexes=[f"eval/{env_pattern}/all/avg@.*"] + [f"eval/{env_pattern}/all/{m}" for m in COMMON_METRICS],
|
||||
)
|
||||
|
||||
|
||||
def build_sections(train_envs: Sequence[str] = (), eval_envs: Sequence[str] = ()) -> list[ws.Section]:
|
||||
# With one env the aggregate == that env, so show only its section. With several, put the
|
||||
# cross-env aggregate on top followed by a section per env.
|
||||
if len(train_envs) == 1:
|
||||
sections = [train_section(f"train/{train_envs[0]}", f"train/{train_envs[0]}")]
|
||||
elif len(train_envs) > 1:
|
||||
sections = [train_section("train/agg", "train/agg")]
|
||||
sections += [train_section(f"train/{env}", f"train/{env}") for env in train_envs]
|
||||
else:
|
||||
# Env names unknown (e.g. SFT): fall back to the aggregate.
|
||||
sections = [train_section("train", "train/agg")]
|
||||
if eval_envs:
|
||||
sections += [eval_section(f"eval/{env}", re.escape(env)) for env in eval_envs]
|
||||
else:
|
||||
# Env names unknown (e.g. SFT): one regex section matching any eval env.
|
||||
sections.append(eval_section("eval", ".*"))
|
||||
sections.append(section("stability", metrics=STABILITY_METRICS))
|
||||
sections.append(section("performance", metrics=PERFORMANCE_METRICS))
|
||||
return sections
|
||||
|
||||
|
||||
def list_views(entity: str, project: str) -> list[tuple[str, str]]:
|
||||
"""``(display_name, internal_name)`` for every saved view in the project."""
|
||||
query = gql(
|
||||
"""
|
||||
query Views($entity: String!, $project: String!) {
|
||||
project(name: $project, entityName: $entity) {
|
||||
allViews(viewType: "project-view") { edges { node { name displayName } } }
|
||||
}
|
||||
}
|
||||
"""
|
||||
)
|
||||
res = wandb.Api().client.execute(query, variable_values={"entity": entity, "project": project})
|
||||
edges = ((res.get("project") or {}).get("allViews") or {}).get("edges") or []
|
||||
return [(e["node"]["displayName"], e["node"]["name"]) for e in edges if e.get("node")]
|
||||
|
||||
|
||||
def env_signature(train_envs: Sequence[str], eval_envs: Sequence[str]) -> tuple:
|
||||
return (tuple(sorted(train_envs)), tuple(sorted(eval_envs)))
|
||||
|
||||
|
||||
def view_env_signature(sections: Sequence[ws.Section]) -> tuple:
|
||||
"""Reconstruct the ``(train, eval)`` env set a view was built for from its section names."""
|
||||
train = sorted(s.name[len("train/") :] for s in sections if s.name.startswith("train/") and s.name != "train/agg")
|
||||
evals = sorted(s.name[len("eval/") :] for s in sections if s.name.startswith("eval/"))
|
||||
return (tuple(train), tuple(evals))
|
||||
|
||||
|
||||
def next_overview_name(base: str, existing: Sequence[str]) -> str:
|
||||
if base not in existing:
|
||||
return base
|
||||
prefix = f"{base}-v"
|
||||
versions = [1] + [int(n[len(prefix) :]) for n in existing if n.startswith(prefix) and n[len(prefix) :].isdigit()]
|
||||
return f"{base}-v{max(versions) + 1}"
|
||||
|
||||
|
||||
def ensure_overview_view(
|
||||
entity: str,
|
||||
project: str,
|
||||
name: str = OVERVIEW_NAME,
|
||||
train_envs: Sequence[str] = (),
|
||||
eval_envs: Sequence[str] = (),
|
||||
) -> str | None:
|
||||
"""Ensure an overview saved view exists for this run's env set. Reuses an existing overview built
|
||||
for the same envs; when the env set is new, creates a fresh versioned view (``overview`` →
|
||||
``overview-v2`` → …). Returns the URL of a newly created view, else None."""
|
||||
target = env_signature(train_envs, eval_envs)
|
||||
overviews = [(dn, iname) for dn, iname in list_views(entity, project) if dn == name or dn.startswith(f"{name}-v")]
|
||||
for _, internal_name in overviews:
|
||||
slug = internal_name.removeprefix("nw-").removesuffix("-v")
|
||||
try:
|
||||
existing = ws.Workspace.from_url(f"https://wandb.ai/{entity}/{project}?nw={slug}")
|
||||
matches = view_env_signature(existing.sections) == target
|
||||
except Exception as e:
|
||||
# A single unreadable view must not abort reuse detection / versioning for the rest.
|
||||
get_logger().warning(f"Could not inspect overview view {internal_name} - {e}")
|
||||
continue
|
||||
if matches:
|
||||
return None
|
||||
workspace = ws.Workspace(
|
||||
entity=entity,
|
||||
project=project,
|
||||
name=next_overview_name(name, [dn for dn, _ in overviews]),
|
||||
sections=build_sections(train_envs, eval_envs),
|
||||
auto_generate_panels=False,
|
||||
settings=ws.WorkspaceSettings(x_axis="step"),
|
||||
)
|
||||
workspace.save()
|
||||
return workspace.url
|
||||
|
||||
@@ -73,6 +73,13 @@ def get_rollout_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "rollouts"
|
||||
|
||||
|
||||
def get_trace_path(output_dir: Path, step: int, kind: str, subset: str) -> Path:
|
||||
"""Where one trace file lives: ``rollouts/step_{n}/{train,eval}/{all,effective}/traces.jsonl``.
|
||||
``all`` is appended per rollout the moment it completes; ``effective`` is written at once
|
||||
per finalized train batch / eval epoch."""
|
||||
return get_step_path(get_rollout_dir(output_dir), step) / kind / subset / "traces.jsonl"
|
||||
|
||||
|
||||
def get_eval_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "evals"
|
||||
|
||||
@@ -150,7 +157,7 @@ def validate_output_dir(output_dir: Path, *, resuming: bool, clean: bool, ckpt_o
|
||||
|
||||
|
||||
def clean_future_steps(output_dir: Path, resume_step: int) -> None:
|
||||
"""Remove stale rollouts and broadcasts past ``resume_step``.
|
||||
"""Remove stale rollouts, broadcasts, and traces past ``resume_step``.
|
||||
|
||||
Pass ``resume_step=-1`` to wipe every step directory (fresh runs).
|
||||
"""
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import hashlib
|
||||
|
||||
import torch
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.optim.optimizer import Optimizer
|
||||
|
||||
TENSOR_SIG_SAMPLE_SIZE = 1000
|
||||
|
||||
|
||||
def get_tensor_signature(a: torch.Tensor | torch.nn.Parameter) -> str:
|
||||
while isinstance(a, torch.nn.Parameter):
|
||||
a = a.data
|
||||
|
||||
if isinstance(a, DTensor):
|
||||
a = a.to_local()
|
||||
|
||||
if a.device == torch.device("meta"):
|
||||
return f"{a.dtype}{a.shape}<meta>"
|
||||
|
||||
if a.numel() < TENSOR_SIG_SAMPLE_SIZE:
|
||||
b = a.as_strided(size=(a.numel(),), stride=(1,))
|
||||
else:
|
||||
step_size = a.numel() // TENSOR_SIG_SAMPLE_SIZE
|
||||
b = a.as_strided(size=(TENSOR_SIG_SAMPLE_SIZE,), stride=(step_size,))
|
||||
element_str = "".join([f"{x:.3e}" for x in b])
|
||||
element_hash = hashlib.md5(element_str.encode("utf-8")).hexdigest()
|
||||
return f"{a.dtype}{a.shape}{a.stride()}<{element_hash}>"
|
||||
|
||||
|
||||
def get_signature(state_dict, compress: bool = True) -> str:
|
||||
if compress:
|
||||
return hashlib.md5(str(state_dict).encode("utf-8")).hexdigest()
|
||||
else:
|
||||
return "\n".join(f"{name}: {sig}" for name, sig in state_dict.items())
|
||||
|
||||
|
||||
def get_optimizer_signature(optimizer: Optimizer, compress: bool = True) -> str:
|
||||
def unwrap_tensor(state_dict: dict) -> dict:
|
||||
new_dict = {}
|
||||
for key, value in state_dict.items():
|
||||
if isinstance(value, dict):
|
||||
new_dict[key] = unwrap_tensor(value)
|
||||
elif isinstance(value, torch.Tensor):
|
||||
new_dict[key] = get_tensor_signature(value)
|
||||
else:
|
||||
new_dict[key] = str(value)
|
||||
return new_dict
|
||||
|
||||
state_dict_sig = unwrap_tensor(optimizer.state_dict())
|
||||
return get_signature(state_dict_sig, compress)
|
||||
|
||||
|
||||
def get_module_signature(module: torch.nn.Module, compress: bool = True) -> str:
|
||||
param_sig = {name: get_tensor_signature(param) for name, param in module.named_parameters()}
|
||||
buffer_sig = {name: get_tensor_signature(buffer) for name, buffer in module.named_buffers()}
|
||||
state_dict_sig = {**param_sig, **buffer_sig}
|
||||
return get_signature(state_dict_sig, compress)
|
||||
@@ -39,11 +39,6 @@ def import_object(dotted_path: str) -> Any:
|
||||
return getattr(module, name)
|
||||
|
||||
|
||||
def capitalize(s: str) -> str:
|
||||
"""Capitalize the first letter of a string."""
|
||||
return s[0].upper() + s[1:]
|
||||
|
||||
|
||||
def clean_exit(func: Callable) -> Callable:
|
||||
"""
|
||||
A decorator that ensures the a torch.distributed process group is properly
|
||||
@@ -113,26 +108,6 @@ def to_col_format(list_of_dicts: list[dict[str, Any]]) -> dict[str, list[Any]]:
|
||||
return dict(dict_of_lists)
|
||||
|
||||
|
||||
def to_row_format(dict_of_lists: dict[str, list[Any]]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Turns a dict of lists to a list of dicts.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
dict_of_lists = {"a": [1, 3], "b": [2, 4]} # Column format
|
||||
to_row_format(dict_of_lists)
|
||||
```
|
||||
|
||||
Returns:
|
||||
|
||||
```python
|
||||
[{"a": 1, "b": 2}, {"a": 3, "b": 4}] # Row format
|
||||
```
|
||||
"""
|
||||
return [dict(zip(dict_of_lists.keys(), values)) for values in zip(*dict_of_lists.values())]
|
||||
|
||||
|
||||
def format_time(time_s: float) -> str:
|
||||
"""
|
||||
Format a time in seconds to a human-readable format:
|
||||
@@ -188,15 +163,6 @@ def get_free_port() -> int:
|
||||
return port
|
||||
|
||||
|
||||
def get_cuda_visible_devices() -> list[int]:
|
||||
"""Returns the list of availble CUDA devices, taking into account the CUDA_VISIBLE_DEVICES environment variable."""
|
||||
cuda_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
|
||||
if cuda_visible is None:
|
||||
# Default to all devices if the environment variable is not set
|
||||
return list(range(torch.cuda.device_count()))
|
||||
return list(sorted([int(device) for device in cuda_visible.split(",")]))
|
||||
|
||||
|
||||
def get_latest_ckpt_step(weights_dir: Path) -> int | None:
|
||||
step_dirs = list(weights_dir.glob("step_*"))
|
||||
if len(step_dirs) == 0:
|
||||
@@ -208,17 +174,6 @@ def get_latest_ckpt_step(weights_dir: Path) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def mean(values: list[float] | list[int]) -> float:
|
||||
"""Compute the mean of a list of values."""
|
||||
return sum(values) / len(values) if values else 0.0
|
||||
|
||||
|
||||
def mean_normalize(values: list[float] | list[int]) -> list[float]:
|
||||
"""Mean-Normalize a list of values to 0-1."""
|
||||
sum_values = sum(values)
|
||||
return [value / sum_values if sum_values > 0 else 0.0 for value in values]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def default_dtype(dtype):
|
||||
prev = torch.get_default_dtype()
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import inspect
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5ForCausalLM as HFQwen3_5ForCausalLM
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import FlashAttention, substitute_ring_attn
|
||||
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5Model
|
||||
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
|
||||
|
||||
|
||||
def _tiny_text_config(attn_impl: str = "sdpa") -> Qwen3_5TextConfig:
|
||||
config = Qwen3_5TextConfig(
|
||||
vocab_size=128,
|
||||
hidden_size=64,
|
||||
intermediate_size=128,
|
||||
num_hidden_layers=2,
|
||||
layer_types=["linear_attention", "full_attention"],
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=16,
|
||||
max_position_embeddings=128,
|
||||
linear_key_head_dim=8,
|
||||
linear_value_head_dim=8,
|
||||
linear_num_key_heads=4,
|
||||
linear_num_value_heads=8,
|
||||
linear_conv_kernel_dim=4,
|
||||
)
|
||||
config._attn_implementation = attn_impl
|
||||
return config
|
||||
|
||||
|
||||
def _tiny_moe_config(attn_impl: str = "sdpa") -> Qwen3_5MoeConfig:
|
||||
config = Qwen3_5MoeConfig(
|
||||
vocab_size=128,
|
||||
hidden_size=64,
|
||||
num_hidden_layers=2,
|
||||
layer_types=["linear_attention", "full_attention"],
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=16,
|
||||
max_position_embeddings=128,
|
||||
linear_key_head_dim=8,
|
||||
linear_value_head_dim=8,
|
||||
linear_num_key_heads=4,
|
||||
linear_num_value_heads=8,
|
||||
linear_conv_kernel_dim=4,
|
||||
moe_intermediate_size=128,
|
||||
shared_expert_intermediate_size=128,
|
||||
num_experts=4,
|
||||
num_experts_per_tok=2,
|
||||
use_grouped_mm=False,
|
||||
)
|
||||
config._attn_implementation = attn_impl
|
||||
return config
|
||||
|
||||
|
||||
def test_qwen3_5_dense_matches_hf_state_keys_on_meta():
|
||||
config = _tiny_text_config()
|
||||
with torch.device("meta"):
|
||||
hf_model = HFQwen3_5ForCausalLM(config)
|
||||
prime_model = Qwen3_5ForCausalLM(config)
|
||||
|
||||
assert set(prime_model.state_dict()) == set(hf_model.state_dict())
|
||||
for name, tensor in prime_model.state_dict().items():
|
||||
assert tensor.shape == hf_model.state_dict()[name].shape, name
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attn_impl", ["flash_attention_3", "kernels-community/vllm-flash-attn3"])
|
||||
def test_qwen3_5_full_attention_uses_custom_class(attn_impl: str):
|
||||
config = _tiny_text_config(attn_impl=attn_impl)
|
||||
with torch.device("meta"):
|
||||
model = Qwen3_5Model(config)
|
||||
|
||||
assert isinstance(model.layers[1].self_attn, Qwen3_5GatedFlashAttention)
|
||||
assert model.config._attn_implementation == "flash_attention_3"
|
||||
assert "ALL_ATTENTION_FUNCTIONS" not in inspect.getsource(type(model.layers[1].self_attn).forward)
|
||||
|
||||
|
||||
def test_qwen3_5_moe_full_attention_normalizes_fa3_hub_alias():
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
Qwen3_5MoeGatedFlashAttention,
|
||||
Qwen3_5MoeModel,
|
||||
)
|
||||
|
||||
config = _tiny_moe_config(attn_impl="kernels-community/vllm-flash-attn3")
|
||||
with torch.device("meta"):
|
||||
model = Qwen3_5MoeModel(config)
|
||||
|
||||
assert isinstance(model.layers[1].self_attn, Qwen3_5MoeGatedFlashAttention)
|
||||
assert model.config._attn_implementation == "flash_attention_3"
|
||||
|
||||
|
||||
def test_qwen3_5_ring_patches_dense_flash_attention():
|
||||
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
|
||||
|
||||
originals = {
|
||||
cls: cls._compute_attention
|
||||
for cls in (FlashAttention, AfmoeFlashAttention, Qwen3_5MoeGatedFlashAttention, Qwen3_5GatedFlashAttention)
|
||||
}
|
||||
try:
|
||||
substitute_ring_attn(process_group=MagicMock(), heads_k_stride=1)
|
||||
assert Qwen3_5GatedFlashAttention._compute_attention is not originals[Qwen3_5GatedFlashAttention]
|
||||
finally:
|
||||
for cls, method in originals.items():
|
||||
cls._compute_attention = method
|
||||
@@ -92,25 +92,25 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
||||
dp_world_size=1,
|
||||
seq_len=4,
|
||||
pad_to_multiple_of=1,
|
||||
tokenizer=None,
|
||||
config=FileSystemTransportConfig(),
|
||||
bin_cost=build_bin_cost(None),
|
||||
start_step=0,
|
||||
)
|
||||
|
||||
packer.buffers[run_idx].append((make_training_sample(), 0))
|
||||
packer.buffers[run_idx].append((make_training_sample(), 0))
|
||||
# Steps are 1-indexed: a fresh run starts at step 1, so the first batch's samples carry step 1.
|
||||
packer.buffers[run_idx].append((make_training_sample(), 1))
|
||||
packer.buffers[run_idx].append((make_training_sample(), 1))
|
||||
|
||||
packer.pack()
|
||||
|
||||
progress = manager.progress[run_idx]
|
||||
assert progress.total_samples == 2
|
||||
assert progress.total_tokens == 4
|
||||
assert progress.step == 1
|
||||
assert progress.step == 2
|
||||
|
||||
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
|
||||
assert micro_batch.run_step == 1
|
||||
|
||||
@@ -76,7 +76,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -91,7 +91,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -106,7 +106,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -282,7 +282,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev389" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -294,6 +294,21 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/3b/00/2344469e2084fb287c2e0b57b72910309874c3245463acd6cf5e3db69324/appdirs-1.4.4-py2.py3-none-any.whl", hash = "sha256:a841dacd6b99318a741b166adb07e19ee71a274450e68237b4650ca1055ab128", size = 9566, upload-time = "2020-05-11T07:59:49.499Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arxivmath-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/arxivmath_v1" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "astor"
|
||||
version = "0.8.1"
|
||||
@@ -408,7 +423,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "httpx" },
|
||||
{ name = "openai" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -914,7 +929,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1270,7 +1285,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "flash-linear-attention"
|
||||
version = "0.5.2"
|
||||
source = { git = "https://github.com/fla-org/flash-linear-attention#bd67d11782696e4ff54ee6cb411483621ed3d93d" }
|
||||
source = { git = "https://github.com/fla-org/flash-linear-attention#a95475391465272cd3dc11e47d4a7772522dc9b7" }
|
||||
dependencies = [
|
||||
{ name = "einops" },
|
||||
{ name = "transformers" },
|
||||
@@ -1342,7 +1357,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1386,43 +1401,19 @@ http = [
|
||||
{ name = "aiohttp" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "general-agent"
|
||||
version = "0.1.4"
|
||||
source = { editable = "deps/research-environments/environments/general_agent" }
|
||||
dependencies = [
|
||||
{ name = "mcp" },
|
||||
{ name = "tyro" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "mcp", specifier = ">=1.0" },
|
||||
{ name = "pytest", marker = "extra == 'test'" },
|
||||
{ name = "pytest-asyncio", marker = "extra == 'test'" },
|
||||
{ name = "ruff", marker = "extra == 'dev'" },
|
||||
{ name = "ty", marker = "extra == 'dev'" },
|
||||
{ name = "tyro", specifier = ">=0.9" },
|
||||
{ name = "verifiers", extras = ["packages"], specifier = ">=0.1.15.dev17" },
|
||||
]
|
||||
provides-extras = ["dev", "test"]
|
||||
|
||||
[[package]]
|
||||
name = "general-agent-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/general_agent_v1" }
|
||||
dependencies = [
|
||||
{ name = "filelock" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "verifiers" },
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "filelock" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
{ name = "verifiers", extras = ["harbor"], specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1434,21 +1425,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/dc/b7/8c72dedbb950d88a6f64588fcbc590d2a21e2b9f19b36aa6c5016c54ec75/gepa-0.1.1-py3-none-any.whl", hash = "sha256:71ead7c591eafcc727b83509cdc4182f20264800a6ddf8520d61419daeb47466", size = 244246, upload-time = "2026-03-16T10:17:51.922Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gguf"
|
||||
version = "0.19.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "numpy" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "requests" },
|
||||
{ name = "tqdm" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/48/ae/17f1308ae45cd7b08ebb521747d5b23f4efc4d172038a4e228dd5106c3ff/gguf-0.19.0.tar.gz", hash = "sha256:dbadcd6cc7ccd44256f2229fe7c2dff5e8aa5cf0612ab987fd2b1a57e428923f", size = 111220, upload-time = "2026-05-06T13:04:03.667Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/bb/d71d6da82763528c2c2ed6b59a9d6142c6595545a4c448e2085d155e88c2/gguf-0.19.0-py3-none-any.whl", hash = "sha256:70bcd10edfe697fb2dad6e40af2234b9d8ece9a41a99761405121ebda1c3c1cd", size = 118475, upload-time = "2026-05-06T13:04:02.588Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gitdb"
|
||||
version = "4.0.12"
|
||||
@@ -1555,7 +1531,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1570,7 +1546,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1773,7 +1749,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "humming-kernels"
|
||||
version = "0.1.4"
|
||||
version = "0.1.6"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cuda-bindings" },
|
||||
@@ -1787,9 +1763,9 @@ dependencies = [
|
||||
{ name = "tqdm" },
|
||||
{ name = "triton" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f5/f6/05e95b66cca48def9db0d6c40374fe285c7d9c913fe126030bcfb7cb3088/humming_kernels-0.1.4.tar.gz", hash = "sha256:fdaf4f23cc6b03bb1be3fd24aa11dc7798881e5448826e2404b4f12d8096f0d0", size = 117555, upload-time = "2026-06-04T03:24:03.504Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/29/5a/fbf574dcd83e9fea6aa3fa96b37bbdec40b8672407b1ed9679efa31fff1d/humming_kernels-0.1.6.tar.gz", hash = "sha256:882b9f382a010165a7cf8eecbad943bfe8d6b17566328fb57611c9a34bdccc9a", size = 214408, upload-time = "2026-06-20T04:04:43.221Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ba/16/d9318061a560305034e14cb7bf6483ffc8735eff6b30f260907dbbd4e85d/humming_kernels-0.1.4-py3-none-any.whl", hash = "sha256:c85094cd7cf8cdd959c5e2f7f239a7d72a7640ec1f948787434bc06e24e9ed00", size = 161312, upload-time = "2026-06-04T03:24:01.897Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/25/85/490681b9ba24531da91d0bae801d2b26850e5a80bbd02c2efc500756e36b/humming_kernels-0.1.6-py3-none-any.whl", hash = "sha256:e64c0883fca930074bf920f4ba47cbf3acd244d7352f6c74c8d2182439770d8f", size = 178759, upload-time = "2026-06-20T04:04:41.66Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
@@ -1823,7 +1799,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "orjson" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev389" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1838,7 +1814,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1887,7 +1863,7 @@ requires-dist = [
|
||||
{ name = "setuptools", specifier = "<78" },
|
||||
{ name = "spacy" },
|
||||
{ name = "syllapy" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev389" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1908,7 +1884,7 @@ requires-dist = [
|
||||
{ name = "immutabledict" },
|
||||
{ name = "langdetect" },
|
||||
{ name = "nltk" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev389" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2365,7 +2341,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "huggingface-hub" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev382" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2419,7 +2395,7 @@ requires-dist = [
|
||||
{ name = "markdown", specifier = ">=3.5.1" },
|
||||
{ name = "math-verify", specifier = ">=0.8.0" },
|
||||
{ name = "sympy", specifier = ">=1.12.0" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev17" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2459,7 +2435,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "longcot", git = "https://github.com/LongHorizonReasoning/longcot.git?rev=6a569ab" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2476,7 +2452,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "longcot", git = "https://github.com/LongHorizonReasoning/longcot.git?rev=6a569ab" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2491,7 +2467,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets", specifier = ">=3.0" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2561,7 +2537,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "math-verify", specifier = ">=0.8.0" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.19" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev17" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2576,7 +2552,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2620,7 +2596,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2763,7 +2739,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2837,7 +2813,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "filelock" },
|
||||
{ name = "httpx" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3350,7 +3326,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "huggingface-hub" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3367,7 +3343,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3386,7 +3362,7 @@ requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3468,7 +3444,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3605,7 +3581,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev394" }]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev411" }]
|
||||
|
||||
[[package]]
|
||||
name = "orderly-set"
|
||||
@@ -3686,7 +3662,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3728,7 +3704,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "nltk", specifier = ">=3.8" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev389" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3956,9 +3932,10 @@ dependencies = [
|
||||
{ name = "transformers" },
|
||||
{ name = "uvloop" },
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
{ name = "vllm", version = "0.23.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
|
||||
{ name = "vllm", version = "0.23.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "vllm", version = "0.24.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
|
||||
{ name = "vllm", version = "0.24.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "wandb" },
|
||||
{ name = "wandb-workspaces" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
@@ -3987,13 +3964,13 @@ envs = [
|
||||
{ name = "alphabet-sort" },
|
||||
{ name = "alphabet-sort-v1" },
|
||||
{ name = "apex-shortlist-v1" },
|
||||
{ name = "arxivmath-v1" },
|
||||
{ name = "browsecomp-v1" },
|
||||
{ name = "code-golf-v1" },
|
||||
{ name = "color-codeword-v1" },
|
||||
{ name = "deepdive-v1" },
|
||||
{ name = "deepwiki-v1" },
|
||||
{ name = "forth-lang-v1" },
|
||||
{ name = "general-agent" },
|
||||
{ name = "general-agent-v1" },
|
||||
{ name = "glossary-v1" },
|
||||
{ name = "gpqa-v1" },
|
||||
@@ -4027,7 +4004,7 @@ envs = [
|
||||
{ name = "redsearcher-v1" },
|
||||
{ name = "reverse-text" },
|
||||
{ name = "reverse-text-v1" },
|
||||
{ name = "rlm-search" },
|
||||
{ name = "s1-deepresearch-v1" },
|
||||
{ name = "scaleswe-v1" },
|
||||
{ name = "simpleqa-v1" },
|
||||
{ name = "simpleqa-verified-v1" },
|
||||
@@ -4036,6 +4013,7 @@ envs = [
|
||||
{ name = "swelego-v1" },
|
||||
{ name = "tau2-bench-v1" },
|
||||
{ name = "terminal-bench-2-v1" },
|
||||
{ name = "tmax-v1" },
|
||||
{ name = "unscramble-v1" },
|
||||
{ name = "uuid-ctf-v1" },
|
||||
{ name = "verbatim-copy-v1" },
|
||||
@@ -4087,6 +4065,7 @@ requires-dist = [
|
||||
{ name = "alphabet-sort", marker = "extra == 'envs'", editable = "deps/verifiers/environments/alphabet_sort" },
|
||||
{ name = "alphabet-sort-v1", marker = "extra == 'envs'", editable = "deps/verifiers/environments/alphabet_sort_v1" },
|
||||
{ name = "apex-shortlist-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/apex_shortlist_v1" },
|
||||
{ name = "arxivmath-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/arxivmath_v1" },
|
||||
{ name = "beartype", specifier = ">=0.21.0" },
|
||||
{ name = "browsecomp-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/browsecomp_v1" },
|
||||
{ name = "code-golf-v1", marker = "extra == 'envs'", editable = "deps/verifiers/environments/code_golf_v1" },
|
||||
@@ -4102,7 +4081,6 @@ requires-dist = [
|
||||
{ name = "flash-attn-4", marker = "extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=96bd151" },
|
||||
{ name = "flash-linear-attention", git = "https://github.com/fla-org/flash-linear-attention" },
|
||||
{ name = "forth-lang-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/forth_lang_v1" },
|
||||
{ name = "general-agent", marker = "extra == 'envs'", editable = "deps/research-environments/environments/general_agent" },
|
||||
{ name = "general-agent-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/general_agent_v1" },
|
||||
{ name = "glossary-v1", marker = "extra == 'envs'", editable = "deps/verifiers/environments/glossary_v1" },
|
||||
{ name = "gpqa-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/gpqa_v1" },
|
||||
@@ -4159,29 +4137,30 @@ requires-dist = [
|
||||
{ name = "pybase64", specifier = ">=1.4.2" },
|
||||
{ name = "pyzmq", specifier = ">=27.1.0" },
|
||||
{ name = "quack-kernels", marker = "extra == 'quack'", specifier = ">=0.4.1" },
|
||||
{ name = "r2e-gym-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/r2e_gym_v1" },
|
||||
{ name = "r2e-gym-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/swe/r2e_gym_v1" },
|
||||
{ name = "redsearcher-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/redsearcher_v1" },
|
||||
{ name = "renderers", editable = "deps/renderers" },
|
||||
{ name = "reverse-text", marker = "extra == 'envs'", editable = "deps/verifiers/environments/reverse_text" },
|
||||
{ name = "reverse-text-v1", marker = "extra == 'envs'", editable = "deps/verifiers/environments/reverse_text_v1" },
|
||||
{ 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 = "scaleswe-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/scaleswe_v1" },
|
||||
{ name = "s1-deepresearch-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/s1_deepresearch_v1" },
|
||||
{ name = "scaleswe-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/swe/scaleswe_v1" },
|
||||
{ name = "setproctitle", specifier = ">=1.3.0" },
|
||||
{ name = "simpleqa-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/simpleqa_v1" },
|
||||
{ name = "simpleqa-verified-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/simpleqa_verified_v1" },
|
||||
{ name = "swebench-pro-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/swebench_pro_v1" },
|
||||
{ name = "swebench-verified-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/swebench_verified_v1" },
|
||||
{ name = "swelego-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/swelego_v1" },
|
||||
{ name = "swebench-pro-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/swe/swebench_pro_v1" },
|
||||
{ name = "swebench-verified-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/swe/swebench_verified_v1" },
|
||||
{ name = "swelego-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/swe/swelego_v1" },
|
||||
{ name = "tau2-bench-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/tau2_bench_v1" },
|
||||
{ name = "tenacity", specifier = ">=8.2.0" },
|
||||
{ name = "terminal-bench-2-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/terminal_bench_2_v1" },
|
||||
{ name = "tilelang", specifier = ">=0.1.8" },
|
||||
{ name = "tmax-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/tmax_v1" },
|
||||
{ name = "torch", specifier = ">=2.9.0", index = "https://download.pytorch.org/whl/cu128" },
|
||||
{ name = "torchaudio", index = "https://download.pytorch.org/whl/cu128" },
|
||||
{ name = "torchdata", specifier = ">=0.11.0" },
|
||||
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
|
||||
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=23e4dfc" },
|
||||
{ name = "torchvision", index = "https://download.pytorch.org/whl/cu128" },
|
||||
{ name = "transformers", specifier = "==5.6.2" },
|
||||
{ name = "unscramble-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/unscramble_v1" },
|
||||
@@ -4189,11 +4168,12 @@ requires-dist = [
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verbatim-copy-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/verbatim_copy_v1" },
|
||||
{ name = "verifiers", extras = ["harbor"], editable = "deps/verifiers" },
|
||||
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64'", specifier = ">=0.23.0" },
|
||||
{ name = "vllm", marker = "platform_machine == 'aarch64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine == 'x86_64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64'", specifier = ">=0.24.0" },
|
||||
{ name = "vllm", marker = "platform_machine == 'aarch64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine == 'x86_64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.26.1" },
|
||||
{ name = "wandb-workspaces", specifier = ">=0.4.3" },
|
||||
{ name = "wideseek-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/wideseek_v1" },
|
||||
{ name = "wiki-search", marker = "extra == 'envs'", editable = "deps/verifiers/environments/wiki_search" },
|
||||
{ name = "wiki-search-v1", marker = "extra == 'envs'", editable = "deps/verifiers/environments/wiki_search_v1" },
|
||||
@@ -4290,15 +4270,15 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "prometheus-fastapi-instrumentator"
|
||||
version = "7.1.0"
|
||||
version = "8.0.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "prometheus-client" },
|
||||
{ name = "starlette" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/69/6d/24d53033cf93826aa7857699a4450c1c67e5b9c710e925b1ed2b320c04df/prometheus_fastapi_instrumentator-7.1.0.tar.gz", hash = "sha256:be7cd61eeea4e5912aeccb4261c6631b3f227d8924542d79eaf5af3f439cbe5e", size = 20220, upload-time = "2025-03-19T19:35:05.351Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/1b/e9/2065686d1dfa62296fdc158b6e8fd25b0cb3dca09b0632cabeb5ae81fe4d/prometheus_fastapi_instrumentator-8.0.2.tar.gz", hash = "sha256:3c252e748151768a7aefd66824a04a870144f71de48a67aed211749a9ca2a548", size = 21342, upload-time = "2026-06-23T09:39:31.611Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/27/72/0824c18f3bc75810f55dacc2dd933f6ec829771180245ae3cc976195dec0/prometheus_fastapi_instrumentator-7.1.0-py3-none-any.whl", hash = "sha256:978130f3c0bb7b8ebcc90d35516a6fe13e02d2eb358c8f83887cdef7020c31e9", size = 19296, upload-time = "2025-03-19T19:35:04.323Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c6/c7/fa2b3f469a2e6001b829e0d6bc8680755349aa1329a87bf48731e9d5d30a/prometheus_fastapi_instrumentator-8.0.2-py3-none-any.whl", hash = "sha256:746002ec1e2c58b93f61444e1d104de959a9463a6a3f1c8909ac3757e16c3866", size = 20549, upload-time = "2026-06-23T09:39:32.616Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4726,7 +4706,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "r2e-gym-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/r2e_gym_v1" }
|
||||
source = { editable = "deps/research-environments/environments/swe/r2e_gym_v1" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -4735,7 +4715,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev434" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4786,7 +4766,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4953,27 +4933,6 @@ 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" },
|
||||
{ name = "httpx" },
|
||||
{ name = "openai" },
|
||||
{ name = "prime-sandboxes" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[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 = "rpds-py"
|
||||
version = "0.30.0"
|
||||
@@ -4998,6 +4957,21 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ed/c5/8864e4e7925b836ea354b31d57641ec03830564e281a8b6f061f8c3e0ec1/ruff-0.15.14-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:bb01d645694e3ec0102105d07ef2d53703970407d59c04e59d3ba0b7a1d53553", size = 11560214, upload-time = "2026-05-21T14:34:50.975Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "s1-deepresearch-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/s1_deepresearch_v1" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "huggingface-hub" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "safetensors"
|
||||
version = "0.7.0"
|
||||
@@ -5013,7 +4987,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "scaleswe-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/scaleswe_v1" }
|
||||
source = { editable = "deps/research-environments/environments/swe/scaleswe_v1" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -5022,7 +4996,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev434" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5160,7 +5134,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5177,7 +5151,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev422" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5313,15 +5287,15 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "starlette"
|
||||
version = "0.52.1"
|
||||
version = "1.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/c4/68/79977123bb7be889ad680d79a40f339082c1978b5cfcf62c2d8d196873ac/starlette-0.52.1.tar.gz", hash = "sha256:834edd1b0a23167694292e94f597773bc3f89f362be6effee198165a35d62933", size = 2653702, upload-time = "2026-01-18T13:34:11.062Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/eb/e3/7c1dc7381d9f8ab7d854328ebfa884e62cb3f3d8549ddfd37c7814f42afa/starlette-1.3.1.tar.gz", hash = "sha256:05d0213193f2fbaae60e2ecb593b4add4262ad4e46536b54abe36f11a71724e0", size = 2703240, upload-time = "2026-06-12T09:23:11.602Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/81/0d/13d1d239a25cbfb19e740db83143e95c772a1fe10202dda4b76792b114dd/starlette-0.52.1-py3-none-any.whl", hash = "sha256:0029d43eb3d273bc4f83a08720b4912ea4b071087a3b48db01b7c839f7954d74", size = 74272, upload-time = "2026-01-18T13:34:09.188Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5406,29 +5380,29 @@ wheels = [
|
||||
[[package]]
|
||||
name = "swebench-pro-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/swebench_pro_v1" }
|
||||
source = { editable = "deps/research-environments/environments/swe/swebench_pro_v1" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev389" }]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev434" }]
|
||||
|
||||
[[package]]
|
||||
name = "swebench-verified-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/swebench_verified_v1" }
|
||||
source = { editable = "deps/research-environments/environments/swe/swebench_verified_v1" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev389" }]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev434" }]
|
||||
|
||||
[[package]]
|
||||
name = "swelego-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/swelego_v1" }
|
||||
source = { editable = "deps/research-environments/environments/swe/swelego_v1" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -5437,7 +5411,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev434" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5516,7 +5490,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "audioop-lts", marker = "python_full_version >= '3.13'" },
|
||||
{ name = "tau2", git = "https://github.com/sierra-research/tau2-bench.git?rev=337326e" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev424" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5566,7 +5540,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev389" }]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev411" }]
|
||||
|
||||
[[package]]
|
||||
name = "textarena"
|
||||
@@ -5703,6 +5677,17 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c6/a7/f4bfb86f87e107703146e703204cec2c0eae2492b633e0052b0ace3febb6/tilelang-0.1.9-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:77ab0ee2f40f66ea015b6b21426d482751e28cbc635ef9d1198cbd6502454a7c", size = 42110365, upload-time = "2026-04-22T09:17:18.292Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tmax-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/tmax_v1" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.1.15.dev434" }]
|
||||
|
||||
[[package]]
|
||||
name = "tokenizers"
|
||||
version = "0.22.2"
|
||||
@@ -5845,7 +5830,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "torchtitan"
|
||||
version = "0.1.0"
|
||||
source = { git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e#a1fdd7e43694bbfeff5d6ad8ac738c067bb90d41" }
|
||||
source = { git = "https://github.com/pytorch/torchtitan?rev=23e4dfc#23e4dfca5ca52587dbaf18f67bee8d73e875df5b" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "fsspec" },
|
||||
@@ -6024,7 +6009,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev389" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6045,7 +6030,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev381" }]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev411" }]
|
||||
|
||||
[[package]]
|
||||
name = "uvicorn"
|
||||
@@ -6094,7 +6079,7 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "faker", specifier = ">=20.0.0" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev389" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6239,8 +6224,8 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "vllm"
|
||||
version = "0.23.0+cu129"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
version = "0.24.0+cu129"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'aarch64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -6261,9 +6246,9 @@ dependencies = [
|
||||
{ name = "filelock" },
|
||||
{ name = "flashinfer-cubin" },
|
||||
{ name = "flashinfer-python" },
|
||||
{ name = "gguf" },
|
||||
{ name = "humming-kernels", extra = ["cu12"] },
|
||||
{ name = "ijson" },
|
||||
{ name = "jsonschema" },
|
||||
{ name = "lark" },
|
||||
{ name = "llguidance" },
|
||||
{ name = "lm-format-enforcer" },
|
||||
@@ -6304,6 +6289,7 @@ dependencies = [
|
||||
{ name = "setproctitle" },
|
||||
{ name = "setuptools" },
|
||||
{ name = "six" },
|
||||
{ name = "starlette" },
|
||||
{ name = "tiktoken" },
|
||||
{ name = "tilelang" },
|
||||
{ name = "tokenizers" },
|
||||
@@ -6318,7 +6304,7 @@ dependencies = [
|
||||
{ name = "xgrammar" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:17ac76bbfad014d5b584a9499bca22d3f871d24db93cbb1eb27a87deef0219aa" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e85edf971a25582993ef3bfd26b0d6ebf498d5ca4ae4944fa8824a734b81ac58" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -6336,17 +6322,17 @@ requires-dist = [
|
||||
{ name = "depyf", specifier = "==0.20.0" },
|
||||
{ name = "diskcache", specifier = "==5.6.3" },
|
||||
{ name = "einops" },
|
||||
{ name = "fastapi", extras = ["standard"], specifier = ">=0.115.0" },
|
||||
{ name = "fastapi", extras = ["standard"], specifier = ">=0.133.0,<0.137.0" },
|
||||
{ name = "fastsafetensors", specifier = ">=0.3.2" },
|
||||
{ name = "fastsafetensors", marker = "extra == 'fastsafetensors'", specifier = ">=0.3.2" },
|
||||
{ name = "filelock", specifier = ">=3.16.1" },
|
||||
{ name = "flashinfer-cubin", specifier = "==0.6.12" },
|
||||
{ name = "flashinfer-python", specifier = "==0.6.12" },
|
||||
{ name = "gguf", specifier = ">=0.17.0" },
|
||||
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.0.0" },
|
||||
{ name = "humming-kernels", extras = ["cu12"], specifier = "==0.1.4" },
|
||||
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.1.0" },
|
||||
{ name = "humming-kernels", extras = ["cu12"], specifier = "==0.1.6" },
|
||||
{ name = "ijson" },
|
||||
{ name = "instanttensor", marker = "extra == 'instanttensor'", specifier = ">=0.1.5" },
|
||||
{ name = "jsonschema", specifier = ">=4.23.0" },
|
||||
{ name = "lark", specifier = "==1.2.2" },
|
||||
{ name = "llguidance", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 'x86_64'", specifier = ">=1.7.0,<1.8.0" },
|
||||
{ name = "lm-format-enforcer", specifier = "==0.11.3" },
|
||||
@@ -6378,7 +6364,7 @@ requires-dist = [
|
||||
{ name = "pillow" },
|
||||
{ name = "plotly", marker = "extra == 'bench'" },
|
||||
{ name = "prometheus-client", specifier = ">=0.18.0" },
|
||||
{ name = "prometheus-fastapi-instrumentator", specifier = ">=7.0.0" },
|
||||
{ name = "prometheus-fastapi-instrumentator", specifier = ">=8.0.0" },
|
||||
{ name = "protobuf", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" },
|
||||
{ name = "psutil" },
|
||||
{ name = "py-cpuinfo" },
|
||||
@@ -6401,6 +6387,8 @@ requires-dist = [
|
||||
{ name = "six", marker = "python_full_version >= '3.12'", specifier = ">=1.16.0" },
|
||||
{ name = "smg-grpc-servicer", extras = ["vllm"], marker = "extra == 'grpc'", specifier = ">=0.5.2" },
|
||||
{ name = "soundfile", marker = "extra == 'audio'" },
|
||||
{ name = "soxr", marker = "extra == 'audio'" },
|
||||
{ name = "starlette", specifier = ">=1.0.1" },
|
||||
{ name = "tensorizer", marker = "extra == 'tensorizer'", specifier = "==2.10.1" },
|
||||
{ name = "tiktoken", specifier = ">=0.6.0" },
|
||||
{ name = "tilelang", specifier = "==0.1.9" },
|
||||
@@ -6410,18 +6398,19 @@ requires-dist = [
|
||||
{ name = "torchaudio", specifier = "==2.11.0" },
|
||||
{ name = "torchvision", specifier = "==0.26.0" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "transformers", specifier = ">=4.56.0,!=5.0.*,!=5.1.*,!=5.2.*,!=5.3.*,!=5.4.*,!=5.5.0" },
|
||||
{ name = "transformers", specifier = ">=5.5.3" },
|
||||
{ name = "typing-extensions", specifier = ">=4.10" },
|
||||
{ name = "vllm-gguf-plugin", marker = "extra == 'extra-quant'", specifier = ">=0.0.2" },
|
||||
{ name = "watchfiles" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.2.0,<1.0.0" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.2.1,<1.0.0" },
|
||||
{ name = "zentorch", marker = "extra == 'zen'", specifier = "==2.11.0.0" },
|
||||
]
|
||||
provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttensor", "runai", "audio", "video", "flashinfer", "helion", "grpc", "otel"]
|
||||
provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttensor", "runai", "audio", "video", "flashinfer", "helion", "grpc", "otel", "extra-quant"]
|
||||
|
||||
[[package]]
|
||||
name = "vllm"
|
||||
version = "0.23.0+cu129"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
version = "0.24.0+cu129"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'x86_64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -6442,9 +6431,9 @@ dependencies = [
|
||||
{ name = "filelock" },
|
||||
{ name = "flashinfer-cubin" },
|
||||
{ name = "flashinfer-python" },
|
||||
{ name = "gguf" },
|
||||
{ name = "humming-kernels", extra = ["cu12"] },
|
||||
{ name = "ijson" },
|
||||
{ name = "jsonschema" },
|
||||
{ name = "lark" },
|
||||
{ name = "llguidance" },
|
||||
{ name = "lm-format-enforcer" },
|
||||
@@ -6485,6 +6474,7 @@ dependencies = [
|
||||
{ name = "setproctitle" },
|
||||
{ name = "setuptools" },
|
||||
{ name = "six" },
|
||||
{ name = "starlette" },
|
||||
{ name = "tiktoken" },
|
||||
{ name = "tilelang" },
|
||||
{ name = "tokenizers" },
|
||||
@@ -6499,7 +6489,7 @@ dependencies = [
|
||||
{ name = "xgrammar" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:8bc2203995d061e6b988916b71b9dee8a5970f5fdc5f37d4445a877a2fab2cc1" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:597949743f2a00c0539d9e2ff0f67b32c608a378e973f99e7529fd6fa9445f70" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -6517,17 +6507,17 @@ requires-dist = [
|
||||
{ name = "depyf", specifier = "==0.20.0" },
|
||||
{ name = "diskcache", specifier = "==5.6.3" },
|
||||
{ name = "einops" },
|
||||
{ name = "fastapi", extras = ["standard"], specifier = ">=0.115.0" },
|
||||
{ name = "fastapi", extras = ["standard"], specifier = ">=0.133.0,<0.137.0" },
|
||||
{ name = "fastsafetensors", specifier = ">=0.3.2" },
|
||||
{ name = "fastsafetensors", marker = "extra == 'fastsafetensors'", specifier = ">=0.3.2" },
|
||||
{ name = "filelock", specifier = ">=3.16.1" },
|
||||
{ name = "flashinfer-cubin", specifier = "==0.6.12" },
|
||||
{ name = "flashinfer-python", specifier = "==0.6.12" },
|
||||
{ name = "gguf", specifier = ">=0.17.0" },
|
||||
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.0.0" },
|
||||
{ name = "humming-kernels", extras = ["cu12"], specifier = "==0.1.4" },
|
||||
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.1.0" },
|
||||
{ name = "humming-kernels", extras = ["cu12"], specifier = "==0.1.6" },
|
||||
{ name = "ijson" },
|
||||
{ name = "instanttensor", marker = "extra == 'instanttensor'", specifier = ">=0.1.5" },
|
||||
{ name = "jsonschema", specifier = ">=4.23.0" },
|
||||
{ name = "lark", specifier = "==1.2.2" },
|
||||
{ name = "llguidance", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 'x86_64'", specifier = ">=1.7.0,<1.8.0" },
|
||||
{ name = "lm-format-enforcer", specifier = "==0.11.3" },
|
||||
@@ -6559,7 +6549,7 @@ requires-dist = [
|
||||
{ name = "pillow" },
|
||||
{ name = "plotly", marker = "extra == 'bench'" },
|
||||
{ name = "prometheus-client", specifier = ">=0.18.0" },
|
||||
{ name = "prometheus-fastapi-instrumentator", specifier = ">=7.0.0" },
|
||||
{ name = "prometheus-fastapi-instrumentator", specifier = ">=8.0.0" },
|
||||
{ name = "protobuf", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" },
|
||||
{ name = "psutil" },
|
||||
{ name = "py-cpuinfo" },
|
||||
@@ -6582,6 +6572,8 @@ requires-dist = [
|
||||
{ name = "six", marker = "python_full_version >= '3.12'", specifier = ">=1.16.0" },
|
||||
{ name = "smg-grpc-servicer", extras = ["vllm"], marker = "extra == 'grpc'", specifier = ">=0.5.2" },
|
||||
{ name = "soundfile", marker = "extra == 'audio'" },
|
||||
{ name = "soxr", marker = "extra == 'audio'" },
|
||||
{ name = "starlette", specifier = ">=1.0.1" },
|
||||
{ name = "tensorizer", marker = "extra == 'tensorizer'", specifier = "==2.10.1" },
|
||||
{ name = "tiktoken", specifier = ">=0.6.0" },
|
||||
{ name = "tilelang", specifier = "==0.1.9" },
|
||||
@@ -6591,13 +6583,14 @@ requires-dist = [
|
||||
{ name = "torchaudio", specifier = "==2.11.0" },
|
||||
{ name = "torchvision", specifier = "==0.26.0" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "transformers", specifier = ">=4.56.0,!=5.0.*,!=5.1.*,!=5.2.*,!=5.3.*,!=5.4.*,!=5.5.0" },
|
||||
{ name = "transformers", specifier = ">=5.5.3" },
|
||||
{ name = "typing-extensions", specifier = ">=4.10" },
|
||||
{ name = "vllm-gguf-plugin", marker = "extra == 'extra-quant'", specifier = ">=0.0.2" },
|
||||
{ name = "watchfiles" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.2.0,<1.0.0" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.2.1,<1.0.0" },
|
||||
{ name = "zentorch", marker = "extra == 'zen'", specifier = "==2.11.0.0" },
|
||||
]
|
||||
provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttensor", "runai", "audio", "video", "flashinfer", "helion", "grpc", "otel"]
|
||||
provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttensor", "runai", "audio", "video", "flashinfer", "helion", "grpc", "otel", "extra-quant"]
|
||||
|
||||
[[package]]
|
||||
name = "vllm-router"
|
||||
@@ -6662,6 +6655,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/94/51/a69ac59300e3c813939d0764348959ed2a21e14c668cb1cebcb04010da6a/wandb-0.27.0-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:17aae6e4a88cd05c00ea8f546220918e3ebb6f8c1c36b70ef04a5ac75f0d7160", size = 27599005, upload-time = "2026-05-14T03:43:50.926Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wandb-workspaces"
|
||||
version = "0.4.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
{ name = "wandb" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/44/90/749e3af75f1bc2685711176f8f0fe6dae38d5b979e4dc160c30cd4373597/wandb_workspaces-0.4.3.tar.gz", hash = "sha256:2c551bc35cadda14ff0c7c3ac1d7bbbb1c95b8f0dbc662ec2c58f3d3d832f854", size = 234226, upload-time = "2026-06-10T22:27:17.22Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c0/8f/0c1bc0b48733935031ef8956a1efb1436e3f4e1a3a402eece169a952672b/wandb_workspaces-0.4.3-py3-none-any.whl", hash = "sha256:4536dbc9d57d3aa59318e770b5c526c087f52b6b9488634b1d393163b9f6da2f", size = 109269, upload-time = "2026-06-10T22:27:15.509Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasabi"
|
||||
version = "1.1.3"
|
||||
@@ -6773,7 +6779,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6830,7 +6836,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev381" }]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev411" }]
|
||||
|
||||
[[package]]
|
||||
name = "wordle"
|
||||
|
||||
Reference in New Issue
Block a user