Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
771953ee01 | ||
|
|
e3dd67633d | ||
|
|
0a437ae340 | ||
|
|
9a55a0899c | ||
|
|
666297d09c | ||
|
|
202f108f33 | ||
|
|
96fa737c35 | ||
|
|
35aa06fbfa | ||
|
|
718635b2ca | ||
|
|
f557d7593f | ||
|
|
f87fd0eb33 | ||
|
|
12001f3167 | ||
|
|
1cf683267d | ||
|
|
b944873248 | ||
|
|
c28afbbae2 | ||
|
|
b963ceda3c | ||
|
|
3cc565eecb | ||
|
|
f52f6a69df |
@@ -43,7 +43,7 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
|
||||
## Skills
|
||||
|
||||
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
|
||||
Skills live in `skills/` and are symlinked to `.claude/skills/` (Claude Code) and `.agents/skills/` (Codex). They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
|
||||
|
||||
If a repository skill could benefit from an update, suggest the specific change, explain why it would help, and ask the user for approval before making it. Wait for approval before creating, modifying, renaming, or deleting skills, including their supporting files and symlinks. If the user has already explicitly requested or approved the skill change, proceed without asking again. Requests to change code, fix workflows, update documentation, or open a PR do not implicitly authorize skill changes. You may read and follow skills without changing them.
|
||||
|
||||
|
||||
+27
-12
@@ -137,26 +137,41 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
|
||||
# Needed for private environments hub auth
|
||||
# Needed for private environments hub auth.
|
||||
#
|
||||
# FIXME(prime#940): workaround, remove once the prime CLI drops verifiers as
|
||||
# a dependency (https://github.com/PrimeIntellect-ai/prime/pull/940). The CLI
|
||||
# pins verifiers==0.2.0, which replaced the editable verifiers synced above
|
||||
# with the PyPI wheel and left prime-rl's own entrypoints unable to import;
|
||||
# the --overrides file ignores that one requirement. When removing it, drop
|
||||
# the overrides file and the --overrides flag, keep the import assertion, and
|
||||
# make the same change in scripts/docker-entrypoint.sh, which replays this
|
||||
# step for the runtime source overlay.
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
VIRTUAL_ENV=/app/.venv uv pip install 'prime>=0.7'
|
||||
printf 'verifiers\n' > /tmp/prime-cli-overrides.txt \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --overrides /tmp/prime-cli-overrides.txt 'prime>=0.7' \
|
||||
&& rm /tmp/prime-cli-overrides.txt \
|
||||
&& /app/.venv/bin/python -c 'import pathlib, verifiers; assert pathlib.Path(verifiers.__file__).is_relative_to("/app/deps/verifiers"), verifiers.__file__'
|
||||
|
||||
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
|
||||
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
|
||||
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
|
||||
# the disaggregated P/D path — default off so training-only / single-node
|
||||
# inference builds are unaffected. Enable via `--build-arg INCLUDE_NIXL_FROM_SOURCE=1`.
|
||||
ARG INCLUDE_NIXL_FROM_SOURCE=0
|
||||
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
|
||||
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
|
||||
# rebuilding against our UCX is the documented fix. The rename is required: an
|
||||
# unrenamed source build is `nixl_cu12`, and the `nixl` shim imports nixl_cu13
|
||||
# (the PyPI wheel) first, so the fix would silently not apply. Libraries carry
|
||||
# RUNPATH=/opt/ucx/lib, so no LD_LIBRARY_PATH is needed at runtime.
|
||||
# Opt out via `--build-arg INCLUDE_NIXL_FROM_SOURCE=0`.
|
||||
ARG INCLUDE_NIXL_FROM_SOURCE=1
|
||||
ARG NIXL_VERSION=0.10.1
|
||||
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
|
||||
VIRTUAL_ENV=/app/.venv uv pip install pip \
|
||||
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
|
||||
&& cd /tmp/nixl \
|
||||
&& uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml \
|
||||
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
|
||||
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
|
||||
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu13-*.whl \
|
||||
&& rm -rf /tmp/nixl /app/deps/nixl_cu13-*.whl; \
|
||||
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/tmp/nixl-whl \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /tmp/nixl-whl/nixl_cu13-*.whl \
|
||||
&& ldd /app/.venv/lib/python3.12/site-packages/.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so | grep -q /opt/ucx/lib/libucp.so \
|
||||
&& rm -rf /tmp/nixl /tmp/nixl-whl; \
|
||||
fi
|
||||
|
||||
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: b677502a20...565e8a74c0
Vendored
+1
-1
Submodule deps/verifiers updated: 69cc0f948e...8854e0da3a
@@ -171,6 +171,15 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — takes an `env` block that each of its sources inherits. A source's own `env` values win. The block holds only the knobs that every env and taskset has: `retries`, `timeout`, `max_concurrent_agents`, `interception`, and `taskset.task` and `taskset.system_prompt`. Ids and agents stay on each source:
|
||||
|
||||
```toml
|
||||
[orchestrator.eval.env]
|
||||
retries.max_retries = 3
|
||||
retries.include = ["ProviderError", "SandboxError"]
|
||||
timeout.episode = 7200
|
||||
```
|
||||
|
||||
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire (inherited from the group-level `interval` when unset); a standalone eval has neither.
|
||||
|
||||
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
|
||||
|
||||
+9
-2
@@ -32,7 +32,7 @@ uv run inference --vllm.model Qwen/Qwen3-4B
|
||||
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1
|
||||
```
|
||||
|
||||
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-r` set `num_examples`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). The shorthands cannot be combined with a TOML that defines `[[source]]` blocks. `uv run eval -h` lists them.
|
||||
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-r` set `num_examples`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). `<taskset-id>` cannot be combined with a TOML that defines `[[source]]` blocks; next to one, `--env.<field>` sets the shared [env block](#configuration) instead. `uv run eval -h` lists them.
|
||||
|
||||
Against a local vLLM deployment, set `min_inflight < max_inflight` in `[concurrency]` to dynamically adjust the number of concurrent episodes for maximum throughput. An external API exposes no vLLM `/metrics` to adapt to, so pin the concurrency there (`-c N`, i.e. `min_inflight = max_inflight`).
|
||||
|
||||
@@ -55,6 +55,10 @@ max_inflight = 256
|
||||
[sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[env] # every source inherits these
|
||||
timeout.episode = 7200
|
||||
retries.max_retries = 3
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "bash"
|
||||
@@ -65,7 +69,9 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
|
||||
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. The top-level `[env]` block holds the env knobs that every source inherits (see [Environments](configuration.md#environments)); a source's own `env` values win.
|
||||
|
||||
Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
|
||||
|
||||
## Resume
|
||||
|
||||
@@ -109,6 +115,7 @@ Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
|
||||
|---|---|
|
||||
| `eval/<env>/all/<agent>/reward/mean` | mean reward over the epoch |
|
||||
| `eval/<env>/all/<agent>/is_truncated/mean` | share of rollouts cut by the length limit |
|
||||
| `eval/<env>/all/<agent>/is_timeout/mean` | share of rollouts stopped by a stage deadline (`<stage>_timeout`) |
|
||||
| `eval/<env>/all/<agent>/has_error/mean` | share of rollouts that raised |
|
||||
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
|
||||
|
||||
|
||||
+1
-1
@@ -117,7 +117,7 @@ CP shards a single sequence across multiple GPUs along the token dimension — f
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "auto" # auto = FA3 on Hopper, FA4 on Blackwell; or flash_attention_2/3/4
|
||||
attn = "auto" # auto = FA3 on Hopper, FA4 on datacenter Blackwell, FA2 otherwise; or flash_attention_2/3/4
|
||||
cp = 2 # CP degree
|
||||
cp_style = "ulysses" # "ring"
|
||||
```
|
||||
|
||||
+2
-1
@@ -118,6 +118,7 @@ Pulled from the console logs and mirrored to W&B.
|
||||
|
||||
- `reward/{all,env}/mean` — main signal. Should trend upward over hundreds of steps.
|
||||
- `seq_len/{all,env}/mean` and `is_truncated/{all,env}/mean` — rollout length and truncation rate.
|
||||
- `is_timeout/{all,env}/mean` — share of rollouts stopped by a stage deadline (`setup`/`agent`/`finalize`/`scoring` `_timeout`). Training counts a timed-out rollout as an error, so it stays out of the batch; eval scores it.
|
||||
- `num_turns/{all,env}/mean` — for multi-turn envs.
|
||||
- `empty_rollouts/{all,env}`, `errored_rollouts/{all,env}` — non-zero is fine in small numbers; sustained > 5% is a smell.
|
||||
- `eval/{env}/{avg@k,pass@k}` — eval scores when `[orchestrator.eval]` is set.
|
||||
@@ -251,7 +252,7 @@ Pulled from the console log and mirrored to W&B.
|
||||
|
||||
- `optim/grad_norm` — spikes precede divergence.
|
||||
- `optim/lr` — LR schedule.
|
||||
- For MoE: `max_vio/mean` (load-balancing violation), `routing_confidence/mean` — both are logged when non-zero.
|
||||
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
|
||||
|
||||
**Performance:**
|
||||
|
||||
|
||||
@@ -100,3 +100,18 @@ Pass several output directories to track parallel experiments side by side (`uv
|
||||
Both RL configs ship without `[ckpt]` — add a `[ckpt]` overlay (e.g. `interval = 100`) for periodic checkpoints. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
|
||||
|
||||
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
|
||||
|
||||
## SFT
|
||||
|
||||
The SFT configs live under [`sft/h200/`](sft/h200) — they are tuned for 8-GPU H200 nodes. Compose the base config with a data overlay:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml
|
||||
```
|
||||
|
||||
This will start a SFT run with the following configuration:
|
||||
|
||||
- The model is `zai-org/GLM-5.3-BF16`
|
||||
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
|
||||
|
||||
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
clean = true
|
||||
|
||||
[env_vars]
|
||||
HF_HOME = "/home/huggingface"
|
||||
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2"
|
||||
cp = 8
|
||||
ep = 8
|
||||
optim_cpu_offload = true
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[optim]
|
||||
type = "sign_sgd"
|
||||
lr = 5e-5
|
||||
weight_decay = 0.01
|
||||
|
||||
[scheduler]
|
||||
type = "linear"
|
||||
warmup_steps = 50
|
||||
decay_steps = 0
|
||||
|
||||
[renderer]
|
||||
name = "glm-5.3"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 8
|
||||
|
||||
[slurm]
|
||||
job_name = "glm53-sft"
|
||||
partition = "all"
|
||||
@@ -0,0 +1,8 @@
|
||||
[model.debug]
|
||||
force_balanced_routing = true
|
||||
|
||||
[data]
|
||||
type = "fake"
|
||||
batch_size = 8
|
||||
micro_batch_size = 1
|
||||
seq_len = 131072
|
||||
@@ -0,0 +1,7 @@
|
||||
[data]
|
||||
type = "sft"
|
||||
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
|
||||
splits = ["math"]
|
||||
batch_size = 8
|
||||
micro_batch_size = 1
|
||||
seq_len = 131072
|
||||
@@ -45,6 +45,7 @@ weight_decay = 0.01
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 2048
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 4096
|
||||
|
||||
@@ -42,6 +42,7 @@ lr = 1e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 8
|
||||
max_off_policy_steps = 8
|
||||
|
||||
[orchestrator.concurrency]
|
||||
|
||||
@@ -43,6 +43,7 @@ lr = 1e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 8
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
|
||||
@@ -10,7 +10,7 @@ dependencies = [
|
||||
"renderers>=0.1.11",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.3.0",
|
||||
"verifiers>=0.3.2.dev143",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -5,7 +5,7 @@ from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig, RunConfig
|
||||
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
|
||||
@@ -26,6 +26,13 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
sandbox-backed environments to pace provisioning during autoscaling. None disables
|
||||
rate limiting."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat for the run: one ping per landed episode — the first
|
||||
landed episode is the first beat, so the run's boot never shows up as a
|
||||
stale-prone silence. When episodes stop landing, the pings stop and the heartbeat
|
||||
goes stale on Better Stack after its grace period. Size that period + grace above
|
||||
the longest legitimate gap between episodes."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str | None]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
|
||||
@@ -3,7 +3,7 @@ from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import Field, SerializeAsAny, model_validator
|
||||
from pydantic import Field, SerializeAsAny, ValidationError, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.algorithm import (
|
||||
@@ -194,6 +194,22 @@ class EnvConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
def merge_group_env(data: Any) -> Any:
|
||||
"""Shared ``mode="before"`` body for source groups: layer the group's ``env`` block
|
||||
under the ``env`` block of each raw source."""
|
||||
if not isinstance(data, dict) or data.get("env") is None:
|
||||
return data
|
||||
try:
|
||||
shared = vf.SharedEnvConfig.model_validate(data["env"])
|
||||
except ValidationError:
|
||||
return data # the ``env`` field reports the errors once, not once per source
|
||||
data["source"] = [
|
||||
{**source, "env": vf.merge_env_defaults(shared, source.get("env"))} if isinstance(source, dict) else source
|
||||
for source in data.get("source") or []
|
||||
]
|
||||
return data
|
||||
|
||||
|
||||
class StandardSamplerConfig(BaseConfig):
|
||||
type: Literal["standard"] = "standard"
|
||||
|
||||
@@ -308,9 +324,18 @@ class TrainConfig(BaseConfig):
|
||||
source: list[TrainSourceConfig] = Field(default_factory=list)
|
||||
"""Training sources."""
|
||||
|
||||
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
|
||||
"""Env knobs that every training source inherits: the fields every env and taskset
|
||||
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
|
||||
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def resolve_group_env(cls, data):
|
||||
return merge_group_env(data)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
|
||||
@@ -341,6 +366,10 @@ class EvalSourcesConfig(BaseConfig):
|
||||
source: list[EvalSourceConfig] = Field(default_factory=list)
|
||||
"""Evaluation sources."""
|
||||
|
||||
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
|
||||
"""Env knobs that every eval source inherits: the fields every env and taskset
|
||||
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
|
||||
|
||||
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
|
||||
"""Shared eval sampling configuration; can differ from training sampling."""
|
||||
|
||||
@@ -350,6 +379,11 @@ class EvalSourcesConfig(BaseConfig):
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def resolve_group_env(cls, data):
|
||||
return merge_group_env(data)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples and
|
||||
|
||||
@@ -574,6 +574,9 @@ class IPOLossConfig(BaseConfig):
|
||||
eps: float = Field(0.3, ge=0)
|
||||
"""Maximum absolute probability change before a token is masked."""
|
||||
|
||||
max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False)
|
||||
"""Cap the importance weight of accepted tokens while preserving its policy gradient."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
|
||||
+6
-6
@@ -16,7 +16,7 @@ dependencies = [
|
||||
"transformers==5.6.2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime-sandboxes>=0.3.0",
|
||||
"prime-sandboxes>=0.3.2",
|
||||
"prime-runs[train]>=0.1.3",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
@@ -29,7 +29,7 @@ dependencies = [
|
||||
"rich>=14.0.0",
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"verifiers[harbor]>=0.3.1",
|
||||
"verifiers[harbor]>=0.3.2.dev143",
|
||||
"renderers[multimodal]>=0.1.12.dev2",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
@@ -171,11 +171,11 @@ members = [
|
||||
"deps/verifiers/environments/wiki_search",
|
||||
"deps/verifiers/environments/wordle",
|
||||
]
|
||||
# tau2-synth and tau3-bench pin `tau2` forks/revs that conflict with the
|
||||
# canonical tau2-bench; apex-agents pins `verifiers` as a git rev instead of
|
||||
# the editable workspace member. A workspace shares one lock, so these can't
|
||||
# coexist.
|
||||
# Tau tasksets require litellm<1.82.7, while Harbor requires litellm>=1.92.0.
|
||||
# Apex pins a verifiers git revision instead of the editable workspace member.
|
||||
# A workspace shares one lock, so these packages need separate environments.
|
||||
exclude = [
|
||||
"deps/prime-envs/environments/tool_use/tau2_bench",
|
||||
"deps/prime-envs/environments/tool_use/tau2_synth",
|
||||
"deps/prime-envs/environments/tool_use/tau3_bench",
|
||||
"deps/prime-envs/environments/tool_use/apex_agents",
|
||||
|
||||
+119
-45
@@ -5,67 +5,141 @@ set -e
|
||||
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
|
||||
|
||||
# Allow runtime override of the prime-rl source itself.
|
||||
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
|
||||
# PRIME_RL_REF can be a git tag, branch, or full commit hash. PRIME_RL_REPO
|
||||
# optionally points at a fork; defaults to the upstream repo.
|
||||
#
|
||||
# We clone into a per-ref dir under /tmp, seed the venv from the baked
|
||||
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
|
||||
# `uv sync --inexact` re-installs prime_rl from the override source.
|
||||
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
|
||||
# resolves the entrypoints from the override venv.
|
||||
# The ref is fetched shallowly under /tmp and synced INTO the baked
|
||||
# /app/.venv: uv re-points the first-party editables (prime_rl, verifiers,
|
||||
# renderers, ...) at the checkout and reinstalls only third-party pins
|
||||
# that differ from the image's lockfile, so the heavy prebuilt wheels
|
||||
# (flash-attn, deep-ep, mamba-ssm, ...) are never rebuilt. A container
|
||||
# starts from a fresh filesystem, so mutating /app/.venv in place is safe.
|
||||
# The pods of the prime-rl-fft chart run this with a sha pinned by the
|
||||
# dispatcher; the exported PRIME_RL_SOURCE_COMMIT records what ran.
|
||||
if [ -n "$PRIME_RL_REF" ]; then
|
||||
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
|
||||
# Slug + content hash for the cache dir name. Slug keeps the path
|
||||
# Slug + content hash for the checkout dir name. Slug keeps the path
|
||||
# human-readable; the hash (over repo + ref) prevents collisions
|
||||
# between distinct refs that slugify the same way (e.g. `feat/foo`
|
||||
# vs `feat-foo`) and between the same ref on different forks.
|
||||
REF_SLUG="${PRIME_RL_REF//\//-}"
|
||||
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
|
||||
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
|
||||
# Rewrite ssh://git@github.com URLs to https so submodules listed
|
||||
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
|
||||
# can be cloned from the pod without ssh keys.
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
if [ ! -d "$DEST/.git" ]; then
|
||||
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
|
||||
rm -rf "$DEST"
|
||||
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
|
||||
# Rewrite git@github.com URLs to https so submodules listed with SSH
|
||||
# URLs (deps/verifiers, deps/renderers, deps/prime-envs) clone from the
|
||||
# pod without ssh keys. Via GIT_CONFIG_* rather than `git config
|
||||
# --global`: the pod's HOME may not be writable by its uid.
|
||||
export GIT_CONFIG_COUNT=1
|
||||
export GIT_CONFIG_KEY_0="url.https://github.com/.insteadOf"
|
||||
export GIT_CONFIG_VALUE_0="git@github.com:"
|
||||
rm -rf "$DEST"
|
||||
git init --quiet "$DEST"
|
||||
git -C "$DEST" remote add origin "$PRIME_RL_REPO"
|
||||
# Depth-1 fetch of the ref itself: GitHub serves branches, tags and
|
||||
# full commit shas alike (abbreviated shas are not fetchable), and
|
||||
# prime-rl's history (~700 MB of .git) is not needed to run it.
|
||||
echo "[prime-rl] fetching ${PRIME_RL_REF} from ${PRIME_RL_REPO}"
|
||||
git -C "$DEST" fetch --quiet --depth 1 origin "$PRIME_RL_REF"
|
||||
git -C "$DEST" checkout --quiet --force --detach FETCH_HEAD
|
||||
# Same public submodules the image build inits (build_image.yaml);
|
||||
# a pinned commit that isn't the submodule's branch tip is fetched by
|
||||
# sha, which GitHub allows.
|
||||
git -C "$DEST" submodule sync --quiet --recursive
|
||||
git -C "$DEST" submodule update --quiet --init --recursive --depth 1 -- \
|
||||
deps/pydantic-config deps/verifiers deps/renderers deps/prime-envs
|
||||
PRIME_RL_SOURCE_COMMIT=$(git -C "$DEST" rev-parse HEAD)
|
||||
export PRIME_RL_SOURCE_COMMIT
|
||||
echo "[prime-rl] source overlay at ${PRIME_RL_SOURCE_COMMIT}"
|
||||
|
||||
# Give the verifiers/renderers editables the same versions the image
|
||||
# build does (Dockerfile.cuda): resolve them with the repo's script
|
||||
# (git describe, else the highest `>=` floor any pyproject declares),
|
||||
# then bake them into hatch-vcs's fallback-version and drop the
|
||||
# submodules' git metadata so the fallback is what gets used. The
|
||||
# shallow clones carry no tags, so hatch-vcs would otherwise stamp
|
||||
# them 0.0.1.dev1 and every `verifiers>=…` floor in the tree would be
|
||||
# unmet, letting the CLI install below swap the editable for a wheel.
|
||||
if [ -f "$DEST/scripts/docker-editable-pretend-versions.sh" ]; then
|
||||
eval "$(bash "$DEST/scripts/docker-editable-pretend-versions.sh" --shell "$DEST")"
|
||||
rm -f "$DEST/deps/verifiers/.git" "$DEST/deps/renderers/.git"
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" "$DEST/deps/verifiers/pyproject.toml"
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" "$DEST/deps/renderers/pyproject.toml"
|
||||
fi
|
||||
# Always fetch + checkout so mutable refs (branches/tags) pick up new
|
||||
# commits between pod restarts. No-op for immutable SHAs.
|
||||
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
|
||||
git -C "$DEST" fetch --quiet --tags --force origin
|
||||
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
|
||||
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
|
||||
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
|
||||
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
|
||||
# Refresh submodules to whatever the parent commit pins. `sync`
|
||||
# picks up URL changes in .gitmodules between checkouts on cache
|
||||
# hit; `update --init --recursive` applies the pinned SHAs.
|
||||
git -C "$DEST" submodule sync --recursive
|
||||
git -C "$DEST" submodule update --init --recursive
|
||||
if [ ! -d "$DEST/.venv" ]; then
|
||||
# Seed from the baked venv so the heavy wheels (flash-attn,
|
||||
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
|
||||
# hardlinks): a subsequent `uv sync` writes into this tree, and
|
||||
# hardlinks would leak those writes back into /app/.venv when
|
||||
# /tmp and /app share a filesystem.
|
||||
cp -a /app/.venv "$DEST/.venv"
|
||||
fi
|
||||
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
|
||||
# --inexact keeps the seeded venv's pre-built wheels (flash-attn-3,
|
||||
# deep-ep, mamba-ssm) in place; uv only rebuilds them if the override's
|
||||
# lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages --all-extras --group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
|
||||
# Wheels the in-place sync cannot rebuild: a lockfile that pins any of
|
||||
# these differently from the image needs a real image build. Fail here
|
||||
# rather than minutes later inside a half-installed torch. Stdlib only;
|
||||
# --project /app pins the interpreter to the baked venv whatever the cwd.
|
||||
uv run --no-sync --project /app python - "$DEST/uv.lock" /app/uv.lock <<'HEAVY_PINS_PY'
|
||||
import sys
|
||||
import tomllib
|
||||
|
||||
HEAVY = {
|
||||
"torch", "torchvision", "torchaudio", "triton", "vllm", "vllm-router",
|
||||
"flash-attn", "flash-attn-3", "flashinfer-python", "tilelang",
|
||||
"deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels",
|
||||
}
|
||||
|
||||
|
||||
def pins(path):
|
||||
with open(path, "rb") as f:
|
||||
lock = tomllib.load(f)
|
||||
out = {}
|
||||
for pkg in lock.get("package", []):
|
||||
if pkg.get("name") in HEAVY:
|
||||
source = repr(sorted((pkg.get("source") or {}).items()))
|
||||
out.setdefault(pkg["name"], set()).add((pkg.get("version"), source))
|
||||
return out
|
||||
|
||||
|
||||
ref_pins, image_pins = pins(sys.argv[1]), pins(sys.argv[2])
|
||||
drift = sorted(name for name in HEAVY if ref_pins.get(name) != image_pins.get(name))
|
||||
if drift:
|
||||
print(
|
||||
f"[prime-rl] {sys.argv[1]} pins {', '.join(drift)} differently from the image; "
|
||||
"the runtime source overlay cannot rebuild these. Build an image for this ref "
|
||||
"(build_image.yaml) or run it on an image whose lockfile matches.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
HEAVY_PINS_PY
|
||||
|
||||
# Sync the checkout into the baked venv. Same extras as Dockerfile.cuda
|
||||
# so an unchanged lockfile is a no-op for third-party packages (keep
|
||||
# the two lists in sync). --inexact leaves packages the checkout
|
||||
# doesn't declare in place instead of uninstalling them.
|
||||
export UV_PROJECT_ENVIRONMENT=/app/.venv
|
||||
export VIRTUAL_ENV=/app/.venv
|
||||
echo "[prime-rl] syncing ${DEST} into /app/.venv"
|
||||
( cd "$DEST" && uv sync --inexact --locked --no-dev --all-packages \
|
||||
--extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 \
|
||||
--extra flash-attn-cute --extra disagg --extra quack --extra kernels \
|
||||
--group mamba-ssm )
|
||||
# Replay the image's post-sync step (Dockerfile.cuda; keep the two in
|
||||
# sync): the prime CLI pulls prime-traces / prime-sandboxes / openai
|
||||
# past the lock's pins, and the --locked sync above just rolled them
|
||||
# back, which leaves `prime env install` unable to import.
|
||||
#
|
||||
# FIXME(prime#940): workaround, remove once the prime CLI drops
|
||||
# verifiers as a dependency
|
||||
# (https://github.com/PrimeIntellect-ai/prime/pull/940). The CLI pins
|
||||
# verifiers==0.2.0, which would swap the editable for the PyPI wheel
|
||||
# and break prime-rl's imports; the --overrides file ignores that one
|
||||
# requirement. When removing it, drop the overrides file and the
|
||||
# --overrides flag here and in Dockerfile.cuda.
|
||||
echo "[prime-rl] installing the prime CLI"
|
||||
printf 'verifiers\n' > /tmp/prime-cli-overrides.txt
|
||||
uv pip install --overrides /tmp/prime-cli-overrides.txt 'prime>=0.7'
|
||||
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
|
||||
# project from the cwd; the venv itself stays /app/.venv via
|
||||
# UV_PROJECT_ENVIRONMENT above.
|
||||
cd "$DEST"
|
||||
fi
|
||||
|
||||
# Allow runtime override of the verifiers package version.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
|
||||
# PRIME_RL_REF swap so when both are set the install lands in the override
|
||||
# venv (uv pip install targets $VIRTUAL_ENV when exported).
|
||||
# PRIME_RL_REF overlay so when both are set verifiers is installed last
|
||||
# (uv pip install targets $VIRTUAL_ENV, which is /app/.venv either way).
|
||||
if [ -n "$VERIFIERS_VERSION" ]; then
|
||||
echo "Installing verifiers version: $VERIFIERS_VERSION"
|
||||
uv pip install --reinstall-package verifiers \
|
||||
|
||||
@@ -82,6 +82,10 @@ else
|
||||
fi
|
||||
cd "$NIXL_SRC"
|
||||
git checkout "$NIXL_VERSION"
|
||||
# Name the wheel nixl-cu13 (pyproject says nixl-cu12): the `nixl` shim imports
|
||||
# nixl_cu13 first, so a nixl_cu12 build would sit unused next to the PyPI wheel.
|
||||
git checkout -- pyproject.toml
|
||||
uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml
|
||||
|
||||
export PKG_CONFIG_PATH="$UCX_INSTALL/lib/pkgconfig"
|
||||
export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
@@ -92,5 +96,5 @@ mkdir -p "$WHEEL_DIR"
|
||||
uv pip install pip 2>/dev/null
|
||||
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR"
|
||||
|
||||
WHEEL=$(ls "$WHEEL_DIR"/nixl*.whl | head -1)
|
||||
WHEEL=$(ls "$WHEEL_DIR"/nixl_cu13-"$NIXL_VERSION"-*.whl | head -1)
|
||||
echo "=== NIXL wheel built at: $WHEEL ==="
|
||||
|
||||
@@ -823,6 +823,8 @@ def message_text(message: dict) -> str:
|
||||
def timeline_status(trace: dict) -> str:
|
||||
if not trace.get("is_completed"):
|
||||
return "running"
|
||||
if trace.get("is_timeout"):
|
||||
return "timeout"
|
||||
if not trace.get("ok") and (trace.get("errors") or trace.get("stop_condition") == "error"):
|
||||
return "failed"
|
||||
return "completed"
|
||||
@@ -1822,6 +1824,7 @@ def episode_series(run: str, kind: str | None = None, etag: str | None = None, a
|
||||
"ok",
|
||||
"num_errors",
|
||||
"truncated",
|
||||
"timeout",
|
||||
"stop_condition",
|
||||
"duration",
|
||||
"reward",
|
||||
|
||||
@@ -423,7 +423,7 @@ function rowsChartHere() {
|
||||
}
|
||||
|
||||
const COMMON_METRICS = ["effective/num_turns/mean", "effective/num_total_tokens/mean", "effective/num_branches/mean"];
|
||||
const COMMON_REGEXES = ["effective/[^/]+/is_truncated/mean", "all/[^/]+/has_error/mean"];
|
||||
const COMMON_REGEXES = ["effective/[^/]+/is_truncated/mean", "all/[^/]+/is_timeout/mean", "all/[^/]+/has_error/mean"];
|
||||
const STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"];
|
||||
const PERFORMANCE_METRICS = ["perf/mfu", "time/step", "time/wait_for_batch", "time/wait_for_policy"];
|
||||
const SFT_TRAIN_METRICS = ["loss/mean", "loss/perplexity", "val/loss", "val/perplexity", "progress/epoch"];
|
||||
@@ -628,11 +628,11 @@ function evalProgressHtml(env, idx, live) {
|
||||
cells =
|
||||
idx
|
||||
.map((i) => {
|
||||
const err = series.ok?.[i] === false;
|
||||
const mark = outcomeClass(series, i);
|
||||
const reward = series.reward?.[i];
|
||||
return (
|
||||
`<span class="ep-cell done${err ? " err" : ""}" data-line="${series.line?.[i]}" ` +
|
||||
`title="#${series.line?.[i]} · reward ${reward != null ? fmtReward(reward) : "n/a"}${err ? " · error" : ""}"></span>`
|
||||
`<span class="ep-cell done ${mark}" data-line="${series.line?.[i]}" ` +
|
||||
`title="#${series.line?.[i]} · reward ${reward != null ? fmtReward(reward) : "n/a"}${mark === "err" ? " · error" : mark === "timeout" ? " · timeout" : ""}"></span>`
|
||||
);
|
||||
})
|
||||
.join("") +
|
||||
@@ -745,7 +745,7 @@ function dotPlotSvg(entry, W, H) {
|
||||
const col = Math.floor(j / perCol), rowN = j % perCol;
|
||||
const cx = x0 + col * (2 * r + 1);
|
||||
const cy = top + plotH - r - rowN * (2 * r + 1);
|
||||
return `<circle data-i="${i}" class="${p.err ? "err" : ""}" cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="${r}"></circle>`;
|
||||
return `<circle data-i="${i}" class="${markClass(p)}" cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="${r}"></circle>`;
|
||||
})
|
||||
.join("");
|
||||
const n = counts.get(v);
|
||||
@@ -829,7 +829,7 @@ function swarmSvg(entry, W, H) {
|
||||
stacks.set(column, k + 1);
|
||||
const offset = Math.ceil(k / 2) * d * (k % 2 ? -1 : 1);
|
||||
const y = Math.max(r, Math.min(plotH - r, mid + offset));
|
||||
return `<circle data-i="${i}" class="${points[i].err ? "err" : ""}" cx="${px.toFixed(1)}" cy="${y.toFixed(1)}" r="${r}"></circle>`;
|
||||
return `<circle data-i="${i}" class="${markClass(points[i])}" cx="${px.toFixed(1)}" cy="${y.toFixed(1)}" r="${r}"></circle>`;
|
||||
});
|
||||
// the x axis: a baseline under the plot, round-valued ticks with grid lines
|
||||
const label = (v) => tickLabel(v, entry.fmt);
|
||||
@@ -868,6 +868,16 @@ function drawSwarms() {
|
||||
|
||||
const SWARM_STAT_ROWS = ["min", "p10", "median", "p90", "max"];
|
||||
|
||||
/* an episode's outcome mark: a timeout reads yellow, an error red, a clean one unmarked */
|
||||
function outcomeClass(series, i) {
|
||||
if (series.timeout?.[i] === true) return "timeout";
|
||||
return series.ok?.[i] === false ? "err" : "";
|
||||
}
|
||||
|
||||
function markClass(point) {
|
||||
return point.timeout ? "timeout" : point.err ? "err" : "";
|
||||
}
|
||||
|
||||
function swarmTipHtml(entry, point) {
|
||||
const row = (k, v) => `<div class="tip-row"><span>${esc(k)}</span><span>${v}</span></div>`;
|
||||
if (point) {
|
||||
@@ -875,6 +885,7 @@ function swarmTipHtml(entry, point) {
|
||||
? [row("rollouts", point.n), row(entry.label, entry.fmt(point.v))]
|
||||
: [row(entry.label, entry.fmt(point.v)), ...(point.reward != null ? [row("reward", fmtReward(point.reward))] : [])];
|
||||
if (point.err) rows.push(row("errors", point.group ? "in a rollout" : "yes"));
|
||||
if (point.timeout) rows.push(row("timeout", point.group ? "in a rollout" : "yes"));
|
||||
rows.push(row("", point.group ? "click opens its first rollout" : "click opens the trace"));
|
||||
return `<div class="tip-head">${point.group ? `task ${esc(point.group.slice(0, 8))}` : `episode #${point.line}`}</div>${rows.join("")}`;
|
||||
}
|
||||
@@ -907,15 +918,16 @@ function evalScoreEntries(idx, filter) {
|
||||
const reward = series.reward?.[i] ?? (series.ok?.[i] === false ? 0 : null);
|
||||
if (reward == null) continue;
|
||||
const task = series.group?.[i] ?? String(i);
|
||||
if (!byTask.has(task)) byTask.set(task, { group: task, line: series.line?.[i], rewards: [], err: false });
|
||||
if (!byTask.has(task)) byTask.set(task, { group: task, line: series.line?.[i], rewards: [], err: false, timeout: false });
|
||||
const t = byTask.get(task);
|
||||
t.rewards.push(reward);
|
||||
if (series.ok?.[i] === false) t.err = true;
|
||||
if (series.timeout?.[i] === true) t.timeout = true;
|
||||
}
|
||||
const tasks = [...byTask.values()];
|
||||
if (!tasks.length) return entries;
|
||||
const k = Math.max(...tasks.map((t) => t.rewards.length));
|
||||
const taskPoint = (t, v) => ({ v, group: t.group, line: t.line, n: t.rewards.length, err: t.err });
|
||||
const taskPoint = (t, v) => ({ v, group: t.group, line: t.line, n: t.rewards.length, err: t.err, timeout: t.timeout });
|
||||
if (!filter || filter.test("avg@k"))
|
||||
entries.push(swarmEntry("avg@k", `avg@${k}`, tasks.map((t) => taskPoint(t, t.rewards.reduce((a, b) => a + b, 0) / t.rewards.length)), fmtReward));
|
||||
if ((!filter || filter.test("pass@k")) && tasks.every((t) => t.rewards.every((r) => r === 0 || r === 1))) {
|
||||
@@ -1015,7 +1027,7 @@ function timingPaneHtml(idx) {
|
||||
if (total == null) return null;
|
||||
const parts = leaves.map((p) => ({ name: p.split("/").pop(), v: series[`timing/${p}`]?.[i] ?? 0 }));
|
||||
parts.push({ name: "other", v: Math.max(0, total - parts.reduce((a, p) => a + p.v, 0)) });
|
||||
return { i, line: series.line?.[i], err: series.ok?.[i] === false, total, parts };
|
||||
return { i, line: series.line?.[i], err: series.ok?.[i] === false, timeout: series.timeout?.[i] === true, total, parts };
|
||||
})
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => b.total - a.total);
|
||||
@@ -1037,7 +1049,7 @@ function tokensPaneHtml(idx) {
|
||||
.map((i) => {
|
||||
const input = series.input_tokens?.[i] ?? 0, output = series.output_tokens?.[i] ?? 0;
|
||||
if (!input && !output) return null;
|
||||
return { i, line: series.line?.[i], err: series.ok?.[i] === false, total: input + output, parts: [{ name: "input", v: input }, { name: "output", v: output }] };
|
||||
return { i, line: series.line?.[i], err: series.ok?.[i] === false, timeout: series.timeout?.[i] === true, total: input + output, parts: [{ name: "input", v: input }, { name: "output", v: output }] };
|
||||
})
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => b.total - a.total);
|
||||
@@ -1113,7 +1125,7 @@ function drawComposition(pane, model, { kind, fmt, time, color }) {
|
||||
const t = tip(
|
||||
`<div class="tip-head">episode #${r.line} · ${fmt(r.total)}</div>` +
|
||||
parts.map((p) => rowTip(p.name, `${fmt(p.v)} · ${Math.round((p.v / (r.total || 1)) * 100)}%`)).join("") +
|
||||
`${r.err ? rowTip("errors", "yes") : ""}${rowTip("", "click opens the trace")}`
|
||||
`${r.err ? rowTip("errors", "yes") : ""}${r.timeout ? rowTip("timeout", "yes") : ""}${rowTip("", "click opens the trace")}`
|
||||
);
|
||||
const segs = parts
|
||||
.map((p) => {
|
||||
@@ -1126,7 +1138,7 @@ function drawComposition(pane, model, { kind, fmt, time, color }) {
|
||||
.join("");
|
||||
return (
|
||||
`<rect class="tm-row-hit" data-tip="${t}" data-row="${n}" data-line="${r.line}" x="0" y="${y - GAP / 2}" width="${W}" height="${SH + GAP}"></rect>` +
|
||||
`<text class="hax tm-line${r.err ? " err" : ""}" data-row="${n}" x="${PAD_L - 6}" y="${y + SH - 1}" style="text-anchor:end">#${r.line}</text>${segs}`
|
||||
`<text class="hax tm-line ${markClass(r)}" data-row="${n}" x="${PAD_L - 6}" y="${y + SH - 1}" style="text-anchor:end">#${r.line}</text>${segs}`
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
@@ -1174,13 +1186,19 @@ function summaryTilesHtml(idx, all, scoreEntries) {
|
||||
const rows = entry.rows ?? SWARM_STAT_ROWS.map((k) => [k, entry.fmt(entry.stats[k])]);
|
||||
tile(entry.label, entry.headline, `<div class="tip-head">${esc(entry.label)} · ${fmtCompact(entry.stats.n)} tasks</div>${rows.map(([k, v]) => rowTip(k, v)).join("")}`, { cls: " score" });
|
||||
}
|
||||
// failure rates count every landed episode, the errors filter notwithstanding
|
||||
// failure rates count every landed episode, the errors filter notwithstanding;
|
||||
// the timeout rate reads yellow as soon as any episode timed out
|
||||
if (all.length) {
|
||||
const errored = all.filter((i) => series.ok?.[i] === false).length;
|
||||
const truncated = all.filter((i) => (series.truncated?.[i] ?? TRUNCATING_STOPS.has(series.stop_condition?.[i])) === true).length;
|
||||
for (const [label, n, what] of [["error rate", errored, "errored"], ["truncation rate", truncated, "truncated"]]) {
|
||||
const timedOut = all.filter((i) => series.timeout?.[i] === true).length;
|
||||
for (const [label, n, what, cls] of [
|
||||
["error rate", errored, "errored", rateClass],
|
||||
["truncation rate", truncated, "truncated", rateClass],
|
||||
["timeout rate", timedOut, "timed out", (rate) => (rate > 0 ? " rate-timeout" : "")],
|
||||
]) {
|
||||
const rate = n / all.length;
|
||||
tile(label, `${Math.round(rate * 100)}%`, `<div class="tip-head">${esc(label)}</div>${rowTip(what, `${n} of ${all.length} episodes`)}`, { cls: rateClass(rate) });
|
||||
tile(label, `${Math.round(rate * 100)}%`, `<div class="tip-head">${esc(label)}</div>${rowTip(what, `${n} of ${all.length} episodes`)}`, { cls: cls(rate) });
|
||||
}
|
||||
}
|
||||
const turns = distStats(idx.map((i) => series.turns?.[i]));
|
||||
@@ -1236,6 +1254,7 @@ function renderEvalPane(body) {
|
||||
line: series.line?.[i],
|
||||
reward: series.reward?.[i],
|
||||
err: series.ok?.[i] === false,
|
||||
timeout: series.timeout?.[i] === true,
|
||||
})),
|
||||
fmt,
|
||||
opts
|
||||
@@ -4040,6 +4059,7 @@ function scopedErrorsHtml(scope, { failed, recovered }) {
|
||||
}
|
||||
|
||||
function episodeRowClass(ep) {
|
||||
if (ep.timeout) return "timeout";
|
||||
if (!ep.ok) return "err";
|
||||
return ep.num_errors ? "retried" : "";
|
||||
}
|
||||
@@ -4047,7 +4067,9 @@ function episodeRowClass(ep) {
|
||||
function episodeRowTitle(ep) {
|
||||
const n = ep.num_errors || 0;
|
||||
const errors = `${n || 1} error${n === 1 ? "" : "s"}`;
|
||||
if (!ep.ok) return errors;
|
||||
const timeout = ep.timeout ? `timed out (${ep.stop_condition ?? "timeout"})` : "";
|
||||
if (!ep.ok) return [timeout, errors].filter(Boolean).join(" · ");
|
||||
if (timeout) return timeout;
|
||||
return n ? `recovered from ${errors} in earlier attempts` : "";
|
||||
}
|
||||
|
||||
@@ -4340,6 +4362,7 @@ function renderMeta(ep, trace, branches) {
|
||||
parts.push(metaRow("stop_condition", trace.stop_condition));
|
||||
parts.push(metaRow("is_completed", trace.is_completed));
|
||||
parts.push(metaRow("is_truncated", traceTruncated(trace)));
|
||||
parts.push(metaRow("is_timeout", !!trace.is_timeout));
|
||||
parts.push(metaRow("ok", trace.ok));
|
||||
|
||||
const durations = [];
|
||||
@@ -5532,7 +5555,7 @@ function renderEpisode() {
|
||||
traceTabs.innerHTML =
|
||||
traces.length > 1
|
||||
? traces
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.is_timeout ? " timeout" : trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.join("")
|
||||
: "";
|
||||
const branchTabs = $("#tm-branch-tabs");
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
--accent: #b6ff3c;
|
||||
--negative: #ff4539;
|
||||
--timeout: #ffd166;
|
||||
--positive: #b6ff3c;
|
||||
--infra: #4a9eff;
|
||||
--risk: #ff6b4a;
|
||||
@@ -358,6 +359,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
.ep-cell { flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); }
|
||||
.ep-cell.done { background: var(--accent); border-color: var(--accent); cursor: pointer; }
|
||||
.ep-cell.done.err { background: var(--negative); border-color: var(--negative); }
|
||||
.ep-cell.done.timeout { background: var(--timeout); border-color: var(--timeout); }
|
||||
.ep-cell.done:hover { filter: brightness(1.2); }
|
||||
.ep-cell.live { border-color: var(--accent); background: rgba(182, 255, 60, 0.18); animation: live-pulse 1.6s ease-in-out infinite; cursor: pointer; }
|
||||
|
||||
@@ -369,6 +371,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
.swarm .sw-bg { fill: transparent; }
|
||||
.swarm circle { fill: var(--accent); fill-opacity: 0.7; cursor: pointer; }
|
||||
.swarm circle.err { fill: var(--negative); }
|
||||
.swarm circle.timeout { fill: var(--timeout); }
|
||||
.swarm circle:hover { fill-opacity: 1; stroke: var(--grey-6); stroke-width: 1; }
|
||||
.sw-axis { stroke: var(--grey-3); stroke-width: 1; }
|
||||
.sw-grid { stroke: var(--hairline-faint); stroke-width: 1; }
|
||||
@@ -392,6 +395,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
.tm-strip-seg.dim { opacity: 0.2; }
|
||||
.tm-strip-seg:hover { filter: brightness(1.25); }
|
||||
.tm-line.err { fill: var(--negative); }
|
||||
.tm-line.timeout { fill: var(--timeout); }
|
||||
.comp-pane [data-part].dim { opacity: 0.2; }
|
||||
.comp-pane .tm-node.dim { opacity: 0.35; }
|
||||
/* the summary is one row whatever the count: the tiles share the width equally */
|
||||
@@ -401,6 +405,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
.sum-tile .stat-value { font-size: clamp(16px, 1.7vw, 24px); margin-top: 8px; }
|
||||
.sum-tile.rate-warn .stat-value { color: #ffd166; }
|
||||
.sum-tile.rate-bad .stat-value { color: var(--negative); }
|
||||
.sum-tile.rate-timeout .stat-value { color: var(--timeout); }
|
||||
.tm-note { font-size: 10px; margin-top: 4px; }
|
||||
.tm-more { color: var(--grey-5); cursor: pointer; text-decoration: underline dotted; text-underline-offset: 3px; }
|
||||
.tm-more:hover { color: var(--grey-6); }
|
||||
@@ -834,6 +839,8 @@ mark.hit {
|
||||
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
|
||||
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
|
||||
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
|
||||
.tm-item.timeout { background: rgba(255, 209, 102, 0.08); border-color: var(--timeout); }
|
||||
.tm-item.timeout:hover, .tm-item.timeout.active { background: rgba(255, 209, 102, 0.16); }
|
||||
.tm-item.retried { border-left: 2px dotted var(--grey-4); }
|
||||
.tm-item .tm-reward { margin-left: auto; }
|
||||
.tm-nav { padding: 0 8px; height: 24px; }
|
||||
@@ -936,6 +943,7 @@ mark.hit {
|
||||
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
|
||||
.tl-state.completed { color: var(--positive); }
|
||||
.tl-state.failed { color: var(--negative); }
|
||||
.tl-state.timeout { color: var(--timeout); }
|
||||
.tl-state.running { color: var(--infra); }
|
||||
.tl-tooltip {
|
||||
position: fixed;
|
||||
@@ -1212,6 +1220,7 @@ mark.hit {
|
||||
.trace-recovered-item .trace-error-type { color: var(--grey-4); }
|
||||
.trace-recovered-item .trace-error-tb > summary { border-top-color: var(--grey-3); }
|
||||
.seg button.err, .seg button.err.active { color: var(--negative); }
|
||||
.seg button.timeout, .seg button.timeout.active { color: var(--timeout); }
|
||||
.trace-error-tb > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1731,6 +1740,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
|
||||
place of their number set them apart */
|
||||
.live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); animation: live-pulse 2s ease-out infinite; }
|
||||
#episode-table tr.err td:first-child { border-left: 2px solid var(--negative); }
|
||||
#episode-table tr.timeout td:first-child { border-left: 2px solid var(--timeout); }
|
||||
#episode-table tr.retried td:first-child { border-left: 2px dotted var(--grey-4); }
|
||||
#episode-table tr.live.landing .live-dot { animation: none; opacity: 0.45; }
|
||||
.badge.stage { font-size: 9px; padding: 2px 5px; line-height: 12px; border-radius: 3px; background: var(--hairline); border-color: transparent; color: var(--accent); }
|
||||
|
||||
@@ -25,9 +25,10 @@ usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-r N] [-c
|
||||
uv run eval @ eval.toml [options] multi-source runs ([[source]] blocks)
|
||||
uv run eval @ eval.toml --run.name <name> --resume resume an interrupted run
|
||||
|
||||
Shorthands for a single-source run:
|
||||
Shorthands:
|
||||
<taskset-id> the taskset of the run's only source
|
||||
--env.<field> <value> a field of that source's env block (e.g. --env.agent.harness.id bash)
|
||||
--env.<field> <value> a field of that source's env block (e.g. --env.agent.harness.id bash); next to a
|
||||
TOML with [[source]] blocks, a field of the shared env block (e.g. --env.retries.max-retries 3)
|
||||
-c N pin the concurrency band (concurrency.min_inflight = max_inflight = N)
|
||||
"""
|
||||
|
||||
@@ -46,17 +47,21 @@ def parse_value(raw: str) -> Any:
|
||||
|
||||
|
||||
def expand_shorthands(argv: list[str]) -> list[str]:
|
||||
"""Rewrite the single-source shorthands into flags ``EvalConfig`` parses.
|
||||
"""Rewrite the shorthands into flags ``EvalConfig`` parses.
|
||||
|
||||
``<taskset-id>`` and ``--env.<path> <value>`` describe the run's only source and fold
|
||||
into one JSON ``--source`` flag (pydantic-config has no list-index paths, so
|
||||
``--source.0.env...`` cannot address it). ``-c N`` pins the concurrency band.
|
||||
Everything else passes through untouched.
|
||||
``--source.0.env...`` cannot address it). Next to a config file that defines
|
||||
``[[source]]`` blocks, ``--env.*`` flags pass through to the shared ``env`` block.
|
||||
``-c N`` pins the concurrency band. Everything else passes through untouched.
|
||||
"""
|
||||
out: list[str] = []
|
||||
source: dict[str, Any] = {}
|
||||
rest = list(argv)
|
||||
if rest and not rest[0].startswith(("-", "@")):
|
||||
positional = bool(rest) and not rest[0].startswith(("-", "@"))
|
||||
sources_in_toml = any(toml_defines_source(path) for path in root_config_files(argv))
|
||||
shared_env = sources_in_toml and not positional
|
||||
if positional:
|
||||
set_nested(source, ["env", "taskset", "id"], rest.pop(0))
|
||||
i = 0
|
||||
while i < len(rest):
|
||||
@@ -67,7 +72,9 @@ def expand_shorthands(argv: list[str]) -> list[str]:
|
||||
raise SystemExit(f"{flag} needs a value")
|
||||
i += 1
|
||||
value = rest[i]
|
||||
if flag.startswith("--env."):
|
||||
if flag.startswith("--env.") and shared_env:
|
||||
out += [flag, value]
|
||||
elif flag.startswith("--env."):
|
||||
set_nested(source, [key.replace("-", "_") for key in flag[2:].split(".")], parse_value(value))
|
||||
elif flag == "-c":
|
||||
out += ["--concurrency.min_inflight", value, "--concurrency.max_inflight", value]
|
||||
@@ -75,9 +82,9 @@ def expand_shorthands(argv: list[str]) -> list[str]:
|
||||
out.append(arg)
|
||||
i += 1
|
||||
if source:
|
||||
if any(toml_defines_source(path) for path in root_config_files(argv)):
|
||||
if sources_in_toml:
|
||||
raise SystemExit(
|
||||
"The <taskset-id> / --env.* shorthands describe a single source and cannot be combined "
|
||||
"The <taskset-id> shorthand describes a single source and cannot be combined "
|
||||
"with a config file that defines [[source]] blocks - use one or the other"
|
||||
)
|
||||
out += ["--source", json.dumps([source])]
|
||||
|
||||
@@ -27,7 +27,6 @@ class Eval:
|
||||
landed: list[dict] = []
|
||||
if config.resume:
|
||||
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
|
||||
resume.check_config(resume.previous_config(config.run_dir), dump_resolved_config(config))
|
||||
landed = resume.take_landed(config.run_dir)
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
|
||||
@@ -8,16 +8,14 @@ ones the interruption cut off are owed again.
|
||||
|
||||
A landed episode counts toward the task with its ``task.key``, so a resumed run may
|
||||
select more or fewer examples or rollouts per example than the interrupted one: the
|
||||
kept episodes are matched to the new selection and the rest is owed. What defines the
|
||||
measurement itself - the model, the sampling, each source's env - must not change
|
||||
(``check_config``).
|
||||
kept episodes are matched to the new selection and the rest is owed. The resumed
|
||||
config is not checked against the interrupted one: any of it may be overridden.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter, defaultdict
|
||||
from collections.abc import Iterator
|
||||
from fnmatch import fnmatch
|
||||
from pathlib import Path
|
||||
|
||||
import orjson
|
||||
@@ -28,30 +26,10 @@ from prime_rl.monitors.file.traces.chunks import chunk_numbers, open_chunk
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
|
||||
RESUMABLE = (
|
||||
"resume",
|
||||
"clean",
|
||||
"dry_run",
|
||||
"dashboard",
|
||||
"num_examples",
|
||||
"group_size",
|
||||
"concurrency",
|
||||
"client",
|
||||
"log",
|
||||
"monitors",
|
||||
"source.*.num_examples",
|
||||
"source.*.shuffle",
|
||||
"source.*.group_size",
|
||||
"source.*.serve",
|
||||
)
|
||||
"""Config paths a resumed run may change: how many rollouts to run and how to run them,
|
||||
never what is measured."""
|
||||
|
||||
|
||||
CONFIG_NAME = "eval.json"
|
||||
"""The resolved config an attempt stamps into its file monitor directory once it is
|
||||
running, beside the episodes it produces: a resume validates against the config those
|
||||
episodes were measured with, never against an attempt that was rejected or dry."""
|
||||
running, beside the episodes it produces, recording the config those episodes were
|
||||
measured with."""
|
||||
|
||||
|
||||
def stamp_config(run_dir: Path, config: dict) -> None:
|
||||
@@ -60,45 +38,6 @@ def stamp_config(run_dir: Path, config: dict) -> None:
|
||||
(directory / CONFIG_NAME).write_bytes(orjson.dumps(config, option=orjson.OPT_INDENT_2))
|
||||
|
||||
|
||||
def previous_config(run_dir: Path) -> dict:
|
||||
"""The config stamped beside the run's landed episodes: the current file monitor
|
||||
directory's, else the newest archive's."""
|
||||
for directory in [get_file_monitor_dir(run_dir), *reversed(archives(run_dir))]:
|
||||
if (directory / CONFIG_NAME).is_file():
|
||||
return orjson.loads((directory / CONFIG_NAME).read_bytes())
|
||||
raise FileNotFoundError(f"Nothing to resume: {run_dir} holds no attempt that ran")
|
||||
|
||||
|
||||
def config_diff(previous, current, prefix: str = "") -> list[str]:
|
||||
"""Dotted paths at which two resolved configs differ (list items by index)."""
|
||||
if isinstance(previous, dict) and isinstance(current, dict):
|
||||
return [
|
||||
path
|
||||
for key in sorted(set(previous) | set(current))
|
||||
for path in config_diff(previous.get(key), current.get(key), f"{prefix}.{key}" if prefix else key)
|
||||
]
|
||||
if isinstance(previous, list) and isinstance(current, list) and len(previous) == len(current):
|
||||
return [
|
||||
path
|
||||
for index, (before, after) in enumerate(zip(previous, current, strict=True))
|
||||
for path in config_diff(before, after, f"{prefix}.{index}")
|
||||
]
|
||||
return [] if previous == current else [prefix]
|
||||
|
||||
|
||||
def check_config(previous: dict, current: dict) -> None:
|
||||
changed = [
|
||||
path
|
||||
for path in config_diff(previous, current)
|
||||
if not any(fnmatch(path, pattern) or fnmatch(path, f"{pattern}.*") for pattern in RESUMABLE)
|
||||
]
|
||||
if changed:
|
||||
raise ValueError(
|
||||
f"The run cannot resume with a different {', '.join(changed)} - the landed episodes would not "
|
||||
"measure the same thing. Relaunch with --clean to start over."
|
||||
)
|
||||
|
||||
|
||||
def read_records(stream: Path) -> Iterator[dict]:
|
||||
"""Every record of a trace stream, in order. A torn last line (the interrupted
|
||||
process died mid-append) ends the stream."""
|
||||
|
||||
@@ -45,6 +45,7 @@ from prime_rl.orchestrator.utils import (
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
)
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_config_dir
|
||||
|
||||
@@ -71,11 +72,20 @@ class EvalRunner:
|
||||
self.dispatcher: Dispatcher | None = None
|
||||
self.inference_metrics: InferenceMetricsCollector | None = None
|
||||
self.periodic_logger: PeriodicLogger | None = None
|
||||
self.heart: Heartbeat | None = None
|
||||
|
||||
async def setup(self, *, skip_first_step: bool = False, is_resumed: bool = False) -> None:
|
||||
config = self.config
|
||||
set_default_executor()
|
||||
|
||||
# The heartbeat is beaten only by landed episodes — the first episode is its
|
||||
# first beat. No startup ping on purpose: the run-start to first-episode gap
|
||||
# (pool boot, env servers, the first episode's full duration) would otherwise
|
||||
# sit inside the ping stream as an abnormally long silence and flip a healthy
|
||||
# run stale. Until then the heartbeat has simply never been pinged.
|
||||
if config.heartbeat is not None:
|
||||
self.heart = Heartbeat(config.heartbeat.url)
|
||||
|
||||
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
|
||||
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
|
||||
self.run_name = os.environ.get("PRL_RUN_NAME")
|
||||
@@ -224,6 +234,8 @@ class EvalRunner:
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
else:
|
||||
stamp_arrival([item], "eval", eval_work(item).step)
|
||||
if self.heart is not None:
|
||||
self.heart.beat()
|
||||
await self.land(item, pending)
|
||||
continue
|
||||
if eval_batch is not None:
|
||||
@@ -291,7 +303,8 @@ class EvalRunner:
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%} | "
|
||||
f"Timeout {full.is_timeout.mean():.1%}"
|
||||
)
|
||||
|
||||
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
|
||||
|
||||
@@ -2,21 +2,27 @@
|
||||
|
||||
vLLM ships a generic tokens-in / tokens-out handler at
|
||||
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
|
||||
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
|
||||
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
|
||||
defaulting and ``usage`` reporting. We subclass it for the one bit still
|
||||
missing from the upstream handler: compact ``routed_experts`` export — when the
|
||||
engine emits routing decisions, surface them as ``{data, shape, start, dtype}``
|
||||
base64 raw-byte objects (the form the PD router can merge and the renderers
|
||||
parse) instead of upstream's single ``.npy`` base64 string.
|
||||
prefix-cache salting, lora dispatch, multimodal content parts and features,
|
||||
prompt logprobs, priority, ``data_parallel_rank`` header routing, server-side
|
||||
``max_tokens`` defaulting and ``usage`` reporting. We subclass it for the bits
|
||||
still missing from the upstream handler:
|
||||
|
||||
Everything else (request/response schema, sampling params, error handling)
|
||||
delegates to upstream so we track future vLLM changes for free.
|
||||
1. Compact ``routed_experts`` export — when the engine emits routing
|
||||
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
|
||||
objects (the form the PD router can merge and the renderers parse) instead
|
||||
of upstream's single ``.npy`` base64 string.
|
||||
|
||||
2. Prompt metadata — return the effective engine prompt and authoritative
|
||||
multimodal placeholder ranges after expansion. Drop this once upstream's
|
||||
response includes these fields.
|
||||
|
||||
Everything else delegates to upstream so we track future vLLM changes for free.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncGenerator
|
||||
from collections.abc import AsyncGenerator, AsyncIterable
|
||||
from contextvars import ContextVar
|
||||
from typing import Any
|
||||
|
||||
from vllm.entrypoints.generate.base.protocol import RequestResponseMetadata
|
||||
@@ -24,6 +30,7 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateRequest,
|
||||
GenerateResponse,
|
||||
GenerateResponseChoice,
|
||||
PlaceholderRangeInfo,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
@@ -33,14 +40,34 @@ from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
|
||||
|
||||
|
||||
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
|
||||
# Overrides upstream's base64 ``.npy`` string form with the compact
|
||||
# ``{data, shape, start, dtype}`` object the PD router merges and the
|
||||
# renderers parse.
|
||||
# Overrides upstream's base64 ``.npy`` string form with the compact object
|
||||
# the PD router merges and the renderers parse.
|
||||
routed_experts: dict[str, Any] | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
class PrimeRlGenerateResponse(GenerateResponse):
|
||||
choices: list[PrimeRlGenerateResponseChoice]
|
||||
prompt_token_ids: list[int] | None = None
|
||||
mm_placeholders: dict[str, list[PlaceholderRangeInfo]] | None = None
|
||||
|
||||
|
||||
_response_mm_placeholders: ContextVar[dict[str, list[PlaceholderRangeInfo]] | None] = ContextVar(
|
||||
"response_mm_placeholders", default=None
|
||||
)
|
||||
|
||||
|
||||
def _extract_mm_placeholders(
|
||||
engine_input: Any,
|
||||
) -> dict[str, list[PlaceholderRangeInfo]] | None:
|
||||
if not isinstance(engine_input, dict) or engine_input.get("type") != "multimodal":
|
||||
return None
|
||||
return {
|
||||
modality: [
|
||||
PlaceholderRangeInfo(offset=placeholder.offset, length=placeholder.length)
|
||||
for placeholder in sorted(ranges, key=lambda placeholder: placeholder.offset)
|
||||
]
|
||||
for modality, ranges in engine_input["mm_placeholders"].items()
|
||||
}
|
||||
|
||||
|
||||
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
@@ -52,11 +79,32 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
)
|
||||
for choice in response.choices
|
||||
]
|
||||
return PrimeRlGenerateResponse(**{**dict(response), "choices": choices})
|
||||
return PrimeRlGenerateResponse(**{**response.model_dump(exclude={"choices"}), "choices": choices})
|
||||
|
||||
|
||||
class _PromptTokenIdsCapture:
|
||||
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
|
||||
self._source = source
|
||||
self.prompt_token_ids: list[int] | None = None
|
||||
|
||||
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
|
||||
async for output in self._source:
|
||||
self.prompt_token_ids = output.prompt_token_ids
|
||||
yield output
|
||||
|
||||
|
||||
class PrimeRlServingTokens(ServingTokens):
|
||||
"""ServingTokens + compact routed experts."""
|
||||
"""ServingTokens with Prime's remaining response and PD extensions."""
|
||||
|
||||
def _log_inputs(
|
||||
self,
|
||||
request_id: str,
|
||||
inputs: Any,
|
||||
params: Any,
|
||||
lora_request: Any,
|
||||
) -> None:
|
||||
_response_mm_placeholders.set(_extract_mm_placeholders(inputs))
|
||||
super()._log_inputs(request_id, inputs, params, lora_request)
|
||||
|
||||
async def serve_tokens_full_generator( # type: ignore[override]
|
||||
self,
|
||||
@@ -66,22 +114,30 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
model_name: str,
|
||||
request_metadata: RequestResponseMetadata,
|
||||
) -> ErrorResponse | GenerateResponse:
|
||||
# Capture routed_experts as vLLM streams request outputs, then post-process
|
||||
# the final response into our GenerateResponse subclass so the encoded
|
||||
# experts surface in the JSON.
|
||||
capture: _GenerateRoutedExpertsCapture | None = None
|
||||
routed_experts: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
capture = _GenerateRoutedExpertsCapture(
|
||||
routed_experts = _GenerateRoutedExpertsCapture(
|
||||
result_generator,
|
||||
start=request.sampling_params.routed_experts_prompt_start,
|
||||
)
|
||||
result_generator = capture
|
||||
result_generator = routed_experts
|
||||
|
||||
prompt_capture = _PromptTokenIdsCapture(result_generator)
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
request,
|
||||
prompt_capture,
|
||||
request_id,
|
||||
model_name,
|
||||
request_metadata,
|
||||
)
|
||||
|
||||
if capture is not None and isinstance(response, GenerateResponse):
|
||||
response = capture.post_process(response)
|
||||
if not isinstance(response, GenerateResponse):
|
||||
return response
|
||||
|
||||
if routed_experts is not None:
|
||||
response = routed_experts.post_process(response)
|
||||
else:
|
||||
response = PrimeRlGenerateResponse(**response.model_dump())
|
||||
response.prompt_token_ids = prompt_capture.prompt_token_ids
|
||||
response.mm_placeholders = _response_mm_placeholders.get()
|
||||
return response
|
||||
|
||||
@@ -55,6 +55,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
turns = branches = 0
|
||||
stop_condition = None
|
||||
truncated = False
|
||||
timeout = bool(rec.get("is_timeout"))
|
||||
reward_parts: dict[str, list[float]] = {}
|
||||
metric_parts: dict[str, list[float]] = {}
|
||||
timing: dict[str, float] = {}
|
||||
@@ -92,6 +93,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
turns += 1
|
||||
stop_condition = trace.get("stop_condition", stop_condition)
|
||||
truncated = truncated or trace_truncated(trace)
|
||||
timeout = timeout or bool(trace.get("is_timeout"))
|
||||
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
|
||||
return {
|
||||
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
|
||||
@@ -117,6 +119,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
"branches": branches,
|
||||
"stop_condition": stop_condition,
|
||||
"truncated": truncated,
|
||||
"timeout": timeout,
|
||||
# when the episode landed and how long it was alive: the stream's x axis,
|
||||
# and the one duration worth sorting a stream by
|
||||
"dispatch": (first_info.get("dispatch") or {}).get("time"),
|
||||
|
||||
@@ -40,6 +40,7 @@ COMMON_METRICS = [
|
||||
COMMON_REGEXES = [
|
||||
"all/[^/]+/has_error/mean",
|
||||
"effective/[^/]+/is_truncated/mean",
|
||||
"all/[^/]+/is_timeout/mean",
|
||||
]
|
||||
|
||||
STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"]
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, MultimodalAdapter
|
||||
from prime_rl.multimodal.registry import get_multimodal_adapter
|
||||
|
||||
__all__ = [
|
||||
"ForwardPolicy",
|
||||
"MaterializedMM",
|
||||
"MultimodalAdapter",
|
||||
"get_multimodal_adapter",
|
||||
]
|
||||
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Protocol
|
||||
|
||||
import torch
|
||||
from PIL.Image import Image
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ForwardPolicy:
|
||||
pass_position_ids: bool = True
|
||||
requires_mm_token_type_ids: bool = False
|
||||
defer_context_parallelism: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MaterializedMM:
|
||||
kwargs: dict[str, torch.Tensor]
|
||||
forward_policy: ForwardPolicy
|
||||
|
||||
|
||||
class MultimodalAdapter(Protocol):
|
||||
model_types: frozenset[str]
|
||||
forward_policy: ForwardPolicy
|
||||
|
||||
def materialize(
|
||||
self,
|
||||
image_processor: Any,
|
||||
images: list[Image],
|
||||
placeholder_lengths: list[int],
|
||||
) -> MaterializedMM: ...
|
||||
|
||||
|
||||
def required_tensors(values: Any, keys: tuple[str, ...]) -> dict[str, torch.Tensor]:
|
||||
data = dict(values)
|
||||
missing = [key for key in keys if key not in data]
|
||||
if missing:
|
||||
raise ValueError(f"Image processor did not return {', '.join(missing)}")
|
||||
return {key: torch.as_tensor(data[key]).contiguous() for key in keys}
|
||||
@@ -0,0 +1,33 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from PIL.Image import Image
|
||||
|
||||
from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, required_tensors
|
||||
|
||||
|
||||
class KimiK25Adapter:
|
||||
model_types = frozenset({"kimi_k25"})
|
||||
forward_policy = ForwardPolicy()
|
||||
|
||||
def materialize(
|
||||
self,
|
||||
image_processor: Any,
|
||||
images: list[Image],
|
||||
placeholder_lengths: list[int],
|
||||
) -> MaterializedMM:
|
||||
preprocess = getattr(image_processor, "preprocess", None)
|
||||
if preprocess is None:
|
||||
raise ValueError("Kimi image processor is missing preprocess")
|
||||
media = [{"type": "image", "image": image} for image in images]
|
||||
kwargs = required_tensors(
|
||||
preprocess(media, return_tensors="pt"),
|
||||
("pixel_values", "grid_thws"),
|
||||
)
|
||||
lengths = [1] * len(kwargs["grid_thws"].reshape(-1, 3))
|
||||
if lengths != placeholder_lengths:
|
||||
raise ValueError(
|
||||
f"Kimi image placeholder lengths differ from vLLM: expected {placeholder_lengths}, got {lengths}"
|
||||
)
|
||||
return MaterializedMM(kwargs=kwargs, forward_policy=self.forward_policy)
|
||||
@@ -0,0 +1,35 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from PIL.Image import Image
|
||||
|
||||
from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, required_tensors
|
||||
|
||||
|
||||
class QwenVLAdapter:
|
||||
model_types = frozenset({"qwen3_vl", "qwen3_vl_moe", "qwen3_5", "qwen3_5_moe"})
|
||||
forward_policy = ForwardPolicy(
|
||||
pass_position_ids=False,
|
||||
requires_mm_token_type_ids=True,
|
||||
defer_context_parallelism=True,
|
||||
)
|
||||
|
||||
def materialize(
|
||||
self,
|
||||
image_processor: Any,
|
||||
images: list[Image],
|
||||
placeholder_lengths: list[int],
|
||||
) -> MaterializedMM:
|
||||
kwargs = required_tensors(
|
||||
image_processor(images=images, return_tensors="pt"),
|
||||
("pixel_values", "image_grid_thw"),
|
||||
)
|
||||
merge_size = int(image_processor.merge_size)
|
||||
# HF Qwen-VL / renderer pad count: T*H*W / merge_size^2.
|
||||
lengths = [int(grid.prod()) // (merge_size * merge_size) for grid in kwargs["image_grid_thw"].reshape(-1, 3)]
|
||||
if lengths != placeholder_lengths:
|
||||
raise ValueError(
|
||||
f"Qwen image placeholder lengths differ from vLLM: expected {placeholder_lengths}, got {lengths}"
|
||||
)
|
||||
return MaterializedMM(kwargs=kwargs, forward_policy=self.forward_policy)
|
||||
@@ -0,0 +1,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.multimodal.base import MultimodalAdapter
|
||||
from prime_rl.multimodal.kimi_k25 import KimiK25Adapter
|
||||
from prime_rl.multimodal.qwen_vl import QwenVLAdapter
|
||||
|
||||
_ADAPTERS = (QwenVLAdapter(), KimiK25Adapter())
|
||||
_BY_MODEL_TYPE: dict[str, MultimodalAdapter] = {
|
||||
model_type: adapter for adapter in _ADAPTERS for model_type in adapter.model_types
|
||||
}
|
||||
|
||||
|
||||
def get_multimodal_adapter(model_type: str) -> MultimodalAdapter:
|
||||
try:
|
||||
return _BY_MODEL_TYPE[model_type]
|
||||
except KeyError as exc:
|
||||
raise NotImplementedError(f"Raw image training is not implemented for model type {model_type!r}") from exc
|
||||
@@ -670,9 +670,16 @@ class Dispatcher:
|
||||
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
|
||||
|
||||
for trace in episode.traces:
|
||||
if not trace.has_error and trace.num_turns == 0:
|
||||
if trace.is_timeout and not trace.has_error and meta.kind == "train":
|
||||
# Training keeps a timed-out rollout out of the batch: an error,
|
||||
# like any other failure. Eval keeps it as a scored outcome.
|
||||
trace.errors.append(vf.Error(type="Timeout", message=f"Trace stopped by {trace.stop_condition}"))
|
||||
trace.ok = False
|
||||
episode.ok = False
|
||||
if not trace.has_error and not trace.is_timeout and trace.num_turns == 0:
|
||||
# Empty trajectory: promote to an explicit error so the sink
|
||||
# treats it like any other failure (``has_error`` reads ``ok``)
|
||||
# treats it like any other failure (``has_error`` reads ``ok``).
|
||||
# A timed-out eval trace with no turns stays a timeout: scored, no samples.
|
||||
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
|
||||
trace.ok = False
|
||||
episode.ok = False
|
||||
|
||||
@@ -197,7 +197,7 @@ class TraceMetrics(StatGroup):
|
||||
"num_turns",
|
||||
"num_branches",
|
||||
)
|
||||
RATES = ("is_truncated", "is_completed")
|
||||
RATES = ("is_truncated", "is_timeout", "is_completed")
|
||||
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
return {
|
||||
@@ -321,6 +321,10 @@ class EpisodeMetrics:
|
||||
def is_truncated(self) -> Stat:
|
||||
return Stat([float(record.trace.is_truncated) for record in self.records])
|
||||
|
||||
@property
|
||||
def is_timeout(self) -> Stat:
|
||||
return Stat([float(record.trace.is_timeout) for record in self.records])
|
||||
|
||||
@property
|
||||
def has_error(self) -> Stat:
|
||||
return Stat(
|
||||
|
||||
@@ -883,7 +883,7 @@ class Orchestrator:
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max_off_policy_steps} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {eff.is_truncated.mean():.1%}"
|
||||
f"Truncation {eff.is_truncated.mean():.1%} | Timeout {episodes.metrics.is_timeout.mean():.1%}"
|
||||
)
|
||||
if len(self.train_envs) <= 1:
|
||||
get_logger().success(head)
|
||||
@@ -904,7 +904,7 @@ class Orchestrator:
|
||||
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {env_eff.is_truncated.mean():.1%}"
|
||||
f"Truncation {env_eff.is_truncated.mean():.1%} | Timeout {pool.metrics.is_timeout.mean():.1%}"
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
|
||||
@@ -952,7 +952,8 @@ class Orchestrator:
|
||||
f"Evaluated {batch.env_name} | "
|
||||
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%} | "
|
||||
f"Timeout {full.is_timeout.mean():.1%}"
|
||||
)
|
||||
|
||||
async def maybe_save_ckpt(self, step: int) -> float:
|
||||
|
||||
@@ -8,9 +8,8 @@ training sample directly. Token-length readers (`completion_len`, `total_tokens`
|
||||
live on `vf.Trace` itself.
|
||||
|
||||
Training is renderer-only across every mode (RL/OPD student, SFT teacher), so every node
|
||||
always carries its tokens — no backfill needed. For multimodal rollouts the branch also carries
|
||||
the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat `mm_kwargs` /
|
||||
`mm_token_type_ids` the trainer forwards.
|
||||
always carries its tokens — no backfill needed. Multimodal RL keeps the inline image URLs on
|
||||
the messages and pairs them with vLLM's expanded image-token runs here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,33 +19,48 @@ from collections.abc import Iterator
|
||||
import numpy as np
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts, SamplingMask
|
||||
from prime_rl.transports.batch import MMImageRef, MMRefs, TrainingSample
|
||||
from prime_rl.transports.batch.types import RoutedExperts, SamplingMask
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def _to_numpy(val) -> np.ndarray:
|
||||
"""A renderer mm item value (torch tensor or numpy array) -> a contiguous numpy array."""
|
||||
if hasattr(val, "detach"): # torch tensor
|
||||
val = val.detach().cpu().numpy()
|
||||
return np.ascontiguousarray(val)
|
||||
def _image_urls(branch: vf.Branch) -> list[str]:
|
||||
urls: list[str] = []
|
||||
for node in branch.nodes:
|
||||
content = node.message.content
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for part in content:
|
||||
if getattr(part, "type", None) == "image_url":
|
||||
urls.append(part.image_url.url)
|
||||
return urls
|
||||
|
||||
|
||||
def _encode_mm_kwargs(mm_items: dict[str, list[dict]]) -> dict[str, EncodedTensor] | None:
|
||||
"""Concatenate the branch's per-image renderer items into the flat `mm_kwargs` the trainer
|
||||
forwards — one `EncodedTensor` per kwarg key (e.g. `pixel_values`, `image_grid_thw`), images
|
||||
cat'd along dim 0 in branch token order. Model-agnostic: the keys are whatever the processor
|
||||
emits. Returns None when there are no items."""
|
||||
bins: dict[str, list[np.ndarray]] = {}
|
||||
for items in mm_items.values(): # per modality
|
||||
for item in items: # per image
|
||||
for key, val in item.items():
|
||||
bins.setdefault(key, []).append(_to_numpy(val))
|
||||
encoded: dict[str, EncodedTensor] = {}
|
||||
for key, arrs in bins.items():
|
||||
arr = np.concatenate(arrs, axis=0)
|
||||
encoded[key] = EncodedTensor(dtype=str(arr.dtype), shape=list(arr.shape), data=arr.tobytes())
|
||||
return encoded or None
|
||||
def _image_runs(token_types: list[int]) -> list[tuple[int, int]]:
|
||||
runs: list[tuple[int, int]] = []
|
||||
start: int | None = None
|
||||
for index, token_type in enumerate([*token_types, 0]):
|
||||
if token_type == 1 and start is None:
|
||||
start = index
|
||||
elif token_type != 1 and start is not None:
|
||||
runs.append((start, index - start))
|
||||
start = None
|
||||
return runs
|
||||
|
||||
|
||||
def _build_mm_refs(urls: list[str], token_types: list[int]) -> MMRefs | None:
|
||||
runs = _image_runs(token_types)
|
||||
if len(urls) != len(runs):
|
||||
raise ValueError(
|
||||
f"Inline image count does not match expanded placeholder runs: images={len(urls)}, runs={len(runs)}"
|
||||
)
|
||||
if not urls:
|
||||
return None
|
||||
return MMRefs(
|
||||
images=[
|
||||
MMImageRef(url=url, offset=offset, length=length) for url, (offset, length) in zip(urls, runs, strict=True)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExperts | None:
|
||||
@@ -140,19 +154,21 @@ def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSam
|
||||
`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. Errored traces are dropped upstream (`TrainSink.process_episode`), so no error
|
||||
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
|
||||
pixel tensors) and `mm_token_type_ids` (`branch.mm_token_type_ids`, computed from the
|
||||
trace's renderer-stamped `mm_token_type_id_map`). Branches with no sampled tokens
|
||||
(e.g. an openai client carrying none) yield nothing.
|
||||
handling happens here. A branch carrying images gets raw image refs paired with expanded
|
||||
placeholder ranges and `mm_token_type_ids`. Branches with no sampled tokens yield nothing.
|
||||
"""
|
||||
samples: list[TrainingSample] = []
|
||||
trained_loss_nodes: dict[str, set[int]] = {"rl": set(), "ce": set(), "ref_kl": set()}
|
||||
for branch, mask in iter_trainable_branches(trace):
|
||||
token_ids = branch.token_ids
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mmd = branch.multi_modal_data
|
||||
if mmd is not None:
|
||||
mm_kwargs = _encode_mm_kwargs(mmd.mm_items)
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
mm_refs: MMRefs | None = None
|
||||
image_urls = _image_urls(branch)
|
||||
if image_urls:
|
||||
mm_token_type_ids = branch.mm_token_type_ids
|
||||
if mm_token_type_ids is None:
|
||||
raise ValueError("Inline images have no expanded multimodal prompt tokens")
|
||||
mm_refs = _build_mm_refs(image_urls, mm_token_type_ids)
|
||||
samples.append(
|
||||
TrainingSample(
|
||||
token_ids=token_ids,
|
||||
@@ -161,8 +177,8 @@ def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSam
|
||||
temperatures=[], # filled by TrainSink.process_group
|
||||
env_name=env_name,
|
||||
ref_logprobs=branch.reference_logprobs,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=branch.mm_token_type_ids,
|
||||
mm_refs=mm_refs,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
routed_experts=_encode_routed_experts(branch.routed_experts, len(token_ids)),
|
||||
rl_weights=_loss_weights(branch, "rl", trained_loss_nodes["rl"]),
|
||||
ce_weights=_loss_weights(branch, "ce", trained_loss_nodes["ce"]),
|
||||
|
||||
@@ -6,7 +6,7 @@ from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, SamplingMask, TrainingSample
|
||||
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, SamplingMask, TrainingSample
|
||||
|
||||
# Backfill value per component weight stream when a packed sample doesn't
|
||||
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
|
||||
@@ -303,56 +303,17 @@ def _pad_sampling_mask(micro_batch: MicroBatch, padding_size: int) -> None:
|
||||
sampling_mask.counts += b"\0" * (padding_size * _SAMPLING_MASK_ITEMSIZE)
|
||||
|
||||
|
||||
def _slice_encoded(tensor: EncodedTensor, n_rows: int) -> EncodedTensor:
|
||||
"""First `n_rows` rows of a dim-0-stacked encoded tensor (e.g. pixel_values, image_grid_thw)."""
|
||||
row = int(np.prod(tensor.shape[1:])) if len(tensor.shape) > 1 else 1
|
||||
itemsize = np.dtype(tensor.dtype).itemsize
|
||||
return EncodedTensor(
|
||||
dtype=tensor.dtype,
|
||||
shape=[n_rows, *tensor.shape[1:]],
|
||||
data=tensor.data[: n_rows * row * itemsize],
|
||||
)
|
||||
|
||||
|
||||
def _truncate_mm(
|
||||
mm_token_type_ids: list[int], mm_kwargs: dict[str, EncodedTensor], seq_len: int
|
||||
) -> tuple[int, dict[str, EncodedTensor] | None]:
|
||||
"""Truncating a sample must not split an image's placeholder block, else the surviving image
|
||||
token count no longer matches the image embeddings in `mm_kwargs`. Returns the cut point
|
||||
(<= seq_len, never inside an image block) and `mm_kwargs` sliced to the images whose
|
||||
placeholders fully survive (None if no image survives)."""
|
||||
grid = np.frombuffer(bytearray(mm_kwargs["image_grid_thw"].data), dtype=mm_kwargs["image_grid_thw"].dtype).reshape(
|
||||
mm_kwargs["image_grid_thw"].shape
|
||||
)
|
||||
patches_per_image = [int(g.prod()) for g in grid]
|
||||
total_patches = mm_kwargs["pixel_values"].shape[0]
|
||||
total_tokens = sum(1 for t in mm_token_type_ids if t)
|
||||
ppt = total_patches // total_tokens if total_tokens else 1 # patches per token (merge^2)
|
||||
tokens_per_image = [p // ppt for p in patches_per_image]
|
||||
|
||||
surviving = sum(1 for t in mm_token_type_ids[:seq_len] if t)
|
||||
kept = acc = 0
|
||||
for n in tokens_per_image:
|
||||
if acc + n > surviving:
|
||||
def _truncate_mm_refs(refs: MMRefs, seq_len: int) -> tuple[int, MMRefs | None]:
|
||||
cut = seq_len
|
||||
kept: list[MMImageRef] = []
|
||||
for image in refs.images:
|
||||
end = image.offset + image.length
|
||||
if image.offset < seq_len < end:
|
||||
cut = image.offset
|
||||
break
|
||||
acc += n
|
||||
kept += 1
|
||||
if acc == surviving:
|
||||
cut = seq_len # surviving image tokens are exactly `kept` whole images
|
||||
else:
|
||||
# `surviving` lands inside image `kept`; cut to its first placeholder, dropping it.
|
||||
seen, cut = 0, seq_len
|
||||
for i, t in enumerate(mm_token_type_ids):
|
||||
if t:
|
||||
seen += 1
|
||||
if seen == acc + 1:
|
||||
cut = i
|
||||
break
|
||||
if not kept:
|
||||
return cut, None
|
||||
kept_patches = sum(patches_per_image[:kept])
|
||||
sliced = {k: _slice_encoded(v, kept if k == "image_grid_thw" else kept_patches) for k, v in mm_kwargs.items()}
|
||||
return cut, sliced
|
||||
if end <= seq_len:
|
||||
kept.append(image)
|
||||
return cut, MMRefs(images=kept) if kept else None
|
||||
|
||||
|
||||
def multimodal_sample_error(sample: TrainingSample) -> str | None:
|
||||
@@ -362,8 +323,14 @@ def multimodal_sample_error(sample: TrainingSample) -> str | None:
|
||||
"mm_token_type_ids length must match token_ids length "
|
||||
f"({len(mm_token_type_ids)} != {len(sample.token_ids)})"
|
||||
)
|
||||
if sample.mm_kwargs is not None and "image_grid_thw" in sample.mm_kwargs and mm_token_type_ids is None:
|
||||
return "image_grid_thw multimodal samples require mm_token_type_ids"
|
||||
if sample.mm_refs is not None and mm_token_type_ids is None:
|
||||
return "multimodal samples require mm_token_type_ids"
|
||||
if sample.mm_refs is not None:
|
||||
previous_end = 0
|
||||
for image in sample.mm_refs.images:
|
||||
if image.offset < previous_end or image.offset + image.length > len(sample.token_ids):
|
||||
return "multimodal image refs must be ordered, non-overlapping, and within token_ids"
|
||||
previous_end = image.offset + image.length
|
||||
return None
|
||||
|
||||
|
||||
@@ -395,7 +362,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
ref_kl_weights = list(training_example.ref_kl_weights) if training_example.ref_kl_weights is not None else None
|
||||
position_ids = list(range(len(input_ids)))
|
||||
mm_token_type_ids = training_example.mm_token_type_ids
|
||||
mm_kwargs = training_example.mm_kwargs
|
||||
mm_refs = training_example.mm_refs
|
||||
assert training_example.env_name != "all", "env_name='all' is reserved for aggregate metric keys"
|
||||
env_names = [training_example.env_name] * len(input_ids)
|
||||
|
||||
@@ -413,11 +380,9 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
sampling_mask = training_example.sampling_mask
|
||||
|
||||
if len(input_ids) > seq_len:
|
||||
# Multimodal: never split an image's placeholder block — cut to a whole-image boundary
|
||||
# and slice mm_kwargs to match, so image-token count == image-embedding count.
|
||||
cut = seq_len
|
||||
if mm_token_type_ids is not None and mm_kwargs is not None:
|
||||
cut, mm_kwargs = _truncate_mm(mm_token_type_ids, mm_kwargs, seq_len)
|
||||
if mm_refs is not None:
|
||||
cut, mm_refs = _truncate_mm_refs(mm_refs, seq_len)
|
||||
input_ids = input_ids[:cut]
|
||||
loss_mask = loss_mask[:cut]
|
||||
inference_logprobs = inference_logprobs[:cut]
|
||||
@@ -488,7 +453,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
sampling_mask=sampling_mask,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_refs=mm_refs,
|
||||
rl_weights=rl_weights,
|
||||
ce_weights=ce_weights,
|
||||
ref_kl_weights=ref_kl_weights,
|
||||
@@ -500,7 +465,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
|
||||
def _is_multimodal_sample(sample: MicroBatch) -> bool:
|
||||
"""Check if a sample contains multimodal data (images)."""
|
||||
return sample.mm_kwargs is not None
|
||||
return sample.mm_refs is not None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -516,36 +481,15 @@ class _MicroBatchBin:
|
||||
def first_sample(self) -> MicroBatch:
|
||||
return self.samples[0]
|
||||
|
||||
@property
|
||||
def first_multimodal_sample(self) -> MicroBatch | None:
|
||||
for sample in self.samples:
|
||||
if _is_multimodal_sample(sample):
|
||||
return sample
|
||||
return None
|
||||
|
||||
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
|
||||
# Loss routing is per token (component weight streams), so samples of
|
||||
# different loss types pack together freely. Multimodal packing is still
|
||||
# constrained by modality sidecars, length, and routed experts.
|
||||
# different loss types and raw-image refs pack together freely.
|
||||
first_sample = self.first_sample
|
||||
if self.length + len(sample.input_ids) > max_seq_len:
|
||||
return False
|
||||
if (first_sample.routed_experts is None) != (sample.routed_experts is None):
|
||||
return False
|
||||
|
||||
sample_is_mm = _is_multimodal_sample(sample)
|
||||
existing_mm_sample = self.first_multimodal_sample
|
||||
if existing_mm_sample is not None and sample_is_mm:
|
||||
dst = existing_mm_sample.mm_kwargs
|
||||
src = sample.mm_kwargs
|
||||
assert dst is not None and src is not None, "multimodal samples must carry mm_kwargs"
|
||||
return set(dst) == set(src) and all(
|
||||
dst[key].dtype == src[key].dtype
|
||||
and len(dst[key].shape) > 0
|
||||
and len(dst[key].shape) == len(src[key].shape)
|
||||
and dst[key].shape[1:] == src[key].shape[1:]
|
||||
for key in dst
|
||||
)
|
||||
return True
|
||||
|
||||
def add(self, sample: MicroBatch) -> None:
|
||||
@@ -594,7 +538,7 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
env_names: list[str] = []
|
||||
ref_logprobs: list[float] | None = [] if has_ref_logprobs else None
|
||||
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mm_refs: MMRefs | None = None
|
||||
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
|
||||
seq_lens: list[int] = []
|
||||
routed_experts: RoutedExperts | None = None
|
||||
@@ -630,13 +574,17 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
assert routed_experts.shape[1:] == sample.routed_experts.shape[1:]
|
||||
routed_experts.data += sample.routed_experts.data
|
||||
routed_experts.shape[0] += sample.routed_experts.shape[0]
|
||||
if sample.mm_kwargs is not None:
|
||||
if mm_kwargs is None:
|
||||
mm_kwargs = copy.deepcopy(sample.mm_kwargs)
|
||||
else:
|
||||
for key in mm_kwargs:
|
||||
mm_kwargs[key].data += sample.mm_kwargs[key].data
|
||||
mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0]
|
||||
if sample.mm_refs is not None:
|
||||
if mm_refs is None:
|
||||
mm_refs = MMRefs(images=[])
|
||||
mm_refs.images.extend(
|
||||
MMImageRef(
|
||||
url=image.url,
|
||||
offset=len(input_ids) - sample_len + image.offset,
|
||||
length=image.length,
|
||||
)
|
||||
for image in sample.mm_refs.images
|
||||
)
|
||||
seq_lens.extend(sample.seq_lens)
|
||||
if sampling_mask is not None:
|
||||
sample_mask = sample.sampling_mask if sample.sampling_mask is not None else _empty_sampling_mask(sample_len)
|
||||
@@ -662,7 +610,7 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
sampling_mask=sampling_mask,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_refs=mm_refs,
|
||||
rl_weights=streams["rl_weights"],
|
||||
ce_weights=streams["ce_weights"],
|
||||
ref_kl_weights=streams["ref_kl_weights"],
|
||||
@@ -679,7 +627,7 @@ def _expand_bins_by_splitting(
|
||||
candidates = [
|
||||
(bin_content.workload(bin_cost), idx)
|
||||
for idx, bin_content in enumerate(bins)
|
||||
if len(bin_content.samples) > 1 and bin_content.first_multimodal_sample is None
|
||||
if len(bin_content.samples) > 1
|
||||
]
|
||||
if not candidates:
|
||||
break
|
||||
@@ -700,9 +648,8 @@ def packed_samples_into_micro_bs(
|
||||
We follow the First Fit Decreasing algorithm to pack the samples into bins and minimize potential padding while never truncating.
|
||||
With per-token temperatures, samples can be packed together regardless of their temperature values.
|
||||
|
||||
Multimodal samples pack with text spans and with compatible eager
|
||||
``mm_kwargs`` samples. Packed batches preserve sample boundaries in
|
||||
``seq_lens``.
|
||||
Multimodal samples pack with text spans and other raw-image samples. Packed
|
||||
batches preserve sample boundaries in ``seq_lens``.
|
||||
"""
|
||||
# Sort by decreasing length for packing efficiency
|
||||
samples.sort(key=lambda sample: -len(sample.input_ids))
|
||||
|
||||
@@ -10,6 +10,7 @@ os.environ.setdefault("USE_HUB_KERNELS", "NO")
|
||||
|
||||
import torch
|
||||
import torch._dynamo
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from huggingface_hub import snapshot_download
|
||||
from jaxtyping import Int
|
||||
@@ -30,6 +31,7 @@ from prime_rl.configs.trainer import (
|
||||
MXFP8Config,
|
||||
TokenizerConfig,
|
||||
)
|
||||
from prime_rl.multimodal import ForwardPolicy
|
||||
from prime_rl.trainer.activation_checkpointing import get_activation_checkpoint_wrapper
|
||||
from prime_rl.trainer.lora import apply_lora_to_model, freeze_all_except_lora_and_specified, strip_lora_from_state_dict
|
||||
from prime_rl.trainer.models import (
|
||||
@@ -240,38 +242,69 @@ def is_tt_moe_model(model: nn.Module) -> bool:
|
||||
|
||||
|
||||
def get_load_balance_stats(
|
||||
model: nn.Module, reset_stats: bool = True, try_to_avoid_padding_experts: bool = True
|
||||
model: nn.Module,
|
||||
group: dist.ProcessGroup | None = None,
|
||||
) -> dict[str, Tensor | None]:
|
||||
"""Compute routing stats after summing raw counts across the group, if given."""
|
||||
per_layer_max_vio = []
|
||||
per_layer_routing_confidence = []
|
||||
language_model = get_language_model(model)
|
||||
block_mlps = []
|
||||
for transformer_block in language_model.layers:
|
||||
# This is necessary for models that have mixed dense layers
|
||||
block_mlp = getattr(transformer_block, "mlp", None)
|
||||
if block_mlp is None or not hasattr(block_mlp, "tokens_per_expert"):
|
||||
continue
|
||||
tokens_per_expert: torch.Tensor = block_mlp.tokens_per_expert
|
||||
if block_mlp is not None and hasattr(block_mlp, "tokens_per_expert"):
|
||||
block_mlps.append(block_mlp)
|
||||
if not block_mlps:
|
||||
return {"max_vio": None, "routing_confidence": None}
|
||||
|
||||
layer_stats = [(block_mlp.tokens_per_expert, block_mlp.routing_confidence_sum) for block_mlp in block_mlps]
|
||||
if group is not None:
|
||||
sizes = [tokens_per_expert.numel() + 1 for tokens_per_expert, _ in layer_stats]
|
||||
packed_stats = torch.cat(
|
||||
[torch.cat((tokens_per_expert, confidence.reshape(1))) for tokens_per_expert, confidence in layer_stats]
|
||||
)
|
||||
dist.all_reduce(packed_stats, op=dist.ReduceOp.SUM, group=group)
|
||||
layer_stats = [(stats[:-1], stats[-1]) for stats in packed_stats.split(sizes)]
|
||||
|
||||
for block_mlp, (tokens_per_expert, routing_confidence_sum) in zip(block_mlps, layer_stats):
|
||||
num_routed_tokens = tokens_per_expert.sum() / block_mlp.router.top_k
|
||||
if try_to_avoid_padding_experts:
|
||||
tokens_per_expert = tokens_per_expert.sort(dim=0, descending=True).values[block_mlp.router.top_k :]
|
||||
tokens_per_expert = tokens_per_expert.sort(dim=0, descending=True).values[block_mlp.router.top_k :]
|
||||
balanced_load = tokens_per_expert.mean()
|
||||
max_vio = (tokens_per_expert.max() - balanced_load) / balanced_load
|
||||
per_layer_max_vio.append(max_vio.detach())
|
||||
|
||||
routing_confidence = block_mlp.routing_confidence_sum / num_routed_tokens
|
||||
routing_confidence = routing_confidence_sum / num_routed_tokens
|
||||
per_layer_routing_confidence.append(routing_confidence.detach())
|
||||
|
||||
if reset_stats:
|
||||
block_mlp.tokens_per_expert.zero_()
|
||||
block_mlp.routing_confidence_sum.zero_()
|
||||
if len(per_layer_max_vio) == 0:
|
||||
return {"max_vio": None, "routing_confidence": None}
|
||||
block_mlp.tokens_per_expert.zero_()
|
||||
block_mlp.routing_confidence_sum.zero_()
|
||||
return {
|
||||
"max_vio": torch.stack(per_layer_max_vio),
|
||||
"routing_confidence": torch.stack(per_layer_routing_confidence),
|
||||
}
|
||||
|
||||
|
||||
def get_global_moe_stats(
|
||||
model: nn.Module,
|
||||
ep_group: dist.ProcessGroup | None,
|
||||
dp_cp_group: dist.ProcessGroup,
|
||||
) -> dict[str, Tensor]:
|
||||
"""Reduce one microstep's routing stats across EP, then DP and CP ranks."""
|
||||
stats = {}
|
||||
for name, values in get_load_balance_stats(model, group=ep_group).items():
|
||||
if values is None:
|
||||
continue
|
||||
value = values.max() if name == "max_vio" else values.mean()
|
||||
if name == "max_vio":
|
||||
dist.all_reduce(value, op=dist.ReduceOp.MAX, group=dp_cp_group)
|
||||
else:
|
||||
dist.all_reduce(value, op=dist.ReduceOp.SUM, group=dp_cp_group)
|
||||
value /= dist.get_world_size(dp_cp_group)
|
||||
stats[name] = value.to("cpu")
|
||||
return stats
|
||||
|
||||
|
||||
def get_model(
|
||||
config: ModelConfig, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.bfloat16
|
||||
) -> nn.Module:
|
||||
@@ -889,6 +922,7 @@ def _reset_runtime_moe_buffers(model: nn.Module) -> None:
|
||||
for module in model.modules():
|
||||
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
|
||||
module.tokens_per_expert.zero_()
|
||||
module.routing_confidence_sum.zero_()
|
||||
|
||||
|
||||
def _validate_flash_attn_4_installed() -> None:
|
||||
@@ -914,13 +948,14 @@ def _validate_flash_attn_4_installed() -> None:
|
||||
def resolve_auto_attn(config: ModelConfig) -> None:
|
||||
"""Resolve ``attn='auto'`` to a concrete flash attention implementation based on GPU architecture.
|
||||
|
||||
FA4 on Blackwell or newer (SM100+, incl. SM103 B300/GB300), FA3 on Hopper (SM90),
|
||||
FA2 otherwise.
|
||||
FA4 on datacenter Blackwell (SM10x/SM11x, e.g. B200, B300), FA3 on Hopper (SM90), FA2
|
||||
otherwise. FA4 is built around the tcgen05/TMEM instructions of the SM10x/SM11x families.
|
||||
Workstation Blackwell (SM12x, e.g. RTX PRO 6000) lacks them, so it gets FA2.
|
||||
"""
|
||||
if config.attn != "auto":
|
||||
return
|
||||
major, minor = torch.cuda.get_device_capability()
|
||||
if major >= 10:
|
||||
if major in (10, 11):
|
||||
resolved = "flash_attention_4"
|
||||
elif major == 9:
|
||||
resolved = "flash_attention_3"
|
||||
@@ -1054,12 +1089,8 @@ def forward(
|
||||
temperature: Tensor | None = None,
|
||||
routed_experts: Int[Tensor, "batch seq layers topk"] | None = None,
|
||||
sampling_mask: Int[Tensor, "batch seq mask"] | None = None,
|
||||
# Generic multimodal kwargs (e.g. {"pixel_values": ...,
|
||||
# "image_grid_thw": ...} for Qwen3-VL; just {"pixel_values": ...}
|
||||
# for Gemma3). Passed straight through to ``model(**kwargs)`` so
|
||||
# the model's HF forward signature is the schema. ``mm_token_type_ids``
|
||||
# is split out because it comes from the renderer rather than the processor.
|
||||
mm_kwargs: dict[str, Tensor] | None = None,
|
||||
mm_forward_policy: ForwardPolicy | None = None,
|
||||
mm_token_type_ids: Int[Tensor, "batch seq"] | None = None,
|
||||
# True when seq_lens holds the full pre-CP-shard document boundaries
|
||||
# (kept global because documents can straddle the shard cut).
|
||||
@@ -1077,13 +1108,15 @@ def forward(
|
||||
kwargs["sampling_mask"] = sampling_mask
|
||||
|
||||
if mm_kwargs:
|
||||
# Forward the per-model multimodal tensors verbatim, plus the
|
||||
# renderer-supplied ``mm_token_type_ids`` (renderer owns the
|
||||
# token→modality mapping via ``mm_token_type_id_map``).
|
||||
kwargs.update(mm_kwargs)
|
||||
if mm_token_type_ids is not None:
|
||||
kwargs["mm_token_type_ids"] = mm_token_type_ids
|
||||
if "image_grid_thw" not in mm_kwargs:
|
||||
# SFT still uses its existing eager processor path and does not provide
|
||||
# an adapter policy yet, so preserve its current kwargs-based behavior.
|
||||
policy = mm_forward_policy or ForwardPolicy(pass_position_ids="image_grid_thw" not in mm_kwargs)
|
||||
if policy.requires_mm_token_type_ids and mm_token_type_ids is None:
|
||||
raise ValueError("Multimodal forward policy requires mm_token_type_ids")
|
||||
if policy.pass_position_ids:
|
||||
kwargs["position_ids"] = position_ids
|
||||
else:
|
||||
kwargs["position_ids"] = position_ids
|
||||
|
||||
@@ -392,8 +392,6 @@ class SparseAttnInputs:
|
||||
|
||||
# A surplus pick is `IGNORE_SLOT` (-1) and stays `IGNORE_SLOT`; a real one names an entry,
|
||||
# which sits past the token stream in `kv_buf`, hence the shift by `n_tokens`.
|
||||
# NOTE: the attention kernel recompiles for every unique `indices.shape[-1]` value. If
|
||||
# recompilation becomes a bottleneck, consider padding to fixed length with `IGNORE_SLOT` values.
|
||||
picks = torch.where(top_k_indices >= 0, top_k_indices + n_tokens, IGNORE_SLOT)
|
||||
indices = torch.cat([window, picks[:, :, None, :].to(torch.int32)], dim=-1)
|
||||
return cls(kv_buf=kv_buf, indices=indices)
|
||||
|
||||
@@ -30,6 +30,7 @@ LOG2E = 1.44269504
|
||||
# The forward tiles the gather-slot axis at `block_I = 64` and the backward at `block_size = 32`,
|
||||
# so the slot count must be a multiple of `lcm(64, 32) = 64`.
|
||||
SLOT_TILE = 64
|
||||
BWD_SLOT_TILE = 32
|
||||
|
||||
|
||||
def _pad_slots_to_tile(indices: torch.Tensor) -> torch.Tensor:
|
||||
@@ -47,6 +48,20 @@ def _pad_slots_to_tile(indices: torch.Tensor) -> torch.Tensor:
|
||||
return F.pad(indices, (0, SLOT_TILE - remainder), value=IGNORE_SLOT).contiguous()
|
||||
|
||||
|
||||
def num_tiles_covering_valid_slots(indices: torch.Tensor, tile_size: int) -> torch.Tensor:
|
||||
"""Per query, the number of leading tiles of `tile_size` slots it takes to contain every valid slot.
|
||||
|
||||
`indices` is `(batch, seq_len, num_kv_heads, n_slots)` and the result is
|
||||
`(batch, seq_len, num_kv_heads)`, both int32.
|
||||
"""
|
||||
n_slots = indices.shape[-1]
|
||||
assert n_slots % tile_size == 0, f"n_slots must be a multiple of tile_size {tile_size}, got {n_slots}"
|
||||
slot_idxs = torch.arange(n_slots, device=indices.device, dtype=torch.int32)
|
||||
is_valid_slot = indices >= 0
|
||||
last_valid_slot_idx = torch.where(is_valid_slot, slot_idxs, -1).amax(dim=-1)
|
||||
return last_valid_slot_idx // tile_size + 1
|
||||
|
||||
|
||||
def sparse_attn_shape_error(heads: int, kv_group: int, dim: int) -> str | None:
|
||||
"""The reason these kernels cannot serve this shape, or ``None`` if they can.
|
||||
|
||||
@@ -107,13 +122,14 @@ def dsv4_sparse_attn(
|
||||
assert shape_error is None, shape_error
|
||||
assert indices.shape[:3] == (batch, seq_len, kv_group)
|
||||
assert sinks.shape == (heads,)
|
||||
assert SLOT_TILE % block_I == 0, (
|
||||
f"the slot axis is padded to a multiple of {SLOT_TILE}, so block_I must divide it, got {block_I}"
|
||||
)
|
||||
indices = _pad_slots_to_tile(indices)
|
||||
topk = indices.shape[-1]
|
||||
|
||||
kernel = dsv4_sparse_attn_fwd(
|
||||
heads,
|
||||
dim,
|
||||
topk,
|
||||
kv_group,
|
||||
sm_scale,
|
||||
True,
|
||||
@@ -121,7 +137,9 @@ def dsv4_sparse_attn(
|
||||
num_stages=num_stages,
|
||||
threads=threads,
|
||||
)
|
||||
out, lse = kernel(q, kv, indices, sinks.float().contiguous())
|
||||
tiled_indices = indices.view(batch, seq_len, kv_group, -1, block_I)
|
||||
tile_counts = num_tiles_covering_valid_slots(indices, block_I)
|
||||
out, lse = kernel(q, kv, tiled_indices, sinks.float().contiguous(), tile_counts)
|
||||
return out, lse
|
||||
|
||||
|
||||
@@ -166,15 +184,16 @@ def dsv4_sparse_attn_backward(
|
||||
assert indices.shape[:3] == (batch, seq_len, kv_group)
|
||||
assert lse.shape == (batch, seq_len, heads)
|
||||
indices = _pad_slots_to_tile(indices)
|
||||
topk = indices.shape[-1]
|
||||
|
||||
preprocess_kernel = preprocess(heads, dim)
|
||||
bwd_kernel = bwd(heads, dim, topk, kv_group, sm_scale, True)
|
||||
bwd_kernel = bwd(heads, dim, kv_group, sm_scale, True, block_size=BWD_SLOT_TILE)
|
||||
postprocess_kernel = postprocess(dim, kv_group)
|
||||
|
||||
delta = preprocess_kernel(out, grad_out)
|
||||
dkv = torch.zeros_like(kv, dtype=torch.float32)
|
||||
dq = bwd_kernel(q, kv, grad_out, indices, lse, delta, dkv)
|
||||
tiled_indices = indices.view(batch, seq_len, kv_group, -1, BWD_SLOT_TILE)
|
||||
tile_counts = num_tiles_covering_valid_slots(indices, BWD_SLOT_TILE)
|
||||
dq = bwd_kernel(q, kv, grad_out, tiled_indices, lse, delta, tile_counts, dkv)
|
||||
dkv = postprocess_kernel(dkv)
|
||||
|
||||
return dq, dkv, delta
|
||||
|
||||
@@ -15,6 +15,11 @@ Beyond the forward's tensors:
|
||||
dQ[b, s, h, d] (B, S, H, D) bfloat16
|
||||
dKV[b, n, g, d] (B, N, G, D) float32 until `postprocess`
|
||||
|
||||
`Indices` arrives tiled as in the forward, but at this kernel's own tile:
|
||||
`(B, S, G, n_tiles, block_size)` with `n_tiles = K / block_size`, and only `n_tiles` symbolic. `TileCounts` is the
|
||||
forward's too, counted in these tiles, and skipping the tiles past it is exact for the same reason:
|
||||
a masked slot contributes nothing to any gradient.
|
||||
|
||||
[What it computes]
|
||||
|
||||
With `key[b,s,k,d] = KV[b, Indices[b,s,0,k], 0, d]` and `scale = D ** -0.5` as in the forward:
|
||||
@@ -50,8 +55,8 @@ negative.
|
||||
[How the loop runs]
|
||||
|
||||
The grid is `(query position, batch, head block)`, the third axis also carrying the KV head when
|
||||
`G > 1`, and at `H <= 64` it is a single block covering every query head. The block walks the `K`
|
||||
slots in tiles of `block_size`, half the forward's tile, and per tile:
|
||||
`G > 1`, and at `H <= 64` it is a single block covering every query head. The block walks its first
|
||||
`TileCounts[b,s,g]` tiles of `block_size` slots, half the forward's tile, and per tile:
|
||||
|
||||
1. gather `KV_shared[k,d]`, and seed `acc_p` to `0` or `-inf` from the mask
|
||||
2. `acc_p[h,k] += Q_shared[h,d] KV_shared[k,d]` onto that seed, then `exp2(... - Lse)` in place,
|
||||
@@ -167,7 +172,6 @@ def postprocess(
|
||||
def bwd(
|
||||
H,
|
||||
D,
|
||||
topk,
|
||||
kv_group=1,
|
||||
sm_scale=None,
|
||||
is_causal=True,
|
||||
@@ -179,7 +183,6 @@ def bwd(
|
||||
accum_dtype=T.float32,
|
||||
):
|
||||
assert is_causal is True, "non-casual is not supported now"
|
||||
assert topk % block_size == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
|
||||
assert dtype == T.bfloat16
|
||||
assert accum_dtype == T.float32
|
||||
assert indices_dtype == T.int32
|
||||
@@ -191,13 +194,15 @@ def bwd(
|
||||
B = T.dynamic("B")
|
||||
S = T.dynamic("S")
|
||||
S_kv = T.dynamic("S_kv")
|
||||
n_tiles = T.dynamic("n_tiles")
|
||||
|
||||
H_kv = H // kv_group
|
||||
q_shape = [B, S, H, D]
|
||||
k_shape = [B, S_kv, kv_group, D]
|
||||
o_shape = [B, S, H, D]
|
||||
indices_shape = [B, S, kv_group, topk]
|
||||
indices_shape = [B, S, kv_group, n_tiles, block_size]
|
||||
delta_shape = [B, S, H]
|
||||
tile_counts_shape = [B, S, kv_group]
|
||||
lse_shape = [B, S, H]
|
||||
|
||||
H = H_kv
|
||||
@@ -206,7 +211,6 @@ def bwd(
|
||||
assert padded_H % block_H == 0
|
||||
NH = padded_H // block_H
|
||||
BS = block_size
|
||||
NS = tilelang.cdiv(topk, block_size)
|
||||
|
||||
split_store = 2
|
||||
# The acc_dkv accumulator's per-thread layout (from the GEMMs that produce it) is only
|
||||
@@ -231,6 +235,7 @@ def bwd(
|
||||
Indices: T.Tensor(indices_shape, indices_dtype),
|
||||
Lse: T.Tensor(lse_shape, accum_dtype),
|
||||
Delta: T.Tensor(delta_shape, accum_dtype),
|
||||
TileCounts: T.Tensor(tile_counts_shape, indices_dtype),
|
||||
dQ: T.Tensor(q_shape, dtype),
|
||||
dKV: T.Tensor(k_shape, accum_dtype),
|
||||
):
|
||||
@@ -260,15 +265,18 @@ def bwd(
|
||||
|
||||
T.clear(acc_dq)
|
||||
|
||||
for i_i in T.Pipelined(NS, num_stages=num_stages):
|
||||
# `TileCounts` never exceeds `n_tiles`, but TileLang cannot know that; the `min` lets it
|
||||
# prove every `Indices` read in bounds. Without it, TileLang guards each read with a
|
||||
# runtime check inside the hot loop, which noticeably slows the backward.
|
||||
for i_i in T.Pipelined(T.min(TileCounts[by, s_i, bz // NH], n_tiles), num_stages=num_stages):
|
||||
for bi_i in T.Parallel(BS):
|
||||
mask[bi_i] = Indices[by, s_i, bz // NH, i_i * BS + bi_i] >= 0
|
||||
mask[bi_i] = Indices[by, s_i, bz // NH, i_i, bi_i] >= 0
|
||||
|
||||
for h_i, bi_i in T.Parallel(block_H, BS):
|
||||
acc_p[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_p.dtype))
|
||||
|
||||
for bi_i, d_i in T.Parallel(BS, D):
|
||||
KV_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i * BS + bi_i], bz // NH, d_i]
|
||||
KV_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i, bi_i], bz // NH, d_i]
|
||||
|
||||
T.gemm(Q_shared, KV_shared, acc_p, transpose_B=True, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
@@ -313,9 +321,9 @@ def bwd(
|
||||
# dKV. Do not add a predicate back: reading the `mask` fragment here compiles
|
||||
# cleanly but pins this loop to the four threads owning those elements.
|
||||
for bi_i, d_i in T.Parallel(BS // split_store, D // 4):
|
||||
slot_i = i_i * BS + bi_i + s * (BS // split_store)
|
||||
slot_i = bi_i + s * (BS // split_store)
|
||||
T.atomic_addx4(
|
||||
dKV[by, Indices[by, s_i, bz // NH, slot_i], bz // NH, d_i * 4],
|
||||
dKV[by, Indices[by, s_i, bz // NH, i_i, slot_i], bz // NH, d_i * 4],
|
||||
acc_dkv_shared[bi_i, d_i * 4],
|
||||
)
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ Shapes, with the capital of an index letter naming that axis's size:
|
||||
KV[b, n, g, d] (B, N, G, D) keys, bfloat16; V == K here, so one buffer is both
|
||||
Indices[b, s, g, k] (B, S, G, K) int32 positions into KV's `n` axis
|
||||
Sinks[h] (H,) float32, one learnable logit per query head
|
||||
TileCounts[b, s, g] (B, S, G) int32, how many leading slot tiles the query reads
|
||||
Output[b, s, h, d] (B, S, H, D) bfloat16
|
||||
Lse[b, s, h] (B, S, H) float32
|
||||
|
||||
@@ -30,6 +31,12 @@ asserts `G == 1` outright, so the equations below fix `g = 0` and drop it. Note
|
||||
is spelled `kv_group` but counts KV heads; the query heads per KV head are `H / G`, spelled
|
||||
`head_kv`.
|
||||
|
||||
`Indices` is listed by its logical shape, but the kernel receives it split into
|
||||
`n_tiles = K / block_I` tiles of `block_I` slots, as `(B, S, G, n_tiles, block_I)`. `K` is sized for
|
||||
the most keys any query could need, and a given query will often have fewer. Only `n_tiles` is
|
||||
symbolic, so one compiled kernel serves every `K`. Declaring `K` itself symbolic instead makes
|
||||
TileLang bounds-check every slot read against it, a runtime check inside the innermost loop.
|
||||
|
||||
[What it computes]
|
||||
|
||||
Write `key[b,s,k,d] = KV[b, Indices[b,s,0,k], 0, d]` for the gathered keys. Summing over repeated
|
||||
@@ -50,8 +57,10 @@ a shrunken combination of the gathered keys. That is how a head attends to nothi
|
||||
|
||||
[What the caller must guarantee]
|
||||
|
||||
`K` is fixed when the kernel compiles and is part of its compilation key, so it is sized for the
|
||||
most keys any query could need and a given query will often have fewer.
|
||||
`TileCounts[b,s,g]` must cover the query's last valid slot: every slot past its first
|
||||
`TileCounts * block_I` has to be masked, because the kernel never reads those tiles. A fully masked
|
||||
tile changes nothing in the online softmax, so skipping one is exact, and a query that reaches
|
||||
only a few of the `K` slots pays for only those.
|
||||
|
||||
Every unused slot must hold a negative index, which is the masking condition:
|
||||
|
||||
@@ -69,8 +78,8 @@ would cost a sync, so an out-of-range index silently corrupts that query's softm
|
||||
|
||||
The grid is `(query position, batch, KV head)`, so with `G == 1` that is one block per query
|
||||
position per batch index, holding all `H` query heads of that query at once, or a 64-head chunk
|
||||
when `H > 64` (`REPLICATE_H`). The block walks the `K` slots in tiles of `block_I`,
|
||||
software-pipelined `num_stages` deep, and per tile:
|
||||
when `H > 64` (`REPLICATE_H`). The block walks its first `TileCounts[b,s,g]` tiles of `block_I`
|
||||
slots, software-pipelined `num_stages` deep, and per tile:
|
||||
|
||||
1. gather `KV_shared[k,d] = KV[b, Indices[b,s,0,k], 0, d]` into one shared tile of keys
|
||||
2. `acc_s[h,k] = Q_shared[h,d] KV_shared[k,d]`, pre-seeded to `-inf` at masked slots
|
||||
@@ -122,7 +131,6 @@ LOG2E = 1.44269504
|
||||
def dsv4_sparse_attn_fwd(
|
||||
heads,
|
||||
dim,
|
||||
topk,
|
||||
kv_group=1,
|
||||
sm_scale=None,
|
||||
is_causal=True,
|
||||
@@ -132,7 +140,6 @@ def dsv4_sparse_attn_fwd(
|
||||
):
|
||||
assert dim == tilelang.math.next_power_of_2(dim), f"haven't check padding correctness yet, dim={dim}"
|
||||
assert is_causal is True, "non-casual is not supported"
|
||||
assert topk % block_I == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
|
||||
if sm_scale is None:
|
||||
sm_scale = (1.0 / dim) ** 0.5
|
||||
# Both names are kept: the sink logit enters the softmax unscaled, so seeding the running max
|
||||
@@ -142,13 +149,15 @@ def dsv4_sparse_attn_fwd(
|
||||
batch = T.dynamic("batch")
|
||||
seq_len = T.dynamic("seq_len")
|
||||
seq_len_kv = T.dynamic("seq_len_kv")
|
||||
n_tiles = T.dynamic("n_tiles")
|
||||
|
||||
head_kv = heads // kv_group
|
||||
q_shape = [batch, seq_len, heads, dim]
|
||||
kv_shape = [batch, seq_len_kv, kv_group, dim]
|
||||
o_shape = [batch, seq_len, heads, dim]
|
||||
indices_shape = [batch, seq_len, kv_group, topk]
|
||||
indices_shape = [batch, seq_len, kv_group, n_tiles, block_I]
|
||||
sinks_shape = [heads]
|
||||
tile_counts_shape = [batch, seq_len, kv_group]
|
||||
lse_shape = [batch, seq_len, heads]
|
||||
indices_dtype = T.int32
|
||||
dtype = T.bfloat16
|
||||
@@ -163,7 +172,6 @@ def dsv4_sparse_attn_fwd(
|
||||
" automatically)"
|
||||
)
|
||||
BI = block_I
|
||||
NI = tilelang.cdiv(topk, block_I)
|
||||
D = dim
|
||||
|
||||
if head_kv > 64:
|
||||
@@ -180,6 +188,7 @@ def dsv4_sparse_attn_fwd(
|
||||
KV: T.Tensor(kv_shape, dtype), # type: ignore
|
||||
Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore
|
||||
Sinks: T.Tensor(sinks_shape, accum_dtype), # type: ignore
|
||||
TileCounts: T.Tensor(tile_counts_shape, indices_dtype), # type: ignore
|
||||
Output: T.Tensor(o_shape, dtype), # type: ignore
|
||||
Lse: T.Tensor(lse_shape, accum_dtype), # type: ignore
|
||||
):
|
||||
@@ -231,12 +240,15 @@ def dsv4_sparse_attn_fwd(
|
||||
|
||||
T.copy(Q[b_i, s_i, H0:H1, :], Q_shared)
|
||||
|
||||
for i_i in T.Pipelined(NI, num_stages=num_stages):
|
||||
# `TileCounts` never exceeds `n_tiles`, but TileLang cannot know that; the `min` lets it
|
||||
# prove every `Indices` read in bounds rather than guarding each one, which costs the
|
||||
# backward 11-18%.
|
||||
for i_i in T.Pipelined(T.min(TileCounts[b_i, s_i, g_i], n_tiles), num_stages=num_stages):
|
||||
for bi_i in T.Parallel(BI):
|
||||
mask[bi_i] = Indices[b_i, s_i, g_i, i_i * BI + bi_i] >= 0
|
||||
mask[bi_i] = Indices[b_i, s_i, g_i, i_i, bi_i] >= 0
|
||||
|
||||
for bi_i, d_i in T.Parallel(BI, D):
|
||||
KV_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, d_i]
|
||||
KV_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i, bi_i], g_i, d_i]
|
||||
|
||||
for h_i, bi_i in T.Parallel(H_per_block, BI):
|
||||
acc_s[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_s.dtype))
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from prime_rl.multimodal import MaterializedMM, MultimodalAdapter
|
||||
from prime_rl.transports.batch import MMRefs
|
||||
|
||||
|
||||
def _load_image(data_url: str) -> Image.Image:
|
||||
header, separator, payload = data_url.partition(",")
|
||||
if not separator or not header.startswith("data:image/") or ";base64" not in header:
|
||||
raise ValueError("Multimodal training requires base64 data image URLs")
|
||||
with Image.open(BytesIO(base64.b64decode(payload, validate=True))) as image:
|
||||
return image.convert("RGB")
|
||||
|
||||
|
||||
def materialize_mm_refs(refs: MMRefs, processor: Any, adapter: MultimodalAdapter) -> MaterializedMM:
|
||||
image_processor = getattr(processor, "image_processor", None)
|
||||
if image_processor is None:
|
||||
raise ValueError("Multimodal samples require a model image processor")
|
||||
images = [_load_image(ref.url) for ref in refs.images]
|
||||
return adapter.materialize(image_processor, images, [ref.length for ref in refs.images])
|
||||
@@ -11,6 +11,7 @@ from prime_rl.trainer.world import get_world
|
||||
from prime_rl.transports.batch import (
|
||||
BatchReceiver,
|
||||
MicroBatch,
|
||||
MMRefs,
|
||||
TransportConfig,
|
||||
setup_batch_receiver,
|
||||
)
|
||||
@@ -46,12 +47,8 @@ class TensorMicroBatch(TypedDict):
|
||||
# maximum mask size. A row containing only -1 has no mask.
|
||||
sampling_mask: Int[Tensor, "batch seq mask"] | None
|
||||
|
||||
# Generic multimodal kwargs — flat dict matching the model's forward
|
||||
# signature (e.g. ``{"pixel_values": ..., "image_grid_thw": ...}`` for
|
||||
# Qwen3-VL; ``{"pixel_values": ...}`` for Gemma3-VL). The trainer
|
||||
# ``**`` -unpacks this into the forward call, so any HF VLM whose
|
||||
# processor and forward agree on kwarg names works out of the box.
|
||||
mm_kwargs: dict[str, Tensor] | None
|
||||
# Materialized immediately before this microbatch's forward pass.
|
||||
mm_refs: MMRefs | None
|
||||
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
|
||||
mm_token_type_ids: Int[Tensor, "batch seq"] | None
|
||||
|
||||
@@ -135,7 +132,7 @@ class FakeDataLoader:
|
||||
"seq_lens": torch.tensor(sequence_lengths, dtype=torch.long),
|
||||
"routed_experts": None,
|
||||
"sampling_mask": None,
|
||||
"mm_kwargs": None,
|
||||
"mm_refs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"rl_weights": None,
|
||||
"ce_weights": None,
|
||||
@@ -167,7 +164,7 @@ class FakeDataLoader:
|
||||
"seq_lens": torch.tensor([self.seq_len], dtype=torch.long),
|
||||
"routed_experts": None,
|
||||
"sampling_mask": None,
|
||||
"mm_kwargs": None,
|
||||
"mm_refs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"rl_weights": None,
|
||||
"ce_weights": None,
|
||||
@@ -201,15 +198,6 @@ class DataLoader:
|
||||
|
||||
def _micro_batch_to_tensor(self, micro_batch: MicroBatch) -> TensorMicroBatch:
|
||||
"""Convert a MicroBatch (msgspec struct with lists) to a TensorMicroBatch (dict with tensors)."""
|
||||
mm_kwargs: dict[str, Tensor] | None = None
|
||||
if micro_batch.mm_kwargs:
|
||||
# Each value is an EncodedTensor (dtype, shape, raw bytes).
|
||||
# No batch dim — the orchestrator concatenates per-image along
|
||||
# dim=0 generically, matching what each HF VLM's forward expects.
|
||||
mm_kwargs = {
|
||||
key: torch.frombuffer(bytearray(payload.data), dtype=_torch_dtype(payload.dtype)).reshape(payload.shape)
|
||||
for key, payload in micro_batch.mm_kwargs.items()
|
||||
}
|
||||
routed_experts = None
|
||||
packed_routed_experts = micro_batch.routed_experts
|
||||
if packed_routed_experts is not None:
|
||||
@@ -249,7 +237,7 @@ class DataLoader:
|
||||
# Single adapter: every token in the batch belongs to it (padding included).
|
||||
lora_num_tokens=torch.tensor([len(micro_batch.input_ids)], dtype=torch.int32),
|
||||
seq_lens=torch.tensor(micro_batch.seq_lens, dtype=torch.long),
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_refs=micro_batch.mm_refs,
|
||||
mm_token_type_ids=torch.tensor(micro_batch.mm_token_type_ids, dtype=torch.long).unsqueeze(0)
|
||||
if micro_batch.mm_token_type_ids is not None
|
||||
else None,
|
||||
|
||||
@@ -125,54 +125,64 @@ def shift_tensor_right(t: Float[Tensor, "batch seq"], pad_value: float | None =
|
||||
def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
|
||||
"""Mean of values over a boolean mask; returns 0 when mask is empty."""
|
||||
denom = torch.clamp_min(mask.sum(), 1)
|
||||
return values[mask].sum() / denom
|
||||
return (values[mask] / denom).sum()
|
||||
|
||||
|
||||
def compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs: Tensor, inference_logprobs: Tensor
|
||||
) -> tuple[Tensor, Tensor, Tensor]:
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
importance_ratio = torch.exp(log_importance_ratio)
|
||||
mismatch_kl = importance_ratio - log_importance_ratio - 1
|
||||
return log_importance_ratio, importance_ratio, mismatch_kl
|
||||
def _mismatch_kl_from_log_ratio(log_importance_ratio: Tensor) -> Tensor:
|
||||
# Keep headroom for FP32 reductions across tokens and ranks.
|
||||
metric_limit = log_importance_ratio.new_tensor(1e30)
|
||||
mismatch_kl = torch.expm1(log_importance_ratio.clamp(max=metric_limit.log())) - log_importance_ratio
|
||||
return mismatch_kl.clamp(max=metric_limit)
|
||||
|
||||
|
||||
def _capped_importance_ratio(log_importance_ratio: Tensor, max_ratio: float) -> Tensor:
|
||||
capped_log_ratio = log_importance_ratio.detach().clamp(max=log_importance_ratio.new_tensor(max_ratio).log())
|
||||
return torch.exp(capped_log_ratio + (log_importance_ratio - log_importance_ratio.detach()))
|
||||
|
||||
|
||||
class IPOLoss:
|
||||
"""IPO loss type: a symmetric trust region (mask tokens whose probability
|
||||
moved more than ``eps`` in absolute terms), policy gradient via
|
||||
the importance ratio, and a squared-log-ratio KL regularizer."""
|
||||
a capped importance ratio, and a squared-log-ratio KL regularizer."""
|
||||
|
||||
def __init__(self, config: IPOLossConfig):
|
||||
self.config = config
|
||||
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs:
|
||||
loss_config = self.config
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
|
||||
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
|
||||
trainer_logprobs = inputs.trainer_logprobs[inputs.loss_mask]
|
||||
inference_logprobs = inputs.inference_logprobs[inputs.loss_mask]
|
||||
advantages = inputs.advantages[inputs.loss_mask]
|
||||
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
|
||||
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
larger_logprob = torch.maximum(trainer_logprobs, inference_logprobs)
|
||||
smaller_logprob = torch.minimum(trainer_logprobs, inference_logprobs)
|
||||
# |e^logp - e^logq| = e^max(logp, logq) - e^min(logp, logq)
|
||||
# = e^max(logp, logq) * (1 - e^(min(logp, logq) - max(logp, logq)))
|
||||
# = e^max(logp, logq) * -expm1(min(logp, logq) - max(logp, logq)).
|
||||
# expm1 avoids cancellation in 1 - e^x when x is near zero.
|
||||
abs_probs_diff = torch.exp(larger_logprob) * -torch.expm1(smaller_logprob - larger_logprob)
|
||||
is_masked = abs_probs_diff > loss_config.eps
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
keep_mask = ~is_masked
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
loss = per_token_loss.sum()
|
||||
importance_ratio = _capped_importance_ratio(log_importance_ratio[keep_mask], loss_config.max_importance_ratio)
|
||||
pg_loss = -loss_config.adv_tau * advantages[keep_mask] * importance_ratio
|
||||
if weights is not None:
|
||||
pg_loss = pg_loss * weights[keep_mask]
|
||||
loss = pg_loss.sum()
|
||||
if loss_config.kl_tau:
|
||||
kl_loss = loss_config.kl_tau * log_importance_ratio.clamp(-1e4, 1e4).square()
|
||||
if weights is not None:
|
||||
kl_loss = kl_loss * weights
|
||||
loss = loss + kl_loss.sum()
|
||||
|
||||
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
|
||||
"is_masked": is_masked.sum() / max(is_masked.numel(), 1),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
@@ -187,28 +197,27 @@ class IcePopLoss:
|
||||
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs:
|
||||
loss_config = self.config
|
||||
log_importance_ratio, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
inputs.trainer_logprobs, inputs.inference_logprobs
|
||||
)
|
||||
log_importance_ratio = inputs.trainer_logprobs[inputs.loss_mask] - inputs.inference_logprobs[inputs.loss_mask]
|
||||
advantages = inputs.advantages[inputs.loss_mask]
|
||||
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
|
||||
|
||||
log_ratio_low = log_importance_ratio.new_tensor(loss_config.ratio_low).log()
|
||||
log_ratio_high = log_importance_ratio.new_tensor(loss_config.ratio_high).log()
|
||||
detached_log_ratio = log_importance_ratio.detach()
|
||||
is_masked = (detached_log_ratio < log_ratio_low) | (detached_log_ratio > log_ratio_high)
|
||||
keep_mask = inputs.loss_mask & ~is_masked
|
||||
keep_mask = ~is_masked
|
||||
|
||||
# Mask before exponentiation so rejected extreme ratios cannot produce
|
||||
# 0 * inf = NaN in the loss or its gradient.
|
||||
safe_log_ratio = torch.where(keep_mask, log_importance_ratio, torch.zeros_like(log_importance_ratio))
|
||||
importance_ratio = torch.exp(safe_log_ratio)
|
||||
per_token_loss = -(keep_mask * loss_config.adv_tau * inputs.advantages * importance_ratio)
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
importance_ratio = torch.exp(log_importance_ratio[keep_mask])
|
||||
per_token_loss = -loss_config.adv_tau * advantages[keep_mask] * importance_ratio
|
||||
if weights is not None:
|
||||
per_token_loss = per_token_loss * weights[keep_mask]
|
||||
|
||||
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, inputs.loss_mask & is_masked),
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
|
||||
"is_masked": _safe_mean(is_masked, inputs.loss_mask),
|
||||
"is_masked": is_masked.sum() / max(is_masked.numel(), 1),
|
||||
}
|
||||
return LossOutputs(loss=per_token_loss.sum(), metrics=metrics)
|
||||
|
||||
@@ -222,39 +231,37 @@ def ref_kl_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
inference probability; a squared-log-ratio term regularizes drift. Scalar
|
||||
advantages are not read — ref_kl algorithms ship none.
|
||||
"""
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
ref_logprobs = inputs.ref_logprobs
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
if ref_logprobs is None:
|
||||
if inputs.ref_logprobs is None:
|
||||
raise ValueError("ref_kl loss type requires ref_logprobs — use the 'opd' or 'opsd' algorithm.")
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
trainer_logprobs = inputs.trainer_logprobs[inputs.loss_mask]
|
||||
inference_logprobs = inputs.inference_logprobs[inputs.loss_mask]
|
||||
ref_logprobs = inputs.ref_logprobs[inputs.loss_mask]
|
||||
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
|
||||
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
|
||||
is_masked = probs_diff < -0.2
|
||||
drop_mask = loss_mask & is_masked
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
keep_mask = ~is_masked
|
||||
|
||||
ref_kl = ref_logprobs - trainer_logprobs
|
||||
|
||||
pg_loss = keep_mask * ref_kl.detach() * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
per_token_loss = -pg_loss + 1e-3 * kl_loss
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
loss = per_token_loss.sum()
|
||||
importance_ratio = _capped_importance_ratio(log_importance_ratio[keep_mask], 1e4)
|
||||
pg_loss = -ref_kl[keep_mask].detach() * importance_ratio
|
||||
kl_loss = 1e-3 * log_importance_ratio.clamp(-1e4, 1e4).square()
|
||||
if weights is not None:
|
||||
pg_loss = pg_loss * weights[keep_mask]
|
||||
kl_loss = kl_loss * weights
|
||||
loss = pg_loss.sum() + kl_loss.sum()
|
||||
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
|
||||
|
||||
# Namespaced: the rl loss fn emits same-named trust-region metrics with a
|
||||
# different definition, and mixed batches run both fns in one step.
|
||||
metrics = {
|
||||
"ref_kl/masked_mismatch_kl": _safe_mean(mismatch_kl, drop_mask),
|
||||
"ref_kl/masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
|
||||
"ref_kl/unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
|
||||
"ref_kl/is_masked": _safe_mean(is_masked, loss_mask),
|
||||
"ref_kl": _safe_mean(ref_kl, loss_mask),
|
||||
"ref_kl/is_masked": is_masked.sum() / max(is_masked.numel(), 1),
|
||||
"ref_kl": ref_kl.sum() / max(ref_kl.numel(), 1),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
@@ -29,20 +29,23 @@ from prime_rl.utils.logger import format_time, setup_logger
|
||||
from prime_rl.trainer.rl.loss import (
|
||||
compute_entropy,
|
||||
compute_loss,
|
||||
compute_importance_ratio_and_mismatch_kl,
|
||||
_mismatch_kl_from_log_ratio,
|
||||
selective_log_softmax,
|
||||
selective_log_softmax_with_sampling_mask,
|
||||
setup_rl_loss_fn,
|
||||
shift_tensor_left,
|
||||
shift_tensor_right,
|
||||
)
|
||||
from prime_rl.multimodal import get_multimodal_adapter
|
||||
from prime_rl.trainer.multimodal import materialize_mm_refs
|
||||
from prime_rl.trainer.rl.annotations import AnnotationWriter
|
||||
from prime_rl.trainer.model import (
|
||||
forward,
|
||||
get_full_offload_dtype_policy,
|
||||
setup_model,
|
||||
get_global_moe_stats,
|
||||
is_tt_moe_model,
|
||||
get_load_balance_stats,
|
||||
setup_model,
|
||||
setup_processor,
|
||||
)
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
|
||||
from prime_rl.trainer.perf import get_perf_counter
|
||||
@@ -142,13 +145,21 @@ def train(config: TrainerConfig):
|
||||
if checkpoint_step is None:
|
||||
checkpoint_step = resolve_latest_ckpt_step(ckpt_manager.ckpt_dir)
|
||||
|
||||
# Initialize the model and tokenizer
|
||||
# Initialize the model
|
||||
logger.info(f"Initializing model ({config.model})")
|
||||
t0 = time.perf_counter()
|
||||
loading_from_ckpt_later = checkpoint_step is not None
|
||||
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
|
||||
logger.debug(f"Initialized model in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
processor = None
|
||||
mm_adapter = None
|
||||
if config.model.vlm is not None:
|
||||
processor = setup_processor(config.model)
|
||||
if processor is None:
|
||||
raise ValueError("Multimodal training requires a model image processor")
|
||||
mm_adapter = get_multimodal_adapter(model.config.model_type)
|
||||
|
||||
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
|
||||
raise ValueError("Packed multimodal training requires model support")
|
||||
|
||||
@@ -193,6 +204,9 @@ def train(config: TrainerConfig):
|
||||
if parallel_dims.cp_enabled:
|
||||
setup_context_parallel(model, config.model, parallel_dims)
|
||||
|
||||
is_moe_model = is_tt_moe_model(model)
|
||||
ep_group = parallel_dims.get_mesh("ep").get_group() if parallel_dims.ep_enabled else None
|
||||
|
||||
# Fresh adapter init after FSDP materialization (the pretrained checkpoint
|
||||
# carries no adapter weights); a checkpoint resume below overwrites it.
|
||||
if config.model.lora is not None:
|
||||
@@ -359,17 +373,17 @@ def train(config: TrainerConfig):
|
||||
micro_batch["sampling_mask"].to("cuda") if micro_batch["sampling_mask"] is not None else None
|
||||
)
|
||||
|
||||
# Multimodal kwargs are an opaque per-model dict (e.g.
|
||||
# {"pixel_values": ..., "image_grid_thw": ...} for Qwen3-VL,
|
||||
# just {"pixel_values": ...} for Gemma3-VL) — we move every
|
||||
# tensor to CUDA and let the model's forward sort them.
|
||||
mm_kwargs_raw = micro_batch.get("mm_kwargs")
|
||||
mm_kwargs = {k: v.to("cuda") for k, v in mm_kwargs_raw.items()} if mm_kwargs_raw else None
|
||||
if mm_kwargs is not None and config.model.vlm is None:
|
||||
raise ValueError(
|
||||
"Received multimodal samples but [model.vlm] is not set. "
|
||||
"Set [model.vlm] to train on multimodal samples."
|
||||
)
|
||||
mm_kwargs = None
|
||||
mm_forward_policy = None
|
||||
mm_refs = micro_batch.get("mm_refs")
|
||||
if mm_refs is not None:
|
||||
if processor is None or mm_adapter is None:
|
||||
raise ValueError("Received multimodal samples but [model.vlm] is not set")
|
||||
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
|
||||
mm_kwargs = {key: value.to("cuda") for key, value in materialized.kwargs.items()}
|
||||
mm_forward_policy = materialized.forward_policy
|
||||
micro_batch["mm_refs"] = None
|
||||
del materialized, mm_refs
|
||||
mm_token_type_ids = (
|
||||
micro_batch["mm_token_type_ids"].to("cuda")
|
||||
if micro_batch.get("mm_token_type_ids") is not None
|
||||
@@ -387,8 +401,9 @@ def train(config: TrainerConfig):
|
||||
seq_lens_are_pre_shard = False
|
||||
|
||||
if cp_enabled:
|
||||
# MRoPE batches must merge image embeddings before sharding.
|
||||
defer_vlm_cp_to_model = mm_kwargs is not None and "image_grid_thw" in mm_kwargs
|
||||
defer_vlm_cp_to_model = bool(
|
||||
mm_forward_policy is not None and mm_forward_policy.defer_context_parallelism
|
||||
)
|
||||
if not defer_vlm_cp_to_model:
|
||||
input_ids, position_ids = setup_cp_params(
|
||||
input_ids,
|
||||
@@ -441,6 +456,7 @@ def train(config: TrainerConfig):
|
||||
labels=labels,
|
||||
temperature=temperatures,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_forward_policy=mm_forward_policy,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
@@ -497,6 +513,8 @@ def train(config: TrainerConfig):
|
||||
loss.backward()
|
||||
finish_backward(gradient_manager)
|
||||
|
||||
mm_kwargs = None
|
||||
|
||||
# Add relevant tensors to tensor dict for logging purposes
|
||||
entropy = out["entropy"][loss_mask].detach().to("cpu")
|
||||
tensors["entropy/all"].append(entropy)
|
||||
@@ -525,8 +543,9 @@ def train(config: TrainerConfig):
|
||||
has_mismatch_tokens = bool(mismatch_mask.any())
|
||||
if has_mismatch_tokens:
|
||||
with torch.no_grad():
|
||||
_, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(out["logprobs"], inference_logprobs)
|
||||
mismatch_kl = mismatch_kl[mismatch_mask].detach().to("cpu")
|
||||
log_ratio = out["logprobs"][mismatch_mask] - inference_logprobs[mismatch_mask]
|
||||
mismatch_kl = _mismatch_kl_from_log_ratio(log_ratio)
|
||||
mismatch_kl = mismatch_kl.detach().to("cpu")
|
||||
tensors["mismatch_kl/all"].append(mismatch_kl)
|
||||
mismatch_env_names = [
|
||||
env_name for env_name, keep in zip(env_names, mismatch_mask.flatten().tolist()) if keep
|
||||
@@ -539,11 +558,9 @@ def train(config: TrainerConfig):
|
||||
|
||||
annotation_writer.export(micro_batch, out)
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
load_balance_stats = get_load_balance_stats(model)
|
||||
for k, v in load_balance_stats.items():
|
||||
if v is not None:
|
||||
tensors[k].append(v)
|
||||
if is_moe_model:
|
||||
for name, value in get_global_moe_stats(model, ep_group, dp_cp_group).items():
|
||||
tensors[name].append(value.reshape(1))
|
||||
|
||||
# Add loss tensors to tensor dict for logging purposes
|
||||
for key, loss_tensor in loss_tensors.items():
|
||||
@@ -553,10 +570,6 @@ def train(config: TrainerConfig):
|
||||
micro_step_message = f"Micro Step {micro_step + 1}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
|
||||
if has_mismatch_tokens:
|
||||
micro_step_message += f" | Mismatch KL {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
|
||||
if "max_vio" in tensors:
|
||||
micro_step_message += f" | Max Vio {tensors['max_vio'][-1].mean().item():.4f}"
|
||||
if "routing_confidence" in tensors:
|
||||
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
|
||||
logger.debug(micro_step_message)
|
||||
|
||||
annotation_writer.flush()
|
||||
|
||||
@@ -28,6 +28,7 @@ from prime_rl.trainer.scheduler import setup_scheduler
|
||||
from prime_rl.trainer.model import (
|
||||
forward,
|
||||
get_full_offload_dtype_policy,
|
||||
get_global_moe_stats,
|
||||
get_load_balance_stats,
|
||||
is_tt_moe_model,
|
||||
setup_processor,
|
||||
@@ -234,6 +235,7 @@ def train(config: SFTConfig):
|
||||
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank() if cp_enabled else 0
|
||||
cp_group = parallel_dims.world_mesh["cp"].get_group() if cp_enabled else None
|
||||
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
|
||||
ep_group = parallel_dims.get_mesh("ep").get_group() if parallel_dims.ep_enabled else None
|
||||
cp_size = parallel_dims.cp
|
||||
|
||||
def compute_loss(micro_batch: dict) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
@@ -364,6 +366,9 @@ def train(config: SFTConfig):
|
||||
|
||||
# No train/eval switch: no dropout in these models, and toggling would trigger torch.compile recompilation
|
||||
mean_loss, nan_count = run_eval_loop(val_dataloader)
|
||||
if is_tt_moe_model(model):
|
||||
# Keep validation routing out of the next training step's statistics.
|
||||
get_load_balance_stats(model)
|
||||
if nan_count > 0:
|
||||
logger.warning(f"Validation at step {step}: {nan_count} batches had NaN loss")
|
||||
if mean_loss != mean_loss:
|
||||
@@ -431,8 +436,9 @@ def train(config: SFTConfig):
|
||||
is_moe_model = is_tt_moe_model(model)
|
||||
moe_stats = (
|
||||
{
|
||||
"max_vio": torch.tensor(0.0, device="cuda"),
|
||||
"routing_confidence": torch.tensor(0.0, device="cuda"),
|
||||
"max_vio/mean": torch.tensor(0.0),
|
||||
"max_vio/max": torch.tensor(0.0),
|
||||
"routing_confidence/mean": torch.tensor(0.0),
|
||||
}
|
||||
if is_moe_model
|
||||
else {}
|
||||
@@ -487,15 +493,10 @@ def train(config: SFTConfig):
|
||||
finish_backward(gradient_manager)
|
||||
|
||||
if is_moe_model:
|
||||
for name, values in get_load_balance_stats(model).items():
|
||||
if values is None:
|
||||
continue
|
||||
value = values.mean()
|
||||
reduce_op = dist.ReduceOp.MAX if name == "max_vio" else dist.ReduceOp.SUM
|
||||
dist.all_reduce(value, op=reduce_op)
|
||||
if reduce_op == dist.ReduceOp.SUM:
|
||||
value /= dist.get_world_size()
|
||||
moe_stats[name] += value / grad_accum_steps
|
||||
for name, value in get_global_moe_stats(model, ep_group, dp_cp_group).items():
|
||||
moe_stats[f"{name}/mean"] += value / grad_accum_steps
|
||||
if name == "max_vio":
|
||||
moe_stats["max_vio/max"] = torch.maximum(moe_stats["max_vio/max"], value)
|
||||
|
||||
forward_backward_time = time.perf_counter() - forward_backward_start_time
|
||||
|
||||
@@ -582,7 +583,7 @@ def train(config: SFTConfig):
|
||||
step_message += f" | Grad. Norm {grad_norm:.4f}"
|
||||
step_message += f" | LR {current_lr:.2e} | Throughput {throughput:.0f} tokens/s | MFU {mfu:.1f}% | Peak Mem. {peak_memory:.1f}/{max_memory:.1f} GiB ({peak_memory / max_memory * 100:.1f}%)"
|
||||
if is_moe_model:
|
||||
for name, label in (("max_vio", "Max Vio"), ("routing_confidence", "Routing Conf.")):
|
||||
for name, label in (("max_vio/mean", "Max Vio"), ("routing_confidence/mean", "Routing Conf.")):
|
||||
value = moe_stats[name].item()
|
||||
if value > 0:
|
||||
step_message += f" | {label} {value:.4f}"
|
||||
@@ -656,7 +657,7 @@ def train(config: SFTConfig):
|
||||
disk_metrics["step"] = progress.step
|
||||
asyncio.run(monitors.log(disk_metrics, step=progress.step))
|
||||
|
||||
moe_log_metrics = {f"{name}/mean": value.item() for name, value in moe_stats.items() if value.item() > 0}
|
||||
moe_log_metrics = {name: value.item() for name, value in moe_stats.items()}
|
||||
if moe_log_metrics:
|
||||
asyncio.run(monitors.log({**moe_log_metrics, "step": progress.step}, step=progress.step))
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ from prime_rl.transports.batch.filesystem import (
|
||||
)
|
||||
from prime_rl.transports.batch.types import (
|
||||
MicroBatch,
|
||||
MMImageRef,
|
||||
MMRefs,
|
||||
RoutedExperts,
|
||||
SamplingMask,
|
||||
TrainingSample,
|
||||
@@ -47,6 +49,8 @@ __all__ = [
|
||||
"ZMQBatchReceiver",
|
||||
"BatchReceiver",
|
||||
"BatchSender",
|
||||
"MMImageRef",
|
||||
"MMRefs",
|
||||
"TrainingSample",
|
||||
"MicroBatch",
|
||||
"SamplingMask",
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import msgspec
|
||||
|
||||
|
||||
# Encoded tensor: {dtype: "float32", shape: [...], data: <bytes>}.
|
||||
# Mirrors verifiers' env-serve msgpack encoder so the same wire shape is
|
||||
# used end-to-end from renderer → orchestrator → trainer.
|
||||
class EncodedTensor(msgspec.Struct, array_like=True, gc=False):
|
||||
dtype: str
|
||||
shape: list[int]
|
||||
data: bytes
|
||||
class MMImageRef(msgspec.Struct, array_like=True, gc=False):
|
||||
url: str
|
||||
offset: int
|
||||
length: int
|
||||
|
||||
|
||||
class MMRefs(msgspec.Struct, array_like=True, gc=False):
|
||||
images: list[MMImageRef]
|
||||
|
||||
|
||||
# Routed experts are large per-token arrays. tolist() is too expensive, so we
|
||||
@@ -42,15 +43,7 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
|
||||
env_name: str
|
||||
ref_logprobs: list[float] | None = None # reference-model logprobs (ref_kl component)
|
||||
|
||||
# Generic multimodal kwargs: flat dict keyed by the kwarg names the
|
||||
# model's forward expects (e.g. {"pixel_values": ..., "image_grid_thw":
|
||||
# ...} for Qwen3-VL; just {"pixel_values": ...} for Gemma3). The
|
||||
# orchestrator batches per-image renderer items by torch.cat along
|
||||
# dim=0 generically — no model-specific knowledge in prime-rl. The
|
||||
# trainer ``**`` -unpacks this into the model forward, so any VLM
|
||||
# whose HF processor / forward agree on kwarg names works without
|
||||
# touching this transport.
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mm_refs: MMRefs | None = None
|
||||
|
||||
routed_experts: RoutedExperts | None = None
|
||||
|
||||
@@ -103,8 +96,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
ref_logprobs: list[float] | None = None
|
||||
routed_experts: RoutedExperts | None = None
|
||||
|
||||
# See TrainingSample.mm_kwargs.
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mm_refs: MMRefs | None = None
|
||||
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
|
||||
|
||||
@@ -52,6 +52,22 @@ def test_expand_shorthands_refuses_shorthand_next_to_source_toml(tmp_path) -> No
|
||||
toml.write_text('[[source]]\nenv.taskset.id = "gsm8k"\n')
|
||||
with pytest.raises(SystemExit, match="cannot be combined"):
|
||||
expand_shorthands(["wordle", "@", toml.as_posix()])
|
||||
with pytest.raises(SystemExit, match="cannot be combined"):
|
||||
expand_shorthands(["wordle", "@", toml.as_posix(), "--env.retries.max-retries", "3"])
|
||||
|
||||
|
||||
def test_expand_shorthands_passes_env_flags_to_the_shared_block_next_to_source_toml(tmp_path) -> None:
|
||||
toml = tmp_path / "eval.toml"
|
||||
toml.write_text('[[source]]\nenv.taskset.id = "gsm8k"\n')
|
||||
argv = ["@", toml.as_posix(), "--env.retries.max-retries", "3", "--env.timeout.episode=60"]
|
||||
assert expand_shorthands(argv) == [
|
||||
"@",
|
||||
toml.as_posix(),
|
||||
"--env.retries.max-retries",
|
||||
"3",
|
||||
"--env.timeout.episode",
|
||||
"60",
|
||||
]
|
||||
|
||||
|
||||
def test_expand_shorthands_requires_a_value() -> None:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import orjson
|
||||
import pytest
|
||||
|
||||
from prime_rl.eval import resume
|
||||
from prime_rl.monitors.file.traces import get_trace_stream
|
||||
@@ -64,28 +63,6 @@ def test_trigger_queues_only_owed_rollouts() -> None:
|
||||
]
|
||||
|
||||
|
||||
def test_check_config_allows_selection_changes_only() -> None:
|
||||
previous = {
|
||||
"model": "a",
|
||||
"num_examples": 8,
|
||||
"group_size": 2,
|
||||
"sampling": {"temperature": 1.0},
|
||||
"source": [{"env": {"taskset": {"id": "gsm8k"}}, "group_size": None, "serve": {"address": None}}],
|
||||
}
|
||||
resized = {
|
||||
**previous,
|
||||
"num_examples": 16,
|
||||
"group_size": 4,
|
||||
"source": [{"env": {"taskset": {"id": "gsm8k"}}, "group_size": 8, "serve": {"address": "tcp://x"}}],
|
||||
}
|
||||
resume.check_config(previous, resized)
|
||||
|
||||
with pytest.raises(ValueError, match="model, sampling.temperature"):
|
||||
resume.check_config(previous, {**previous, "model": "b", "sampling": {"temperature": 0.5}})
|
||||
with pytest.raises(ValueError, match="source"):
|
||||
resume.check_config(previous, {**previous, "source": previous["source"] * 2})
|
||||
|
||||
|
||||
def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
|
||||
def land(*keys: str) -> None:
|
||||
stream = ChunkedJsonl(get_trace_stream(tmp_path), max_bytes=1 << 20, compress=False)
|
||||
@@ -102,11 +79,3 @@ def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
|
||||
land("m0", "m2")
|
||||
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1", "m2"]
|
||||
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1", "file.attempt_2"]
|
||||
|
||||
|
||||
def test_previous_config_is_the_one_stamped_beside_the_results(tmp_path) -> None:
|
||||
resume.stamp_config(tmp_path, {"model": "a"})
|
||||
resume.take_landed(tmp_path) # the attempt that ran is archived; a rejected one never stamps
|
||||
assert resume.previous_config(tmp_path) == {"model": "a"}
|
||||
resume.stamp_config(tmp_path, {"model": "b"})
|
||||
assert resume.previous_config(tmp_path) == {"model": "b"}
|
||||
|
||||
@@ -14,12 +14,17 @@ from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pybase64
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.protocol import GenerateResponse, GenerateResponseChoice
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateResponse,
|
||||
GenerateResponseChoice,
|
||||
)
|
||||
from vllm.entrypoints.serve.engine.protocol import UsageInfo
|
||||
from vllm.multimodal.inputs import PlaceholderRange
|
||||
|
||||
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
|
||||
from prime_rl.inference.vllm.serving_tokens import (
|
||||
PrimeRlServingTokens,
|
||||
_extract_mm_placeholders,
|
||||
_GenerateRoutedExpertsCapture,
|
||||
)
|
||||
|
||||
@@ -58,7 +63,7 @@ def test_serialize_routed_experts_uses_compact_raw_payload():
|
||||
np.testing.assert_array_equal(decoded, routed_experts)
|
||||
|
||||
|
||||
def test_generate_response_post_process_replaces_upstream_routed_experts():
|
||||
def test_generate_response_post_process_preserves_prompt_metadata():
|
||||
compact_routed_experts = {"data": "AQID", "shape": [1, 1, 3], "start": 0}
|
||||
capture = _GenerateRoutedExpertsCapture(_empty_request_outputs())
|
||||
capture.routed_experts[0] = compact_routed_experts
|
||||
@@ -77,12 +82,19 @@ def test_generate_response_post_process_replaces_upstream_routed_experts():
|
||||
)
|
||||
|
||||
processed = capture.post_process(response)
|
||||
processed.prompt_token_ids = [10, 11, 12, 13]
|
||||
processed.mm_placeholders = _extract_mm_placeholders(
|
||||
{
|
||||
"type": "multimodal",
|
||||
"mm_placeholders": {"image": [PlaceholderRange(offset=1, length=2)]},
|
||||
}
|
||||
)
|
||||
|
||||
assert processed.choices[0].routed_experts == compact_routed_experts
|
||||
assert processed.model == "test-model"
|
||||
assert processed.usage == usage
|
||||
# The compact object form must survive JSON serialization (the parent
|
||||
# declares ``routed_experts`` as a base64 string).
|
||||
payload = processed.model_dump(mode="json")
|
||||
assert payload["choices"][0]["routed_experts"] == compact_routed_experts
|
||||
assert payload["prompt_token_ids"] == [10, 11, 12, 13]
|
||||
assert payload["mm_placeholders"] == {"image": [{"offset": 1, "length": 2}]}
|
||||
assert payload["usage"]["total_tokens"] == 7
|
||||
|
||||
@@ -4,7 +4,7 @@ import numpy as np
|
||||
import pytest
|
||||
|
||||
from prime_rl.trainer.batch import _is_multimodal_sample, build_bin_cost, pad_micro_batch, prepare_batch, prepare_sample
|
||||
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
|
||||
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, TrainingSample
|
||||
|
||||
|
||||
def _routed_experts(data, dtype=np.uint8):
|
||||
@@ -16,11 +16,6 @@ def _routed_experts(data, dtype=np.uint8):
|
||||
)
|
||||
|
||||
|
||||
def _encoded(arr) -> EncodedTensor:
|
||||
a = np.asarray(arr)
|
||||
return EncodedTensor(data=a.tobytes(), shape=list(a.shape), dtype=str(a.dtype))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_training_example():
|
||||
def _make_training_example(
|
||||
@@ -435,12 +430,8 @@ def test_prepare_sample_truncates_routed_experts():
|
||||
|
||||
|
||||
def test_prepare_sample_truncates_mm_at_image_boundary():
|
||||
"""Truncation never splits an image's placeholder block: it cuts to a whole-image boundary
|
||||
and slices mm_kwargs to match, so image-token count stays == image-embedding count."""
|
||||
# Two 2-token images (patches-per-token = 1): image-pad at indices 1,2 (img0) and 4,5 (img1).
|
||||
"""Truncation never splits an image's expanded placeholder block."""
|
||||
mm_token_type_ids = [0, 1, 1, 0, 1, 1, 0]
|
||||
pixel_values = np.array([[1.0], [1.0], [2.0], [2.0]], dtype=np.float32) # img0=1.0, img1=2.0
|
||||
grid = np.array([[1, 2, 1], [1, 2, 1]], dtype=np.int64)
|
||||
sample = TrainingSample(
|
||||
token_ids=[10, 11, 12, 13, 14, 15, 16],
|
||||
mask=[False, False, False, False, False, True, True],
|
||||
@@ -449,7 +440,12 @@ def test_prepare_sample_truncates_mm_at_image_boundary():
|
||||
advantages=[0.0] * 6 + [1.0],
|
||||
env_name="test-env",
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
mm_kwargs={"pixel_values": _encoded(pixel_values), "image_grid_thw": _encoded(grid)},
|
||||
mm_refs=MMRefs(
|
||||
images=[
|
||||
MMImageRef(url="data:image/png;base64,first", offset=1, length=2),
|
||||
MMImageRef(url="data:image/png;base64,second", offset=4, length=2),
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
# seq_len=5 falls inside img1 (one of its two placeholders survives) -> drop img1 entirely.
|
||||
@@ -458,12 +454,8 @@ def test_prepare_sample_truncates_mm_at_image_boundary():
|
||||
assert len(mb.mm_token_type_ids) == len(mb.input_ids)
|
||||
n_placeholders = sum(1 for t in mb.mm_token_type_ids if t)
|
||||
assert n_placeholders == 2 # only img0's two placeholders remain
|
||||
# No mismatch: placeholders == image embeddings, and only img0's pixels are kept.
|
||||
assert mb.mm_kwargs["pixel_values"].shape == [2, 1]
|
||||
assert mb.mm_kwargs["image_grid_thw"].shape == [1, 3]
|
||||
kept = np.frombuffer(bytearray(mb.mm_kwargs["pixel_values"].data), dtype=np.float32)
|
||||
assert kept.tolist() == [1.0, 1.0]
|
||||
assert n_placeholders == mb.mm_kwargs["pixel_values"].shape[0] # ppt == 1 here
|
||||
assert mb.mm_refs is not None
|
||||
assert [(ref.url, ref.offset, ref.length) for ref in mb.mm_refs.images] == [("data:image/png;base64,first", 1, 2)]
|
||||
|
||||
|
||||
def test_prepare_batch_packs_multimodal_with_text():
|
||||
@@ -475,10 +467,7 @@ def test_prepare_batch_packs_multimodal_with_text():
|
||||
advantages=[0.0, 1.0, 1.0],
|
||||
env_name="mm-env",
|
||||
mm_token_type_ids=[0, 1, 0],
|
||||
mm_kwargs={
|
||||
"pixel_values": _encoded(np.array([[1.0, 2.0]], dtype=np.float32)),
|
||||
"image_grid_thw": _encoded(np.array([[1, 2, 2]], dtype=np.int64)),
|
||||
},
|
||||
mm_refs=MMRefs(images=[MMImageRef(url="data:image/png;base64,image", offset=1, length=1)]),
|
||||
)
|
||||
text_sample = TrainingSample(
|
||||
token_ids=[20, 21],
|
||||
@@ -492,14 +481,10 @@ def test_prepare_batch_packs_multimodal_with_text():
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=[mm_sample, text_sample],
|
||||
seq_len=8,
|
||||
num_train_workers=2,
|
||||
num_train_workers=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
# FSDP requires uniform modality at each step index across ranks
|
||||
for step_mbs in zip(*batches_per_gpu):
|
||||
assert len({_is_multimodal_sample(mb) for mb in step_mbs}) == 1
|
||||
|
||||
real_batches = [batch for batch in _flatten_batches(batches_per_gpu) if _has_loss_tokens(batch)]
|
||||
assert len(real_batches) == 1
|
||||
batch = real_batches[0]
|
||||
@@ -507,12 +492,36 @@ def test_prepare_batch_packs_multimodal_with_text():
|
||||
assert batch.sequence_lengths == [3, 2]
|
||||
assert batch.position_ids == [0, 1, 2, 0, 1]
|
||||
assert batch.mm_token_type_ids == [0, 1, 0, 0, 0]
|
||||
assert batch.mm_kwargs is not None
|
||||
assert batch.mm_kwargs["pixel_values"].shape == [1, 2]
|
||||
assert batch.mm_kwargs["image_grid_thw"].shape == [1, 3]
|
||||
assert batch.mm_refs is not None
|
||||
assert [(ref.offset, ref.length) for ref in batch.mm_refs.images] == [(1, 1)]
|
||||
assert batch.env_names == ["mm-env"] * 3 + ["text-env"] * 2
|
||||
|
||||
|
||||
def test_split_to_align_splits_multimodal_bins():
|
||||
def make_mm_sample(token: int) -> TrainingSample:
|
||||
return TrainingSample(
|
||||
token_ids=[token, token + 1, token + 2],
|
||||
mask=[False, True, True],
|
||||
logprobs=[0.0, -0.1, -0.2],
|
||||
temperatures=[1.0, 1.0, 1.0],
|
||||
advantages=[0.0, 1.0, 1.0],
|
||||
env_name=f"mm-{token}",
|
||||
mm_token_type_ids=[0, 1, 0],
|
||||
mm_refs=MMRefs(images=[MMImageRef(url=f"data:image/png;base64,{token}", offset=1, length=1)]),
|
||||
)
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=[make_mm_sample(10), make_mm_sample(20)],
|
||||
seq_len=8,
|
||||
num_train_workers=2,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
batches = _flatten_batches(batches_per_gpu)
|
||||
assert len(batches) == 2
|
||||
assert all(_has_loss_tokens(batch) and _is_multimodal_sample(batch) for batch in batches)
|
||||
|
||||
|
||||
def test_prepare_sample_none_routed_experts():
|
||||
"""When routed_experts is None, micro_batch.routed_experts is None."""
|
||||
sample = TrainingSample(
|
||||
|
||||
@@ -22,6 +22,7 @@ def mk(
|
||||
num_turns: int = 1,
|
||||
num_branches: int = 1,
|
||||
is_truncated: bool = False,
|
||||
is_timeout: bool = False,
|
||||
is_completed: bool = True,
|
||||
has_error: bool = False,
|
||||
error_type: str = "error",
|
||||
@@ -51,6 +52,7 @@ def mk(
|
||||
num_turns=num_turns,
|
||||
num_branches=num_branches,
|
||||
is_truncated=is_truncated,
|
||||
is_timeout=is_timeout,
|
||||
is_completed=is_completed,
|
||||
has_error=has_error,
|
||||
last_error=SimpleNamespace(type=error_type) if has_error else None,
|
||||
|
||||
@@ -1,20 +1,11 @@
|
||||
"""End-to-end integration test for the Qwen3-VL renderer path.
|
||||
|
||||
Walks a multimodal request through ``renderers.client.generate`` — the
|
||||
tokenize + /inference/v1/generate features payload path the v1 train
|
||||
client drives — with the HTTP layer mocked, and verifies that vLLM can
|
||||
deserialize the features back into engine inputs identical to what its
|
||||
own server-side processor would have produced for the same messages.
|
||||
|
||||
This is the strongest end-to-end check we can run without a GPU. The
|
||||
remaining missing piece (vLLM actually consuming the engine input,
|
||||
sampling tokens, and returning them) is exercised in real rollouts.
|
||||
"""
|
||||
"""End-to-end request-shape check for raw Qwen3-VL inference."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -47,25 +38,31 @@ class _FakeOpenAI:
|
||||
generate response so the parse-side of the flow runs.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, image_pad_id: int):
|
||||
self.calls: list[dict[str, Any]] = []
|
||||
self.base_url = "http://fake-host:8000/v1"
|
||||
self.image_pad_id = image_pad_id
|
||||
|
||||
async def post(self, path, *, cast_to=dict, body=None, options=None):
|
||||
self.calls.append({"path": path, "body": body, "options": options})
|
||||
# Reply with two sampled tokens + <|im_end|>. The renderer's
|
||||
# parse_response slices the content tokens.
|
||||
prompt_ids = list(body["token_ids"])
|
||||
pad_index = prompt_ids.index(self.image_pad_id)
|
||||
prompt_ids[pad_index : pad_index + 1] = [self.image_pad_id] * 4
|
||||
payload = {
|
||||
"request_id": "qwen-vl-e2e",
|
||||
"prompt_token_ids": prompt_ids,
|
||||
"mm_placeholders": {"image": [{"offset": pad_index, "length": 4}]},
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"token_ids": [50, 60, 151645],
|
||||
"logprobs": {
|
||||
"content": [
|
||||
{"token": "t1", "logprob": -0.1},
|
||||
{"token": "t2", "logprob": -0.2},
|
||||
{"token": "t3", "logprob": -0.3},
|
||||
{"token": "token_id:50", "logprob": -0.1},
|
||||
{"token": "token_id:60", "logprob": -0.2},
|
||||
{"token": "token_id:151645", "logprob": -0.3},
|
||||
]
|
||||
},
|
||||
"finish_reason": "stop",
|
||||
@@ -75,43 +72,30 @@ class _FakeOpenAI:
|
||||
return httpx.Response(200, content=json.dumps(payload).encode())
|
||||
|
||||
|
||||
def test_generate_qwen3_vl_e2e_features_payload_roundtrips_through_vllm():
|
||||
"""Walk a Qwen3-VL multimodal turn through ``renderers.client.generate``
|
||||
and verify the resulting ``/inference/v1/generate`` body has a valid
|
||||
``features`` payload that:
|
||||
|
||||
1. parses through vLLM's ``GenerateRequest`` pydantic model,
|
||||
2. decodes back to ``MultiModalKwargsItem`` instances carrying
|
||||
``pixel_values`` + ``image_grid_thw`` of the right shapes,
|
||||
3. has placeholder ranges that exactly cover the ``<|image_pad|>``
|
||||
runs in the prompt token sequence.
|
||||
"""
|
||||
def test_generate_qwen3_vl_sends_raw_content_and_uses_expanded_prompt_ids():
|
||||
from PIL import Image
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.client import generate
|
||||
from renderers.qwen3_vl import Qwen3VLRenderer
|
||||
from transformers import AutoProcessor
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.protocol import GenerateRequest
|
||||
|
||||
# ── Build a real Qwen3VLRenderer with a real processor. ─────────────
|
||||
tokenizer = load_tokenizer(_MODEL)
|
||||
processor = AutoProcessor.from_pretrained(_MODEL)
|
||||
renderer = Qwen3VLRenderer(tokenizer, processor=processor)
|
||||
renderer = Qwen3VLRenderer(tokenizer)
|
||||
|
||||
image_pad_id = tokenizer.convert_tokens_to_ids("<|image_pad|>")
|
||||
|
||||
fake = _FakeOpenAI()
|
||||
fake = _FakeOpenAI(image_pad_id)
|
||||
|
||||
# ── Build a user message with an image (OpenAI content-part shape). ─
|
||||
img = Image.new("RGB", (224, 224), color=(64, 128, 255))
|
||||
buffer = BytesIO()
|
||||
img.save(buffer, format="PNG")
|
||||
image_url = f"data:image/png;base64,{base64.b64encode(buffer.getvalue()).decode()}"
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "What's in this picture?"},
|
||||
# Embed the PIL image directly; the renderer consumes it as-is.
|
||||
{"type": "image", "image": img},
|
||||
{"type": "image_url", "image_url": {"url": image_url}},
|
||||
],
|
||||
}
|
||||
]
|
||||
@@ -125,51 +109,16 @@ def test_generate_qwen3_vl_e2e_features_payload_roundtrips_through_vllm():
|
||||
sampling_params={"max_tokens": 16},
|
||||
# Explicit cap so generate() skips the /v1/models discovery round-trip.
|
||||
max_prompt_len=1_000_000,
|
||||
process_multimodal=False,
|
||||
)
|
||||
)
|
||||
|
||||
# ── The HTTP body should carry a features payload. ──────────────────
|
||||
assert len(fake.calls) == 1
|
||||
body = fake.calls[0]["body"]
|
||||
assert "features" in body, "generate should ship features for image content"
|
||||
features = body["features"]
|
||||
|
||||
# ── Pydantic-roundtrip through vLLM's GenerateRequest model. ────────
|
||||
gen_req = GenerateRequest(
|
||||
token_ids=body["token_ids"],
|
||||
features=features,
|
||||
sampling_params=body["sampling_params"],
|
||||
)
|
||||
assert gen_req.features is not None
|
||||
assert "image" in gen_req.features.mm_hashes
|
||||
assert len(gen_req.features.mm_hashes["image"]) == 1
|
||||
|
||||
# ── Placeholder anchoring: the offset/length in features must land
|
||||
# exactly on a run of <|image_pad|> ids in the prompt. ───────────
|
||||
placeholders = gen_req.features.mm_placeholders["image"]
|
||||
assert len(placeholders) == 1
|
||||
ph = placeholders[0]
|
||||
pad_slice = body["token_ids"][ph.offset : ph.offset + ph.length]
|
||||
assert all(t == image_pad_id for t in pad_slice), (
|
||||
f"placeholder span ({ph.offset}, {ph.length}) does not cover image_pad tokens; slice={pad_slice[:8]}..."
|
||||
)
|
||||
|
||||
# ── kwargs_data decodes to MultiModalKwargsItem with the right keys. ─
|
||||
assert gen_req.features.kwargs_data is not None
|
||||
encoded_items = gen_req.features.kwargs_data["image"]
|
||||
assert len(encoded_items) == 1
|
||||
item = decode_mm_kwargs_item(encoded_items[0])
|
||||
assert set(item.keys()) == {"pixel_values", "image_grid_thw"}
|
||||
|
||||
# The image_grid_thw must match what the HF processor would have
|
||||
# produced for the same PIL image — strongest signal that the engine
|
||||
# sees the same image features the trainer will.
|
||||
direct_proc_out = processor.image_processor(images=[img], return_tensors="pt")
|
||||
expected_grid = direct_proc_out["image_grid_thw"][0].tolist()
|
||||
assert item["image_grid_thw"].data.tolist() == expected_grid
|
||||
|
||||
# ── Response parsed through renderer's parse_response. ──────────────
|
||||
assert "features" not in body
|
||||
assert body["content_parts"] == [{"type": "image_url", "url": image_url}]
|
||||
assert body["token_ids"].count(image_pad_id) == 1
|
||||
assert result["renderer_prompt_ids"] == body["token_ids"]
|
||||
assert result["prompt_ids"].count(image_pad_id) == 4
|
||||
assert result["mm_placeholders"] == {"image": [{"offset": body["token_ids"].index(image_pad_id), "length": 4}]}
|
||||
assert result["completion_ids"] == [50, 60, 151645]
|
||||
# multi_modal_data surfaces on the result so the caller can persist it.
|
||||
assert result["multi_modal_data"] is not None
|
||||
assert len(result["multi_modal_data"].mm_items["image"]) == 1
|
||||
|
||||
@@ -6,8 +6,10 @@ from prime_rl.trainer.rl.loss import (
|
||||
IcePopLoss,
|
||||
LossInputs,
|
||||
LossOutputs,
|
||||
_mismatch_kl_from_log_ratio,
|
||||
compute_entropy,
|
||||
compute_loss,
|
||||
ref_kl_loss_fn,
|
||||
setup_rl_loss_fn,
|
||||
)
|
||||
|
||||
@@ -124,10 +126,86 @@ def test_icepop_loss_masks_extreme_ratio_without_nan():
|
||||
result = IcePopLoss(IcePopLossConfig()).loss(inputs)
|
||||
|
||||
assert torch.equal(result.loss, torch.zeros_like(result.loss))
|
||||
assert all(torch.isfinite(value) for value in result.metrics.values())
|
||||
result.loss.backward()
|
||||
assert torch.equal(trainer_logprobs.grad, torch.zeros_like(trainer_logprobs.grad))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config", [IPOLossConfig(kl_tau=0.01), IcePopLossConfig()])
|
||||
def test_ipo_icepop_match_original_on_finite_ratios(config):
|
||||
torch.manual_seed(23)
|
||||
trainer_logprobs = (-8 * torch.rand(128, device="cuda")).requires_grad_()
|
||||
inference_logprobs = -8 * torch.rand(128, device="cuda")
|
||||
advantages = torch.randn(128, device="cuda")
|
||||
loss_mask = torch.rand(128, device="cuda") > 0.3
|
||||
weights = torch.rand(128, device="cuda")
|
||||
inputs = LossInputs(trainer_logprobs, inference_logprobs, None, advantages, loss_mask, weights)
|
||||
|
||||
result = setup_rl_loss_fn(config).loss(inputs)
|
||||
log_ratio = trainer_logprobs - inference_logprobs
|
||||
ratio = log_ratio.exp()
|
||||
if isinstance(config, IPOLossConfig):
|
||||
keep = loss_mask & ((trainer_logprobs.exp() - inference_logprobs.exp()).abs() <= config.eps)
|
||||
expected = (
|
||||
(-(keep * config.adv_tau * advantages * ratio) + loss_mask * config.kl_tau * log_ratio.square()) * weights
|
||||
).sum()
|
||||
else:
|
||||
keep = (
|
||||
loss_mask
|
||||
& (log_ratio.detach() >= torch.tensor(config.ratio_low, device="cuda").log())
|
||||
& (log_ratio.detach() <= torch.tensor(config.ratio_high, device="cuda").log())
|
||||
)
|
||||
expected = (-(keep * config.adv_tau * advantages * ratio) * weights).sum()
|
||||
|
||||
torch.testing.assert_close(result.loss, expected, rtol=1e-5, atol=1e-5)
|
||||
actual_grad = torch.autograd.grad(result.loss, trainer_logprobs, retain_graph=True)[0]
|
||||
expected_grad = torch.autograd.grad(expected, trainer_logprobs)[0]
|
||||
torch.testing.assert_close(actual_grad, expected_grad, rtol=1e-5, atol=1e-5)
|
||||
|
||||
|
||||
def test_ipo_excludes_masked_tokens_and_caps_accepted_extreme_ratio():
|
||||
trainer_logprobs = torch.tensor([-10.0, 0.0, float("nan")], device="cuda", requires_grad=True)
|
||||
inputs = LossInputs(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=torch.tensor([-100.0, -100.0, float("nan")], device="cuda"),
|
||||
ref_logprobs=None,
|
||||
advantages=torch.ones(3, device="cuda"),
|
||||
loss_mask=torch.tensor([True, True, False], device="cuda"),
|
||||
)
|
||||
|
||||
result = setup_rl_loss_fn(IPOLossConfig()).loss(inputs)
|
||||
|
||||
torch.testing.assert_close(result.loss, torch.tensor(-1e4, device="cuda"))
|
||||
assert all(torch.isfinite(value) for value in result.metrics.values())
|
||||
result.loss.backward()
|
||||
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([-1e4, 0.0, 0.0], device="cuda"))
|
||||
|
||||
|
||||
def test_ref_kl_loss_stays_finite_with_extreme_ratios_and_masked_nan():
|
||||
trainer_logprobs = torch.tensor([-10.0, 0.0, float("nan")], device="cuda", requires_grad=True)
|
||||
inputs = LossInputs(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=torch.tensor([-100.0, -100.0, float("nan")], device="cuda"),
|
||||
ref_logprobs=torch.tensor([-1.0, -1.0, float("nan")], device="cuda"),
|
||||
advantages=torch.zeros(3, device="cuda"),
|
||||
loss_mask=torch.tensor([True, True, False], device="cuda"),
|
||||
)
|
||||
|
||||
result = ref_kl_loss_fn(inputs)
|
||||
|
||||
assert torch.isfinite(result.loss)
|
||||
assert all(torch.isfinite(value) for value in result.metrics.values())
|
||||
result.loss.backward()
|
||||
assert torch.isfinite(trainer_logprobs.grad).all()
|
||||
|
||||
|
||||
def test_mismatch_kl_retains_small_positive_values():
|
||||
log_ratio = torch.tensor([1e-4], device="cuda")
|
||||
torch.testing.assert_close(
|
||||
_mismatch_kl_from_log_ratio(log_ratio), torch.tensor([5e-9], device="cuda"), rtol=1e-3, atol=0
|
||||
)
|
||||
|
||||
|
||||
def test_ce_component_matches_masked_nll():
|
||||
trainer_logprobs = [torch.tensor([-0.1, -0.5, -0.2], dtype=torch.float32).cuda()]
|
||||
inference_logprobs = [torch.zeros(3, dtype=torch.float32).cuda()]
|
||||
|
||||
@@ -3,6 +3,7 @@ from types import SimpleNamespace
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from prime_rl.multimodal.qwen_vl import QwenVLAdapter
|
||||
from prime_rl.trainer.model import forward
|
||||
|
||||
|
||||
@@ -35,11 +36,11 @@ def test_forward_passes_renderer_mm_token_type_ids_through():
|
||||
position_ids,
|
||||
seq_lens=torch.tensor([input_ids.shape[1]]),
|
||||
mm_kwargs={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw},
|
||||
mm_forward_policy=QwenVLAdapter.forward_policy,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
)
|
||||
|
||||
assert model.kwargs is not None
|
||||
# MRoPE families (image_grid_thw present) get position_ids stripped.
|
||||
assert "position_ids" not in model.kwargs
|
||||
torch.testing.assert_close(model.kwargs["pixel_values"], pixel_values)
|
||||
torch.testing.assert_close(model.kwargs["image_grid_thw"], image_grid_thw)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.multimodal import get_multimodal_adapter
|
||||
from prime_rl.multimodal.kimi_k25 import KimiK25Adapter
|
||||
from prime_rl.multimodal.qwen_vl import QwenVLAdapter
|
||||
from prime_rl.trainer.multimodal import materialize_mm_refs
|
||||
from prime_rl.transports.batch import MMImageRef, MMRefs
|
||||
|
||||
_IMAGE_URL = (
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
|
||||
)
|
||||
|
||||
|
||||
def _refs(length: int) -> MMRefs:
|
||||
return MMRefs(images=[MMImageRef(url=_IMAGE_URL, offset=1, length=length)])
|
||||
|
||||
|
||||
def test_qwen_adapter_materializes_and_validates_expansion():
|
||||
class ImageProcessor:
|
||||
merge_size = 1
|
||||
|
||||
def __call__(self, *, images, return_tensors):
|
||||
assert len(images) == 1 and images[0].mode == "RGB" and return_tensors == "pt"
|
||||
return {
|
||||
"pixel_values": torch.ones(2, 3),
|
||||
"image_grid_thw": torch.tensor([[1, 1, 2]]),
|
||||
}
|
||||
|
||||
processor = SimpleNamespace(image_processor=ImageProcessor())
|
||||
adapter = get_multimodal_adapter("qwen3_vl")
|
||||
materialized = materialize_mm_refs(_refs(2), processor, adapter)
|
||||
|
||||
assert set(materialized.kwargs) == {"pixel_values", "image_grid_thw"}
|
||||
assert materialized.forward_policy == QwenVLAdapter.forward_policy
|
||||
with pytest.raises(ValueError, match="placeholder lengths differ"):
|
||||
materialize_mm_refs(_refs(1), processor, adapter)
|
||||
|
||||
|
||||
def test_kimi_adapter_materializes_sparse_image_position():
|
||||
class ImageProcessor:
|
||||
def preprocess(self, media, *, return_tensors):
|
||||
assert len(media) == 1 and media[0]["type"] == "image"
|
||||
assert media[0]["image"].mode == "RGB" and return_tensors == "pt"
|
||||
return {
|
||||
"pixel_values": torch.ones(4, 3),
|
||||
"grid_thws": torch.tensor([[1, 2, 2]]),
|
||||
}
|
||||
|
||||
processor = SimpleNamespace(image_processor=ImageProcessor())
|
||||
materialized = materialize_mm_refs(_refs(1), processor, get_multimodal_adapter("kimi_k25"))
|
||||
|
||||
assert set(materialized.kwargs) == {"pixel_values", "grid_thws"}
|
||||
assert materialized.forward_policy == KimiK25Adapter.forward_policy
|
||||
@@ -134,7 +134,6 @@ members = [
|
||||
"swelego",
|
||||
"swerebench-v2",
|
||||
"swesmith-env",
|
||||
"tau2-bench",
|
||||
"terminal-bench-2",
|
||||
"terminal-lego",
|
||||
"tmax",
|
||||
@@ -189,15 +188,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/18/a6/907a406bb7d359e6a63f99c313846d9eec4f7e6f7437809e03aa00fa3074/absl_py-2.4.0-py3-none-any.whl", hash = "sha256:88476fd881ca8aab94ffa78b7b6c632a782ab3ba1cd19c9bd423abc4fb4cd28d", size = 135750, upload-time = "2026-01-28T10:17:04.19Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "addict"
|
||||
version = "2.4.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/85/ef/fd7649da8af11d93979831e8f1f8097e85e82d5bfeabc8c68b39175d8e75/addict-2.4.0.tar.gz", hash = "sha256:b3b2210e0e067a281f5646c8c5db92e99b7231ea8b0eb5f74dbdf9e259d4e494", size = 9186, upload-time = "2020-11-21T16:21:31.416Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/6a/00/b08f23b7d7e1e14ce01419a467b583edbb93c6cdb8654e54a9cc579cd61f/addict-2.4.0-py3-none-any.whl", hash = "sha256:249bb56bbfd3cdc2a004ea0ff4c2b6ddc84d53bc2194761636eb314d5cfa5dfc", size = 3832, upload-time = "2020-11-21T16:21:29.588Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ai-dynamo"
|
||||
version = "1.4.2"
|
||||
@@ -427,15 +417,6 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "appdirs"
|
||||
version = "1.4.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d7/d8/05696357e0311f5b5c316d7b95f46c669dd9c15aaeecbb48c7d0aeb88c40/appdirs-1.4.4.tar.gz", hash = "sha256:7d5d0167b2b1ba821647616af46a749d1c653740dd0d2415100fe26e27afdf41", size = 13470, upload-time = "2020-05-11T07:59:51.037Z" }
|
||||
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 = "appnope"
|
||||
version = "0.1.4"
|
||||
@@ -492,15 +473,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "backoff"
|
||||
version = "2.2.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/47/d7/5bbeb12c44d7c4f2fb5b56abce497eb5ed9f34d85701de869acedd602619/backoff-2.2.1.tar.gz", hash = "sha256:03f829f5bb1923180821643f8753b0502c3b682293992485b0eef2807afa5cba", size = 17001, upload-time = "2022-10-05T19:19:32.061Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/df/73/b6e24bd22e6720ca8ee9a85a0c4a2971af8497d8f3193fa05390cbd46e09/backoff-2.2.1-py3-none-any.whl", hash = "sha256:63579f9a0628e06278f7e47b7d7d5b6ce20dc65c5e96a6f3ca99a6adca0396e8", size = 15148, upload-time = "2022-10-05T19:19:30.546Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "backports-zstd"
|
||||
version = "1.7.0"
|
||||
@@ -763,19 +735,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0d/fe/6bea5c9162869c5beba5d9c8abbed835ec85bf1ec1fba05a3822325c45f3/build-1.5.0-py3-none-any.whl", hash = "sha256:13f3eecb844759ab66efec90ca17639bbf14dc06cb2fdf37a9010322d9c50a6f", size = 26018, upload-time = "2026-04-30T03:18:23.644Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cachebox"
|
||||
version = "5.2.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/36/f6/85f176d2518cf1d1be5f981fc2dadf6b131e33fefd721f36b330e3434d6c/cachebox-5.2.3.tar.gz", hash = "sha256:b1f68246685aa739bbbd2734befb1465363a1e1042407c154feadb065f17a099", size = 63686, upload-time = "2026-04-10T12:21:35.028Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/3a/79/89e4423352d0ca33bbf80fc1b4b665e654a93de8b16cf41e96fcac81801a/cachebox-5.2.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f3162758792626685ec34950eedd565d015b115d0ff0d751d2716031fc32d51b", size = 359562, upload-time = "2026-04-10T12:20:10.626Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d2/ab/e533c2751e6a3411ebe369277aaed03199b9e4586a48f0a3712a1f4b418b/cachebox-5.2.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a189a780c3ccd7b9d157074ba6bf3e191e522b39abbdb590075111851f02d50d", size = 397910, upload-time = "2026-04-10T12:18:53.336Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/01/b1/1a3c4e436ad8a4c4ba3e70f4c62e1f927cbbb3c943a9bba5813b8b815bde/cachebox-5.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2a1e7d3cb8a5e7e68996a8619e3ef8771a124d14568c251f9e586eba88d759c1", size = 398223, upload-time = "2026-04-10T12:19:57.583Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/36/71845b5c7a9ffbd85e6fdb470c11a174f499bd5238fa37b1214157c2454d/cachebox-5.2.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c7f0c72c51a3a9e7049ea6ff2a43cd3877ab7fee966eb65771a59621563b75e3", size = 567854, upload-time = "2026-04-10T12:20:38.357Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0a/d6/55859981f5ec6a9e412baaa4db6aa5973a00008750b3f054cdefcb6491fc/cachebox-5.2.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:649d18399f13735bb82daa33800196f815529c49e967767c40ca221723e68afa", size = 612309, upload-time = "2026-04-10T12:21:23.404Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cachetools"
|
||||
version = "7.1.4"
|
||||
@@ -1093,22 +1052,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/ac/aa647675812cd075f2cb9acb00d62f4f2cbcbc6736049a62342b7371ce5b/connectrpc-0.11.1-py3-none-any.whl", hash = "sha256:8a52e2e92a485fa9681c1101a79a5ebeb31807e3ea3d5aabd41f484a6398bc7b", size = 64991, upload-time = "2026-07-15T06:33:29.396Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "contourpy"
|
||||
version = "1.3.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "numpy" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/53/3e/405b59cfa13021a56bba395a6b3aca8cec012b45bf177b0eaf7a202cde2c/contourpy-1.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:556dba8fb6f5d8742f2923fe9457dbdd51e1049c4a43fd3986a0b14a1d815fc6", size = 273979, upload-time = "2025-07-26T12:01:22.448Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/1c/a12359b9b2ca3a845e8f7f9ac08bdf776114eb931392fcad91743e2ea17b/contourpy-1.3.3-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92d9abc807cf7d0e047b95ca5d957cf4792fcd04e920ca70d48add15c1a90ea7", size = 332653, upload-time = "2025-07-26T12:01:24.155Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cc/8f/ec6289987824b29529d0dfda0d74a07cec60e54b9c92f3c9da4c0ac732de/contourpy-1.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4d00e655fcef08aba35ec9610536bfe90267d7ab5ba944f7032549c55a146da1", size = 362601, upload-time = "2025-07-26T12:01:28.808Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/05/0a/a3fe3be3ee2dceb3e615ebb4df97ae6f3828aa915d3e10549ce016302bd1/contourpy-1.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:451e71b5a7d597379ef572de31eeb909a87246974d960049a9848c3bc6c41bf7", size = 1331288, upload-time = "2025-07-26T12:01:31.198Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/33/1d/acad9bd4e97f13f3e2b18a3977fe1b4a37ecf3d38d815333980c6c72e963/contourpy-1.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:459c1f020cd59fcfe6650180678a9993932d80d44ccde1fa1868977438f0b411", size = 1403386, upload-time = "2025-07-26T12:01:33.947Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cryptography"
|
||||
version = "48.0.0"
|
||||
@@ -1245,15 +1188,6 @@ nvtx = [
|
||||
{ name = "nvidia-nvtx" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cycler"
|
||||
version = "0.12.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cymem"
|
||||
version = "2.0.13"
|
||||
@@ -1420,19 +1354,6 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.2.dev137" }]
|
||||
|
||||
[[package]]
|
||||
name = "deepdiff"
|
||||
version = "9.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cachebox" },
|
||||
{ name = "orderly-set" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f9/6b/6a4a5aaf38535eb332c2856aa08e73ed7c549d0851b1215401af0a2db1a7/deepdiff-9.1.0.tar.gz", hash = "sha256:07e9e366fab4297755153c4eab795ad4ef3cbd0d51660e847f5751c6bd727687", size = 382149, upload-time = "2026-05-15T20:18:05.751Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl", hash = "sha256:80c0460e1993b04f6f0ca79abf25548b129fd218478c4ebb08f80560f5d10610", size = 184662, upload-time = "2026-05-15T20:18:03.956Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deepdive"
|
||||
version = "0.1.0"
|
||||
@@ -1527,7 +1448,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "discover-and-prove"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/prime-envs/environments/lean/discover_and_prove" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
@@ -1716,15 +1637,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/64/5f/824e6fb3e9d63408151dc9173994fa65bde620a67dde3a59354f5aecd497/faker-40.23.0-py3-none-any.whl", hash = "sha256:775922453e54afa42eaf60eac478fa3a969357f224d09a8022b93e3ad88f18ae", size = 2013046, upload-time = "2026-06-10T20:53:19.226Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "farama-notifications"
|
||||
version = "0.0.6"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ec/91/14397890dde30adc4bee6462158933806207bc5dd10d7b4d09d5c33845cf/farama_notifications-0.0.6.tar.gz", hash = "sha256:b19acac4bb41d76e59e03394b5dd165f4761c86fa327f56307a35cbee3b60158", size = 2517, upload-time = "2026-04-24T08:43:57.603Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7c/f0/21f81892e4ed10f4ec3ef2e7cf8635fb76e7c0907c55d0da66be50094760/farama_notifications-0.0.6-py3-none-any.whl", hash = "sha256:f84839188efa1ce5bb361c2a84881b2dc2c0d0d7fb661ff00421820170930935", size = 2897, upload-time = "2026-04-24T08:43:56.785Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastapi"
|
||||
version = "0.136.3"
|
||||
@@ -1979,23 +1891,9 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e8/2d/d2a548598be01649e2d46231d151a6c56d10b964d94043a335ae56ea2d92/flatbuffers-25.12.19-py2.py3-none-any.whl", hash = "sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4", size = 26661, upload-time = "2025-12-19T23:16:13.622Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fonttools"
|
||||
version = "4.63.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/84/69/c97f2c18e0db87d2c7b15da1974dace76ae938f1cfa22e2727a648b7ed43/fonttools-4.63.0.tar.gz", hash = "sha256:caeb583deeb5168e694b65cda8b4ee62abedfa66cf88488734466f2366b9c4e0", size = 3597189, upload-time = "2026-05-14T12:04:30.958Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/08/ef/b3c6b9b5be2f82416d73fe2ed2e96e2793cd80e7510bd6a17ca79cdd88ec/fonttools-4.63.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:37dd23e621e3b0aef1baa70a303b80aaf38449632cfc8fd2a55fb285bbccfc02", size = 2881131, upload-time = "2026-05-14T12:03:13.386Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/44/04/0b91d8e916e92ad1fac9e4624760baf0fd5ff2ead614c2f68fb21373f03f/fonttools-4.63.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ef3048ef05dbb552b89817713d9cac912e00d0fde4a3105c00d29e52e10c89af", size = 5044298, upload-time = "2026-05-14T12:03:18.085Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/77/c7/2342da9830e3e9d4870305ca5d2091d2a83284f2953079b7bdd3b5e029d8/fonttools-4.63.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:58dc6bb86a78d782f00f9190ca02c119cf5bbe2807536e361e18d42019f877d8", size = 4999800, upload-time = "2026-05-14T12:03:20.161Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e6/6d/67fe16c48d7ce050979b33f47e0d28a318f02da030602e944c34f7a16ef3/fonttools-4.63.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ee08ebfa58f6e1aeff5697ab9582105bb620008c1caafb681e4c557e7483027b", size = 4982666, upload-time = "2026-05-14T12:03:22.87Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f2/00/3bbab338c07c71fa56269953845e92c951a61457bbbb0f1022551ea266d9/fonttools-4.63.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:27fdc65af8da6f88b9c6121c47a464cbe359fcfff7ff6fc2d37a1f395d755b78", size = 5133598, upload-time = "2026-05-14T12:03:25.168Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2c/47/c99d5268f354002ce80f8d029cd9d7d872969da1de8b93d32de4dc56d6f4/fonttools-4.63.0-py3-none-any.whl", hash = "sha256:445af2eab030a16b9171ea8bdda7ebf7d96bda2df88ee182a464252f6e05e20d", size = 1164562, upload-time = "2026-05-14T12:04:29.092Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "formalmath"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/prime-envs/environments/lean/formalmath" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
@@ -2049,20 +1947,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs"
|
||||
version = "2.4.16"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "appdirs" },
|
||||
{ name = "setuptools" },
|
||||
{ name = "six" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/5d/a9/af5bfd5a92592c16cdae5c04f68187a309be8a146b528eac3c6e30edbad2/fs-2.4.16.tar.gz", hash = "sha256:ae97c7d51213f4b70b6a958292530289090de3a7e15841e108fbe144f069d313", size = 187441, upload-time = "2022-05-02T09:25:54.22Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b9/5c/a3d95dc1ec6cdeb032d789b552ecc76effa3557ea9186e1566df6aac18df/fs-2.4.16-py2.py3-none-any.whl", hash = "sha256:660064febbccda264ae0b6bace80a8d1be9e089e0a5eb2427b7d517f9a91545c", size = 135261, upload-time = "2022-05-02T09:25:52.363Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fsspec"
|
||||
version = "2026.2.0"
|
||||
@@ -2204,7 +2088,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "gpqa"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/prime-envs/environments/science/gpqa" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
@@ -2277,21 +2161,6 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "datasets" }]
|
||||
|
||||
[[package]]
|
||||
name = "gymnasium"
|
||||
version = "1.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cloudpickle" },
|
||||
{ name = "farama-notifications" },
|
||||
{ name = "numpy" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/4d/ff/14b6880d703dfaca204490979d3254ccd280c99550798993319902873658/gymnasium-1.3.0.tar.gz", hash = "sha256:6939e86e835d6b71b6ba6bfd360487420876deafc79bfb7bacba83a7c446bcf3", size = 830646, upload-time = "2026-04-22T13:47:14.155Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/73/fda6a25f3beeb5e49d74330b44092b9e5a547395ccd478d1103ddcbff1fc/gymnasium-1.3.0-py3-none-any.whl", hash = "sha256:6b8c159a8540dcbcb221722d7efda24d78ebbcbc3bd2ea1c2611aa2a34471fc2", size = 953904, upload-time = "2026-04-22T13:47:12.13Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "h11"
|
||||
version = "0.16.0"
|
||||
@@ -3052,7 +2921,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "kimina"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
source = { editable = "deps/prime-envs/environments/lean/kimina" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
@@ -3067,22 +2936,6 @@ requires-dist = [
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kiwisolver"
|
||||
version = "1.5.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d0/67/9c61eccb13f0bdca9307614e782fec49ffdde0f7a2314935d489fa93cd9c/kiwisolver-1.5.0.tar.gz", hash = "sha256:d4193f3d9dc3f6f79aaed0e5637f45d98850ebf01f7ca20e69457f3e8946b66a", size = 103482, upload-time = "2026-03-09T13:15:53.382Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4d/b2/818b74ebea34dabe6d0c51cb1c572e046730e64844da6ed646d5298c40ce/kiwisolver-1.5.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:4e9750bc21b886308024f8a54ccb9a2cc38ac9fa813bf4348434e3d54f337ff9", size = 123158, upload-time = "2026-03-09T13:13:23.127Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/99/9f/795fedf35634f746151ca8839d05681ceb6287fbed6cc1c9bf235f7887c2/kiwisolver-1.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ed3a984b31da7481b103f68776f7128a89ef26ed40f4dc41a2223cda7fb24819", size = 64068, upload-time = "2026-03-09T13:13:25.878Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c4/13/680c54afe3e65767bed7ec1a15571e1a2f1257128733851ade24abcefbcc/kiwisolver-1.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bb5136fb5352d3f422df33f0c879a1b0c204004324150cc3b5e3c4f310c9049f", size = 1477934, upload-time = "2026-03-09T13:13:27.166Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c8/2f/cebfcdb60fd6a9b0f6b47a9337198bcbad6fbe15e68189b7011fd914911f/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b2af221f268f5af85e776a73d62b0845fc8baf8ef0abfae79d29c77d0e776aaf", size = 1278537, upload-time = "2026-03-09T13:13:28.707Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/bd/c314595208e4c9587652d50959ead9e461995389664e490f4dce7ff0f782/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7c60d3c9b06fb23bd9c6139281ccbdc384297579ae037f08ae90c69f6845c0b1", size = 2227742, upload-time = "2026-03-09T13:13:36.4Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e4/34/8aefdd0be9cfd00a44509251ba864f5caf2991e36772e61c408007e7f417/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1d9daea4ea6b9be74fe2f01f7fbade8d6ffab263e781274cffca0dba9be9eec9", size = 2294947, upload-time = "2026-03-09T13:13:43.343Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0f/41/c5f71f9f00aabcc71fee8b7475e3f64747282580c2fe748961ba29b18385/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:f6764a4ccab3078db14a632420930f6186058750df066b8ea2a7106df91d3203", size = 138036, upload-time = "2026-03-09T13:15:36.894Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fa/06/7399a607f434119c6e1fdc8ec89a8d51ccccadf3341dee4ead6bd14caaf5/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c31c13da98624f957b0fb1b5bae5383b2333c2c3f6793d9825dd5ce79b525cb7", size = 194295, upload-time = "2026-03-09T13:15:38.22Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kubernetes"
|
||||
version = "32.0.1"
|
||||
@@ -3164,25 +3017,6 @@ dependencies = [
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0e/72/a3add0e4eec4eb9e2569554f7c70f4a3c27712f40e3284d483e88094cc0e/langdetect-1.0.9.tar.gz", hash = "sha256:cbc1fef89f8d062739774bd51eda3da3274006b3661d199c2655f6b3f6d605a0", size = 981474, upload-time = "2021-05-07T07:54:13.562Z" }
|
||||
|
||||
[[package]]
|
||||
name = "langfuse"
|
||||
version = "4.7.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "backoff" },
|
||||
{ name = "httpx" },
|
||||
{ name = "opentelemetry-api" },
|
||||
{ name = "opentelemetry-exporter-otlp-proto-http" },
|
||||
{ name = "opentelemetry-sdk" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "wrapt" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/2c/74/a6f1a99893ee6d1a69439ae7eb92f8fe8806103492dc26531d5942dbd3bf/langfuse-4.7.1.tar.gz", hash = "sha256:f9e262eceedb353b191c1da1f8452d1e8ebf52297ca20e160cda0206608e3a40", size = 320620, upload-time = "2026-05-29T18:06:22.435Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/9f/9a/bd3368f46b6c72ee2068b80536826b02ae86df53eff1c79941344503098f/langfuse-4.7.1-py3-none-any.whl", hash = "sha256:a4e59c81ad5e5b16a65d3849f4923ebc3ad6e67ec803ada83d50c0cb66149490", size = 562571, upload-time = "2026-05-29T18:06:20.517Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lark"
|
||||
version = "1.2.2"
|
||||
@@ -3207,7 +3041,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "lean-common"
|
||||
version = "0.1.0"
|
||||
version = "0.1.2"
|
||||
source = { editable = "deps/prime-envs/packages/lean_common" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
@@ -3472,7 +3306,7 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "matholympiadbench"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/prime-envs/environments/lean/matholympiadbench" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
@@ -3485,29 +3319,6 @@ requires-dist = [
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matplotlib"
|
||||
version = "3.10.9"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "contourpy" },
|
||||
{ name = "cycler" },
|
||||
{ name = "fonttools" },
|
||||
{ name = "kiwisolver" },
|
||||
{ name = "numpy" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pillow" },
|
||||
{ name = "pyparsing" },
|
||||
{ name = "python-dateutil" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/63/1b/4be5be87d43d327a0cf4de1a56e86f7f84c89312452406cf122efe2839e6/matplotlib-3.10.9.tar.gz", hash = "sha256:fd66508e8c6877d98e586654b608a0456db8d7e8a546eb1e2600efd957302358", size = 34811233, upload-time = "2026-04-24T00:14:13.539Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/18/4880dd762e40cd360c1bf06e890c5a97b997e91cb324602b1a19950ad5ce/matplotlib-3.10.9-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:41cb28c2bd769aa3e98322c6ab09854cbcc52ab69d2759d681bba3e327b2b320", size = 8216016, upload-time = "2026-04-24T00:12:23.4Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/32/91/d024616abdba99e83120e07a20658976f6a343646710760c4a51df126029/matplotlib-3.10.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ae20801130378b82d647ff5047c07316295b68dc054ca6b3c13519d0ea624285", size = 8789336, upload-time = "2026-04-24T00:12:26.096Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/04/030a2f61ef2158f5e4c259487a92ac877732499fb33d871585d89e03c42d/matplotlib-3.10.9-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6c63ebcd8b4b169eb2f5c200552ae6b8be8999a005b6b507ed76fb8d7d674fe2", size = 9604602, upload-time = "2026-04-24T00:12:29.052Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fc/c2/541e4d09d87bb6b5830fc28b4c887a9a8cf4e1c6cee698a8c05552ae2003/matplotlib-3.10.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d75d11c949914165976c621b2324f9ef162af7ebf4b057ddf95dd1dba7e5edcf", size = 9670966, upload-time = "2026-04-24T00:12:32.131Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matplotlib-inline"
|
||||
version = "0.2.2"
|
||||
@@ -3585,7 +3396,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "minif2f"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
source = { editable = "deps/prime-envs/environments/lean/minif2f" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
@@ -4091,7 +3902,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "numina"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
source = { editable = "deps/prime-envs/environments/lean/numina" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
@@ -4706,15 +4517,6 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "orderly-set"
|
||||
version = "5.5.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/4a/88/39c83c35d5e97cc203e9e77a4f93bf87ec89cf6a22ac4818fdcc65d66584/orderly_set-5.5.0.tar.gz", hash = "sha256:e87185c8e4d8afa64e7f8160ee2c542a475b738bc891dc3f58102e654125e6ce", size = 27414, upload-time = "2025-07-10T20:10:55.885Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/12/27/fb8d7338b4d551900fa3e580acbe7a0cf655d940e164cb5c00ec31961094/orderly_set-5.5.0-py3-none-any.whl", hash = "sha256:46f0b801948e98f427b412fcabb831677194c05c3b699b80de260374baa0b1e7", size = 13068, upload-time = "2025-07-10T20:10:54.377Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "orjson"
|
||||
version = "3.11.9"
|
||||
@@ -4940,19 +4742,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/36/43/b4b18bdc87e1949568fffdcde3ff9a0456266b2d0c6d4432cc34d89ea6eb/playwright-1.62.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:db2d76613a57ad844362ce42f7d0c2fa26b19a4f7a46d4f76b891c631e6e5aff", size = 47441423, upload-time = "2026-07-31T17:01:00.404Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "plotly"
|
||||
version = "6.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "narwhals" },
|
||||
{ name = "packaging" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3a/7f/0f100df1172aadf88a929a9dbb902656b0880ba4b960fe5224867159d8f4/plotly-6.7.0.tar.gz", hash = "sha256:45eea0ff27e2a23ccd62776f77eb43aa1ca03df4192b76036e380bb479b892c6", size = 6911286, upload-time = "2026-04-09T20:36:45.738Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/90/ad/cba91b3bcf04073e4d1655a5c1710ef3f457f56f7d1b79dcc3d72f4dd912/plotly-6.7.0-py3-none-any.whl", hash = "sha256:ac8aca1c25c663a59b5b9140a549264a5badde2e057d79b8c772ae2920e32ff0", size = 9898444, upload-time = "2026-04-09T20:36:39.812Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pluggy"
|
||||
version = "1.6.0"
|
||||
@@ -5260,7 +5049,7 @@ requires-dist = [
|
||||
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
|
||||
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.3" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.3.0" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.3.2" },
|
||||
{ name = "prometheus-client", specifier = ">=0.20.0" },
|
||||
{ name = "psutil", specifier = ">=7.0.0" },
|
||||
{ name = "pyarrow", specifier = ">=21.0.0" },
|
||||
@@ -5329,7 +5118,7 @@ requires-dist = [
|
||||
{ name = "renderers", specifier = ">=0.1.11" },
|
||||
{ name = "tomli", specifier = ">=2.2.1" },
|
||||
{ name = "tomli-w", specifier = ">=1.2.0" },
|
||||
{ name = "verifiers", specifier = ">=0.3.0" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev143" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5352,7 +5141,7 @@ train = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-sandboxes"
|
||||
version = "0.3.0"
|
||||
version = "0.3.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiofiles" },
|
||||
@@ -5364,9 +5153,9 @@ dependencies = [
|
||||
{ name = "pyqwest" },
|
||||
{ name = "tenacity" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b6/46/2d118d8bbb901b729f3bc0678725eb28088d757a872db04cffa1492d0208/prime_sandboxes-0.3.0.tar.gz", hash = "sha256:c99075ed82a9bbfe5a453cee84b9f09565a7f6b07fd5ace072401cce59a1fe08", size = 132759, upload-time = "2026-09-18T01:32:31.263Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f8/fe/69195c7c9e3d0f938e84ae54a8ffd386529019fb7635cad65d318e96271d/prime_sandboxes-0.3.2.tar.gz", hash = "sha256:6ded2497cbff8b5760e3f7897e1f00f2b789463daa397481620361bb148bfc45", size = 135266, upload-time = "2026-09-25T21:35:16.33Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5f/04/c77c7f260babf93978f912b85511e76f63a3cfa5bb11a8c34108177d5825/prime_sandboxes-0.3.0-py3-none-any.whl", hash = "sha256:19078ff508fa72de8f565422918faf367e2831ed8a2f26a5a6a98110e4062941", size = 71441, upload-time = "2026-09-18T01:32:30.062Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/26/fc/6eefb673bbcbdd33105b5d14e8d7329a0b10a30c893ac8c74a8f2373a477/prime_sandboxes-0.3.2-py3-none-any.whl", hash = "sha256:d47f07fe90e662464ddd33468fa538f37c962e7bec5c2cbbbd170eb57d0ef89e", size = 72421, upload-time = "2026-09-25T21:35:14.99Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5564,7 +5353,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "proverbench"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
source = { editable = "deps/prime-envs/environments/lean/proverbench" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
@@ -5720,18 +5509,6 @@ email = [
|
||||
{ name = "email-validator" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pydantic-argparse"
|
||||
version = "0.10.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/94/ea/e63d587294c20d3b83e9c312b5d577c9ec28962ee8490839ca9996672849/pydantic_argparse-0.10.0.tar.gz", hash = "sha256:d57eb0a84c8f0af6605376157d3f445cfd786700f2e596ba9d48d15d557185eb", size = 15928, upload-time = "2025-02-09T08:18:30.425Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/be/14/9ee71e3a183f76ff93e46b36157d6ddbf29ec2547b7d2c57931cd5d3aecc/pydantic_argparse-0.10.0-py3-none-any.whl", hash = "sha256:e317f001208d77a5600ece6f7ac78d768d8221a7d64a958980705e9630c2e299", size = 25265, upload-time = "2025-02-09T08:18:27.671Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pydantic-core"
|
||||
version = "2.46.4"
|
||||
@@ -5864,15 +5641,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/42/80/7b13c12fd5f3243b01190130ce098a44ddf62e030e6ed712911cbfe40311/pynvvideocodec-2.0.4-cp312-cp312-manylinux_2_34_aarch64.whl", hash = "sha256:a0daa28b09705806c8c6b26326df217c45e60c0a12a673ea3ea6ee5e2e7193b0", size = 35754893, upload-time = "2026-05-27T04:04:43.866Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyparsing"
|
||||
version = "3.3.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f3/91/9c6ee907786a473bf81c5f53cf703ba0957b23ab84c264080fb5a450416f/pyparsing-3.3.2.tar.gz", hash = "sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc", size = 6851574, upload-time = "2026-01-21T03:57:59.36Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pypika"
|
||||
version = "0.51.1"
|
||||
@@ -6164,15 +5932,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/13/60/164246615e8b059f6d53d34648a0784260421ec98a07eb1e45160f063221/realtime-2.31.0-py3-none-any.whl", hash = "sha256:f6e494b53d6a6e80b6efcee6711c8dd40413a52e766271de1bce8ced6c36cc1d", size = 22374, upload-time = "2026-06-04T13:37:21.162Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redis"
|
||||
version = "8.0.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/53/ae/ed461cca5780b5fc8b9fe8ca0ed98d89508645fb9d880c24cc42c087678f/redis-8.0.0.tar.gz", hash = "sha256:a00c5355432051ac14e593b8b197fc76c887ee12d55a0984f69328a1115fdc49", size = 5101591, upload-time = "2026-05-28T12:45:13.5Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/27/e3/b519734372d305bd547534a9f32e4ce9f98552af753dce72cf3483a0ff0b/redis-8.0.0-py3-none-any.whl", hash = "sha256:c938c18338585009f0bc310f4c7e4e4b4d37639356c4ac072cedf3af570c8dc7", size = 499870, upload-time = "2026-05-28T12:45:11.697Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redsearcher"
|
||||
version = "0.1.0"
|
||||
@@ -6481,20 +6240,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/65/94/7698add8f276dbab7a9de9fb6b0e02fc13ee61d51c7c3f85ac28b65e1239/scipy-1.17.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f590cd684941912d10becc07325a3eeb77886fe981415660d9265c4c418d0bea", size = 37625856, upload-time = "2026-02-23T00:19:00.307Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "seaborn"
|
||||
version = "0.13.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "matplotlib" },
|
||||
{ name = "numpy" },
|
||||
{ name = "pandas" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/86/59/a451d7420a77ab0b98f7affa3a1d78a313d2f7281a57afb1a34bae8ab412/seaborn-0.13.2.tar.gz", hash = "sha256:93e60a40988f4d65e9f4885df477e2fdaff6b73a9ded434c1ab356dd57eefff7", size = 1457696, upload-time = "2024-01-25T13:21:52.551Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/83/11/00d3c3dfc25ad54e731d91449895a79e4bf2384dc3ac01809010ba88f6d5/seaborn-0.13.2-py3-none-any.whl", hash = "sha256:636f8336facf092165e27924f223d3c62ca560b1f2bb5dff7ab7fad265361987", size = 294914, upload-time = "2024-01-25T13:21:49.598Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "senior-swe-bench"
|
||||
version = "0.1.1"
|
||||
@@ -7060,55 +6805,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/40/44/4a5f08c96eb108af5cb50b41f76142f0afa346dfa99d5296fe7202a11854/tabulate-0.9.0-py3-none-any.whl", hash = "sha256:024ca478df22e9340661486f85298cff5f6dcdba14f3813e8830015b9ed1948f", size = 35252, upload-time = "2022-10-06T17:21:44.262Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tau2"
|
||||
version = "0.2.1.dev0"
|
||||
source = { git = "https://github.com/sierra-research/tau2-bench.git?rev=337326e#337326e62d8e0ca74c353b004a9c5d748e0ba914" }
|
||||
dependencies = [
|
||||
{ name = "addict" },
|
||||
{ name = "deepdiff" },
|
||||
{ name = "docstring-parser" },
|
||||
{ name = "fastapi" },
|
||||
{ name = "fs" },
|
||||
{ name = "gymnasium" },
|
||||
{ name = "langfuse" },
|
||||
{ name = "litellm" },
|
||||
{ name = "loguru" },
|
||||
{ name = "matplotlib" },
|
||||
{ name = "pandas" },
|
||||
{ name = "plotly" },
|
||||
{ name = "psutil" },
|
||||
{ name = "pydantic-argparse" },
|
||||
{ name = "pytest" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "redis" },
|
||||
{ name = "rich" },
|
||||
{ name = "ruff" },
|
||||
{ name = "scikit-learn" },
|
||||
{ name = "seaborn" },
|
||||
{ name = "tabulate" },
|
||||
{ name = "tenacity" },
|
||||
{ name = "toml" },
|
||||
{ name = "uvicorn" },
|
||||
{ name = "watchdog" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tau2-bench"
|
||||
version = "0.3.1"
|
||||
source = { editable = "deps/prime-envs/environments/tool_use/tau2_bench" }
|
||||
dependencies = [
|
||||
{ name = "tau2" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
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.3.1" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tenacity"
|
||||
version = "9.1.4"
|
||||
@@ -8537,18 +8233,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/06/7c/34330a89da55610daa5f245ddce5aab81244321101614751e7537f125133/wasabi-1.1.3-py3-none-any.whl", hash = "sha256:f76e16e8f7e79f8c4c8be49b4024ac725713ab10cd7f19350ad18a8e3f71728c", size = 27880, upload-time = "2024-05-31T16:56:16.699Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "watchdog"
|
||||
version = "6.0.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471, upload-time = "2024-11-01T14:06:37.745Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054, upload-time = "2024-11-01T14:06:41.009Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "watchfiles"
|
||||
version = "1.2.0"
|
||||
|
||||
Reference in New Issue
Block a user