Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d72e7e8b1e | ||
|
|
2662c9ace1 | ||
|
|
cde3bcd546 | ||
|
|
f962e9c104 | ||
|
|
771953ee01 | ||
|
|
e3dd67633d | ||
|
|
0a437ae340 | ||
|
|
9a55a0899c | ||
|
|
666297d09c | ||
|
|
202f108f33 |
+13
-10
@@ -153,22 +153,25 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
&& 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
|
||||
|
||||
@@ -22,7 +22,9 @@ lr = 2e-5
|
||||
|
||||
[eval]
|
||||
interval = 25
|
||||
num_examples = 32
|
||||
|
||||
[eval.select]
|
||||
limit = 32
|
||||
|
||||
[eval.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
# CI eval smoke: gsm8k with the null harness in a local subprocess runtime against
|
||||
# Prime Inference — the eval path end to end without a GPU or sandbox.
|
||||
num_examples = 4
|
||||
dashboard = false
|
||||
|
||||
[select]
|
||||
limit = 4
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 8192
|
||||
|
||||
|
||||
@@ -48,7 +48,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 16
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 16
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -54,7 +54,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 16
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 16
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -29,7 +29,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -29,7 +29,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -48,7 +48,9 @@ algo.teacher.base_url = "http://localhost:8001/v1"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -41,7 +41,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -41,7 +41,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -31,7 +31,9 @@ env.player1.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 16
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 16
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
@@ -37,7 +37,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -46,7 +46,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -46,7 +46,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -117,7 +117,7 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
num_examples = 100
|
||||
select.limit = 100
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["debug-concurrency"]
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/multi-env.toml
|
||||
|
||||
num_examples = 16
|
||||
[select]
|
||||
limit = 16
|
||||
|
||||
[[source]]
|
||||
name = "tb2-bash"
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/multi-turn.toml
|
||||
|
||||
num_examples = 16
|
||||
[select]
|
||||
limit = 16
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
|
||||
@@ -7,9 +7,11 @@
|
||||
# <Ctrl-C partway>
|
||||
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug --resume
|
||||
|
||||
num_examples = 8
|
||||
group_size = 2
|
||||
|
||||
[select]
|
||||
limit = 8
|
||||
|
||||
[concurrency]
|
||||
min_inflight = 2
|
||||
max_inflight = 2
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/single-turn.toml
|
||||
|
||||
num_examples = 8
|
||||
group_size = 2
|
||||
|
||||
[select]
|
||||
limit = 8
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 8192
|
||||
|
||||
|
||||
@@ -31,7 +31,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
num_examples = 64
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 64
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: 647ff7ade5...565e8a74c0
Vendored
+1
-1
Submodule deps/verifiers updated: 509983f90e...e5a9e17a8c
@@ -180,6 +180,13 @@ retries.include = ["ProviderError", "SandboxError"]
|
||||
timeout.episode = 7200
|
||||
```
|
||||
|
||||
Each source also takes a `select` block that picks which tasks of its taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit`, in that order. A group's `select` block works like its `env` block: every source inherits it field by field, and a source's own fields win. A source's `include` or `exclude` replaces the group's whole block. To evaluate 128 tasks of each taskset:
|
||||
|
||||
```toml
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
```
|
||||
|
||||
`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>.*`).
|
||||
|
||||
+10
-5
@@ -32,19 +32,21 @@ 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`). `<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.
|
||||
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`/`-s`/`-r` set `select.limit`/`select.shuffle`/`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`).
|
||||
|
||||
## Configuration
|
||||
|
||||
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `num_examples`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
|
||||
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `[select]`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
|
||||
|
||||
```toml
|
||||
model = "Qwen/Qwen3-4B"
|
||||
num_examples = 32
|
||||
group_size = 4
|
||||
|
||||
[select] # every source inherits these
|
||||
limit = 32
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
@@ -67,9 +69,12 @@ env.agent.harness.id = "bash"
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
select.include.idx = ["0:30"]
|
||||
```
|
||||
|
||||
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.
|
||||
Per-source `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.
|
||||
|
||||
Each field a source sets in its `select` overrides the same field of the top-level `[select]`. `select` picks which tasks of the taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit` (see verifiers' [Selecting tasks](../deps/verifiers/docs/v1/tasksets.md#selecting-tasks)). Train sources take the same `select`.
|
||||
|
||||
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.
|
||||
|
||||
@@ -85,7 +90,7 @@ uv run eval @ eval.toml --run.name my-eval --resume
|
||||
|
||||
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
|
||||
|
||||
A landed episode counts toward the task with its `task.key`, so `num_examples` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The model, the sampling and each source's env must match the config the landed episodes were measured with (kept beside them in `monitors/file/eval.json`); a resume that changes them stops with the differing config paths. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
|
||||
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: 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, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
|
||||
|
||||
## Monitors
|
||||
|
||||
|
||||
+1
-1
@@ -287,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
|
||||
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.29 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
|
||||
+4
-2
@@ -184,12 +184,14 @@ Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manag
|
||||
|
||||
### Online Evals
|
||||
|
||||
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `num_examples` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
|
||||
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `select` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
|
||||
|
||||
```toml
|
||||
[eval]
|
||||
interval = 25
|
||||
num_examples = 32
|
||||
|
||||
[eval.select]
|
||||
limit = 32
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
@@ -148,7 +148,7 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "browsecomp"
|
||||
num_examples = 500 # full set is 1266; cap eval at 500
|
||||
select.limit = 500 # full set is 1266; cap eval at 500
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
# uv run eval @ examples/basic/alphabet-sort/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[select]
|
||||
limit = 20
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
# uv run eval @ examples/basic/reverse-text/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-0.6B"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[select]
|
||||
limit = 20
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text-eval"
|
||||
num_examples = 256
|
||||
select.limit = 256
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
@@ -15,7 +15,9 @@ lr = 2e-5
|
||||
|
||||
[eval]
|
||||
interval = 25
|
||||
num_examples = 32
|
||||
|
||||
[eval.select]
|
||||
limit = 32
|
||||
|
||||
[eval.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
# uv run eval @ examples/basic/wiki-search/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[select]
|
||||
limit = 20
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
# uv run eval @ examples/basic/wordle/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-1.7B"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[select]
|
||||
limit = 20
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ dependencies = [
|
||||
"renderers>=0.1.11",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.3.2.dev143",
|
||||
"verifiers>=0.3.2.dev152",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
|
||||
@@ -57,14 +58,15 @@ class EvalConfig(ServedEvalConfig):
|
||||
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
|
||||
"""Client of the inference server. Defaults to Prime Inference."""
|
||||
|
||||
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
|
||||
"""Task selection that every source inherits (``-n`` sets ``limit``, ``-s`` sets
|
||||
``shuffle``). Each field a source sets on its own ``select`` wins over this one."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig(min_inflight=128, max_inflight=128)
|
||||
"""In-flight episodes, pinned at 128 (``-c N`` repins). External APIs expose no vLLM
|
||||
``/metrics`` to adapt to; against a vLLM server set ``min_inflight < max_inflight`` to
|
||||
let the band adapt to KV usage like the orchestrator's."""
|
||||
|
||||
num_examples: int = Field(-1, validation_alias=AliasChoices("num_examples", "n"))
|
||||
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
|
||||
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "r"))
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
@@ -87,9 +89,7 @@ class EvalConfig(ServedEvalConfig):
|
||||
|
||||
resume: bool = False
|
||||
"""Continue the interrupted run named by ``run.name`` from its trace stream: the
|
||||
landed episodes rejoin the epoch and only the rollouts still owed run. The model,
|
||||
sampling and env config must match the interrupted run; ``num_examples`` and
|
||||
``group_size`` may change."""
|
||||
landed episodes rejoin the epoch and only the rollouts still owed run."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
|
||||
@@ -640,6 +640,11 @@ class InferenceConfig(BaseConfig):
|
||||
if "enable_prompt_tokens_details" not in extra_fields:
|
||||
namespace.enable_prompt_tokens_details = True
|
||||
|
||||
# The orchestrator generates through /inference/v1/generate, a scale-out
|
||||
# endpoint that vLLM registers only with `--enable-scale-out`.
|
||||
if "enable_scale_out" not in extra_fields:
|
||||
namespace.enable_scale_out = True
|
||||
|
||||
# vLLM's DeepseekV2-family (and transformers-backend MoE) gates read
|
||||
# `moe_router_dtype` off the HF config to pick the router logits dtype.
|
||||
if self.enable_fp32_router_logits:
|
||||
|
||||
@@ -166,8 +166,8 @@ class EnvConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
|
||||
|
||||
shuffle: bool = False
|
||||
"""Shuffle the source's finite taskset once with a fixed seed. The shuffled order is fixed for the whole run; infinite tasksets cannot be shuffled."""
|
||||
select: vf.SelectConfig = vf.SelectConfig()
|
||||
"""Which of the taskset's tasks this source uses: ``include``/``exclude`` by ``idx``, ``ids``, ``keys`` or ``names``, then ``shuffle``, ``skip`` and ``limit``, applied in that order."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
@@ -194,22 +194,51 @@ 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:
|
||||
def merge_group_defaults(data: Any) -> Any:
|
||||
"""Shared ``mode="before"`` body for source groups: layer the group's ``env`` and
|
||||
``select`` blocks under those of each raw source. A source's own values win; a
|
||||
source's ``include`` or ``exclude`` replaces the group's whole block."""
|
||||
if not isinstance(data, dict):
|
||||
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 []
|
||||
]
|
||||
sources = data.get("source") or []
|
||||
if data.get("env") is not None:
|
||||
try:
|
||||
shared = vf.SharedEnvConfig.model_validate(data["env"])
|
||||
except ValidationError:
|
||||
shared = None # the ``env`` field reports the errors once, not once per source
|
||||
if shared is not None:
|
||||
sources = [
|
||||
{**source, "env": vf.merge_env_defaults(shared, source.get("env"))}
|
||||
if isinstance(source, dict)
|
||||
else source
|
||||
for source in sources
|
||||
]
|
||||
if data.get("select") is not None:
|
||||
group = select_fields(data["select"], vf.SelectCLIConfig)
|
||||
if group is not None:
|
||||
sources = [
|
||||
{**source, "select": group | own}
|
||||
if isinstance(source, dict)
|
||||
and (own := select_fields(source.get("select"), vf.SelectConfig)) is not None
|
||||
else source
|
||||
for source in sources
|
||||
]
|
||||
if sources:
|
||||
data["source"] = sources
|
||||
return data
|
||||
|
||||
|
||||
def select_fields(raw: Any, select_type: type[vf.SelectConfig]) -> dict | None:
|
||||
"""The fields a raw ``select`` block sets, under their canonical names; None when
|
||||
the block is invalid, which leaves it to report its own errors."""
|
||||
if raw is None:
|
||||
return {}
|
||||
try:
|
||||
return select_type.model_validate(raw).model_dump(exclude_unset=True)
|
||||
except ValidationError:
|
||||
return None
|
||||
|
||||
|
||||
class StandardSamplerConfig(BaseConfig):
|
||||
type: Literal["standard"] = "standard"
|
||||
|
||||
@@ -306,9 +335,6 @@ class EvalSourceConfig(EnvConfig):
|
||||
sampling: EvalSamplingConfig = EvalSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
|
||||
|
||||
num_examples: int = -1
|
||||
"""Eval examples to sample from the dataset. ``-1`` uses all available examples."""
|
||||
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
|
||||
|
||||
@@ -331,10 +357,14 @@ class TrainConfig(BaseConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
|
||||
select: vf.SelectConfig = vf.SelectConfig()
|
||||
"""Task selection that every training source inherits. Each field a source sets on
|
||||
its own ``select`` wins over this one."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def resolve_group_env(cls, data):
|
||||
return merge_group_env(data)
|
||||
def resolve_group_defaults(cls, data):
|
||||
return merge_group_defaults(data)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
@@ -373,21 +403,23 @@ class EvalSourcesConfig(BaseConfig):
|
||||
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
|
||||
"""Shared eval sampling configuration; can differ from training sampling."""
|
||||
|
||||
num_examples: int = -1
|
||||
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
|
||||
select: vf.SelectConfig = vf.SelectConfig()
|
||||
"""Task selection that every eval source inherits, e.g. ``limit = 128`` to evaluate
|
||||
128 tasks of each taskset. Each field a source sets on its own ``select`` wins over
|
||||
this one."""
|
||||
|
||||
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)
|
||||
def resolve_group_defaults(cls, data):
|
||||
return merge_group_defaults(data)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples and
|
||||
group_size (the worker ``pool`` is configured per env, default elastic)."""
|
||||
"""Resolve per-env overrides: inherit group-level sampling and group_size (the
|
||||
worker ``pool`` is configured per env, default elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for source in self.source:
|
||||
if "sampling" not in source.model_fields_set:
|
||||
@@ -395,8 +427,6 @@ class EvalSourcesConfig(BaseConfig):
|
||||
else:
|
||||
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
|
||||
source.sampling = EvalSamplingConfig(**merged)
|
||||
if "num_examples" not in source.model_fields_set:
|
||||
source.num_examples = self.num_examples
|
||||
if "group_size" not in source.model_fields_set:
|
||||
source.group_size = self.group_size
|
||||
return self
|
||||
|
||||
@@ -345,7 +345,7 @@ class ModelConfig(BaseModelConfig):
|
||||
"""Debugging knobs for the model and distributed training."""
|
||||
|
||||
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
|
||||
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
|
||||
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. In SFT the fused head computes the summed cross-entropy and its gradients chunk by chunk, holding one chunk's full-vocab logits at a time."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def trust_remote_code_only_with_hf(self):
|
||||
@@ -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."""
|
||||
|
||||
@@ -600,6 +603,41 @@ class IcePopLossConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
class PPOLossConfig(BaseConfig):
|
||||
type: Literal["ppo"] = "ppo"
|
||||
|
||||
ratio_low: float = Field(0.8, gt=0, le=1, allow_inf_nan=False)
|
||||
"""Lower ratio bound for the clipped surrogate."""
|
||||
|
||||
ratio_high: float = Field(1.2, ge=1, allow_inf_nan=False)
|
||||
"""Upper ratio bound for the clipped surrogate."""
|
||||
|
||||
max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False)
|
||||
"""Cap the unbounded side of the surrogate while preserving its gradient."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_max_importance_ratio(self):
|
||||
if self.max_importance_ratio < self.ratio_high:
|
||||
raise ValueError("max_importance_ratio must be at least ratio_high")
|
||||
return self
|
||||
|
||||
|
||||
class CISPOLossConfig(BaseConfig):
|
||||
type: Literal["cispo"] = "cispo"
|
||||
|
||||
ratio_low: float = Field(0.0, ge=0, le=1, allow_inf_nan=False)
|
||||
"""Lower bound for the detached importance weight; zero disables lower clipping."""
|
||||
|
||||
ratio_high: float = Field(5.0, ge=1, allow_inf_nan=False)
|
||||
"""Upper bound for the detached importance weight."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
|
||||
class CustomLossConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
@@ -610,7 +648,9 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | IcePopLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[
|
||||
IPOLossConfig | IcePopLossConfig | PPOLossConfig | CISPOLossConfig | CustomLossConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
|
||||
+10
-10
@@ -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.2.dev143",
|
||||
"verifiers[harbor]>=0.3.2.dev152",
|
||||
"renderers[multimodal]>=0.1.12.dev2",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
@@ -56,7 +56,7 @@ gpu = [
|
||||
"torchvision ; sys_platform == 'linux'",
|
||||
"torchaudio ; sys_platform == 'linux'",
|
||||
"torchdata>=0.11.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.29.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.30.0 ; sys_platform == 'linux'",
|
||||
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
|
||||
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
|
||||
"torchtitan ; sys_platform == 'linux'",
|
||||
@@ -146,9 +146,9 @@ override-dependencies = [
|
||||
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
|
||||
"apache-tvm-ffi==0.1.11",
|
||||
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
|
||||
# vLLM 0.29.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
|
||||
# vLLM 0.30.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
|
||||
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
|
||||
"nvidia-cutlass-dsl==4.6.2",
|
||||
"nvidia-cutlass-dsl==4.7.1",
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.13.0",
|
||||
"openenv-core",
|
||||
@@ -217,10 +217,10 @@ requires-dist = ["nixl-cu13==0.10.1"]
|
||||
# so resolve that variant without installing both runtime packages.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "nvidia-cutlass-dsl"
|
||||
version = "4.6.2"
|
||||
version = "4.7.1"
|
||||
requires-dist = [
|
||||
"nvidia-cutlass-dsl-libs-base==4.6.2",
|
||||
"nvidia-cutlass-dsl-libs-cu13==4.6.2",
|
||||
"nvidia-cutlass-dsl-libs-base==4.7.1",
|
||||
"nvidia-cutlass-dsl-libs-cu13==4.7.1",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
@@ -274,8 +274,8 @@ vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
|
||||
+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 ==="
|
||||
|
||||
@@ -65,7 +65,7 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
Source lists are set in TOML. The CLI has no list-index paths (`--orchestrator.eval.source.0.env.taskset.id` does not parse); a whole list can be passed as JSON (`--orchestrator.eval.source '[{"env": {"taskset": {"id": "reverse-text"}}}]'`), which replaces the list wholesale.
|
||||
|
||||
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server). The `eval` entrypoint flattens it further: `[[source]]`, `[client]`, `[concurrency]`, `num_examples`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -r N -c N -m MODEL` (see the `eval` skill).
|
||||
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server). The `eval` entrypoint flattens it further: `[[source]]`, `[client]`, `[concurrency]`, `[select]`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -s -r N -c N -m MODEL` (see the `eval` skill).
|
||||
|
||||
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
|
||||
|
||||
|
||||
+38
-4
@@ -23,18 +23,20 @@ uv run eval @ eval.toml --monitors.prime # stream eac
|
||||
|
||||
- Config: `EvalConfig` (`packages/prime-rl-configs/src/prime_rl/configs/eval.py`); `uv run eval -h` lists the fields.
|
||||
- Entrypoint: `src/prime_rl/entrypoints/eval.py`; implementation `src/prime_rl/eval/eval.py`, shared engine `src/prime_rl/eval/runner.py`.
|
||||
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `num_examples`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. They cannot be combined with a TOML that defines `[[source]]` blocks.
|
||||
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `select.limit`, `-s` `select.shuffle`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. They cannot be combined with a TOML that defines `[[source]]` blocks.
|
||||
- Concurrency: an API exposes no vLLM `/metrics`, so run pinned there; against `uv run inference` set `min_inflight < max_inflight` in `[concurrency]` to adapt to KV usage.
|
||||
- Env servers: spawned per source on OS-assigned ports (published to `configs/attempt_N/resolved/envs/eval/<name>.address`) unless the source sets `serve.address`.
|
||||
- Ready-made configs: `configs/debug/eval/*.toml`, one per shape (single turn, multi turn, resume, multi env, aime2026, tb2).
|
||||
|
||||
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `num_examples`, `group_size`, `sampling` override the top level):
|
||||
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `select`, `group_size`, `sampling` override the top level):
|
||||
|
||||
```toml
|
||||
model = "Qwen/Qwen3-4B"
|
||||
num_examples = 32
|
||||
group_size = 4
|
||||
|
||||
[select]
|
||||
limit = 32
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
@@ -48,6 +50,38 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
## Select tasks
|
||||
|
||||
`select` picks which tasks of a source's taskset run. The steps apply in a fixed order: `include` and `exclude` (by `idx` position, `ids`, `keys` or `names`), then `shuffle` (under `seed`, default 0), `skip`, `limit`. Set it once for every source of a group (`[select]` in an eval TOML, `[orchestrator.eval.select]`, `[orchestrator.train.select]`), or per source (`select.limit = 50` in a `[[source]]`); a source's own fields win.
|
||||
|
||||
```bash
|
||||
uv run eval gsm8k -n 50 # the first 50 tasks
|
||||
uv run eval gsm8k -n 50 -s # a random subset of 50 (same tasks every run)
|
||||
uv run eval gsm8k -n 50 -s --select.seed 1 # another random subset
|
||||
uv run eval gsm8k --select.include.idx 0:10,42 # tasks by position (ints and Python slices)
|
||||
uv run eval terminal-bench-2 --select.include.names '["fix-git"]' # tasks by name; `ids` and `keys` work the same
|
||||
uv run eval terminal-bench-2 --select.exclude.keys '["<task.key>"]' # drop known-broken tasks (keys are on every trace)
|
||||
```
|
||||
|
||||
Disjoint train/test splits from one taskset:
|
||||
|
||||
```toml
|
||||
# contiguous: eval on the first 100 tasks, train on the rest
|
||||
[[orchestrator.eval.source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
select.include.idx = [":100"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
select.exclude.idx = [":100"]
|
||||
|
||||
# random: the same shuffle on both sides; eval takes 100, train skips them
|
||||
# eval: select.shuffle = true, select.limit = 100
|
||||
# train: select.shuffle = true, select.skip = 100
|
||||
```
|
||||
|
||||
The shuffle comes before `skip` and `limit`, so a larger `limit` extends the same selection: resuming a `-n 50 -s` run with `-n 100` keeps the 50 landed tasks and adds 50 more.
|
||||
|
||||
## Monitor an eval
|
||||
|
||||
Run dir: `output_dir / run.name` (auto `<envs>--<model>--<short-id>`; `ls -t outputs | head -1` finds the latest). The console stays quiet while the eval runs; everything is in the files and the dashboard (`dashboard` skill).
|
||||
@@ -72,4 +106,4 @@ The progress line in `eval.log` counts live rollouts by phase (`- boot 1 · runn
|
||||
|
||||
Metrics live under `eval/<env>/all/<agent>/…` (`reward/mean`, `is_truncated/mean` — raise `sampling.max_completion_tokens` when high, `has_error/mean`, the taskset's own metrics). Validate a result by reading a few traces in the dashboard rather than trusting the mean alone.
|
||||
|
||||
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed (`num_examples`/`group_size` may change, the model, sampling and env config may not). Env servers are children of the eval process and exit with it.
|
||||
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed. Any config may be overridden on resume (`select`/`group_size` change what is owed); keep the model, sampling and env config the same to keep the landed episodes comparable. Env servers are children of the eval process and exit with it.
|
||||
|
||||
@@ -272,13 +272,14 @@ def eval_env(config: dict) -> str | None:
|
||||
|
||||
|
||||
def source_total_episodes(source: dict) -> int | None:
|
||||
"""What one ``[[source]]`` will produce, from its config alone: ``num_examples = -1``
|
||||
means the whole taskset, unknown up front unless the source names its tasks."""
|
||||
tasks = ((source.get("env") or {}).get("taskset") or {}).get("tasks")
|
||||
count = source.get("num_examples") or -1
|
||||
if count < 0 and not tasks:
|
||||
"""What one ``[[source]]`` will produce, from its config alone: without a
|
||||
``select.limit`` the count is unknown up front unless the source names its tasks."""
|
||||
taskset = (source.get("env") or {}).get("taskset") or {}
|
||||
limit = (source.get("select") or {}).get("limit")
|
||||
tasks = taskset.get("tasks")
|
||||
if limit is None and not tasks:
|
||||
return None
|
||||
return (count if count >= 0 else len(tasks)) * (source.get("group_size") or 1)
|
||||
return (limit if limit is not None else len(tasks)) * (source.get("group_size") or 1)
|
||||
|
||||
|
||||
def eval_totals(config: dict) -> dict[str, int | None]:
|
||||
@@ -294,7 +295,7 @@ def eval_total_episodes(config: dict) -> int | None:
|
||||
if sources:
|
||||
totals = [source_total_episodes(s) for s in sources]
|
||||
return None if any(t is None for t in totals) else sum(totals) or None
|
||||
return (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None
|
||||
return ((config.get("select") or {}).get("limit") or 0) * (config.get("num_rollouts") or 0) or None
|
||||
|
||||
|
||||
def run_meta(run_dir: Path) -> dict:
|
||||
|
||||
@@ -21,7 +21,7 @@ from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes, set_proc_title
|
||||
|
||||
USAGE = """\
|
||||
usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-r N] [-c N] [-m MODEL] [options]
|
||||
usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-s] [-r N] [-c N] [-m MODEL] [options]
|
||||
uv run eval @ eval.toml [options] multi-source runs ([[source]] blocks)
|
||||
uv run eval @ eval.toml --run.name <name> --resume resume an interrupted run
|
||||
|
||||
|
||||
@@ -21,8 +21,6 @@ def apply_shared_vllm_patches():
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
monkey_patch_deepseek_v4_allowed_layer_types()
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
monkey_patch_deepseek_v4_per_layer_rope()
|
||||
monkey_patch_deepseek_v4_bf16_o_proj()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
@@ -185,110 +183,6 @@ def monkey_patch_kv_xfer_finished_tolerate_freed():
|
||||
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_bf16_o_proj():
|
||||
"""Run DeepSeek V4's output projection in bf16 when the weights are not FP8.
|
||||
|
||||
vLLM's DeepSeek V4 output projection is FP8-only. All three CUDA attention
|
||||
classes (``DeepseekV4FlashMLAAttention``,
|
||||
``DeepseekV4FlashInferMLAAttention``, ``DeepseekV4FlashInferSM120Attention``)
|
||||
implement ``_o_proj`` by calling ``deep_gemm_fp8_o_proj``
|
||||
(``vllm/models/deepseek_v4/nvidia/ops/o_proj.py``), which dereferences
|
||||
``wo_a.weight_scale``, falling back to ``wo_a.weight_scale_inv``, and hands
|
||||
the result to DeepGEMM's ``fp8_einsum``. There is no branch on quant config
|
||||
or weight dtype, and ``_o_proj`` is an ``@abstractmethod`` dispatched purely
|
||||
by platform subclass, so no attention backend routes around it. A bf16
|
||||
checkpoint has neither attribute and therefore fails with
|
||||
``AttributeError: 'ColumnParallelLinear' object has no attribute
|
||||
'weight_scale_inv'``.
|
||||
|
||||
Quantizing is not an answer, because nothing quantizes by default:
|
||||
``[inference.vllm] quantization`` is unset, which leaves vLLM to infer the
|
||||
scheme from the checkpoint. bf16 DeepSeek V4 checkpoints are a first-class
|
||||
artifact here, written by ``tools/convert_fp8_to_bf16.py``,
|
||||
``tools/convert_dcp_to_bf16.py``, and trainer exports, and they carry no
|
||||
scales for the op to find. Passing ``--quantization fp8_per_block`` does
|
||||
produce a correct ``weight_scale_inv`` and is a genuine alternative on
|
||||
hardware whose DeepGEMM build has block-scaled FP8 kernels, but it changes
|
||||
the served numerics, so it is a deployment decision rather than a fix for
|
||||
serving the bf16 weights as given.
|
||||
|
||||
Only the unquantized case is redirected: an FP8 weight keeps using vLLM's own
|
||||
kernel, so a real FP8-serialized checkpoint behaves exactly as before. The
|
||||
condition is the weight dtype rather than the presence of
|
||||
``weight_scale_inv``, so a checkpoint that *is* quantized but whose scales
|
||||
ended up in the wrong layout still fails loudly instead of being silently
|
||||
rerouted.
|
||||
|
||||
The replacement mirrors the Triton kernel's arithmetic
|
||||
(``vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py:95-105``)
|
||||
without the quantization step. The trailing ``rope_dim`` channels of each head
|
||||
carry an inverse RoPE over interleaved pairs, with ``cos_sin_cache`` holding
|
||||
``rope_dim // 2`` cosines followed by the matching sines:
|
||||
|
||||
y[even] = x[even] * cos + x[odd] * sin
|
||||
y[odd] = x[odd] * cos - x[even] * sin
|
||||
|
||||
The remaining ``nope_dim`` channels pass through. The projection is the same
|
||||
grouped contraction ``fp8_einsum`` performs, with the group axis recovered by
|
||||
reshaping: head ``g * heads_per_group + i`` belongs to group ``g`` at offset
|
||||
``i * head_dim``, matching the kernel's own
|
||||
``g = pid_gh // heads_per_group`` indexing.
|
||||
|
||||
Rotation is computed in fp32 and the contraction runs in bf16, whose CUDA
|
||||
matmuls accumulate in fp32. That is strictly more accurate than the FP8 path
|
||||
it replaces, and it avoids materializing an fp32 copy of the attention output.
|
||||
"""
|
||||
from vllm.models.deepseek_v4.nvidia import flashinfer_sparse, flashmla
|
||||
from vllm.models.deepseek_v4.nvidia.ops import o_proj as o_proj_module
|
||||
|
||||
original_o_proj = o_proj_module.deep_gemm_fp8_o_proj
|
||||
if getattr(original_o_proj, "_prime_rl_has_bf16_fallback", False):
|
||||
return
|
||||
|
||||
def _inverse_rope(o, positions, cos_sin_cache, rope_dim):
|
||||
num_tokens, num_heads, head_dim = o.shape
|
||||
half_rope = rope_dim // 2
|
||||
cos_sin = cos_sin_cache[positions].float()
|
||||
cos = cos_sin[:, :half_rope].view(num_tokens, 1, half_rope)
|
||||
sin = cos_sin[:, half_rope:].view(num_tokens, 1, half_rope)
|
||||
|
||||
rotated = o[:, :, head_dim - rope_dim :].float().reshape(num_tokens, num_heads, half_rope, 2)
|
||||
even, odd = rotated[..., 0], rotated[..., 1]
|
||||
pairs = torch.stack((even * cos + odd * sin, odd * cos - even * sin), dim=-1)
|
||||
|
||||
out = o.clone()
|
||||
out[:, :, head_dim - rope_dim :] = pairs.reshape(num_tokens, num_heads, rope_dim).to(o.dtype)
|
||||
return out
|
||||
|
||||
def _patched_o_proj(o, positions, cos_sin_cache, wo_a, wo_b, *, n_groups, heads_per_group, **kwargs):
|
||||
if wo_a.weight.dtype == torch.float8_e4m3fn:
|
||||
return original_o_proj(
|
||||
o,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
wo_a,
|
||||
wo_b,
|
||||
n_groups=n_groups,
|
||||
heads_per_group=heads_per_group,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
x = _inverse_rope(o, positions, cos_sin_cache, kwargs["rope_dim"])
|
||||
x = x.reshape(o.shape[0], n_groups, heads_per_group * o.shape[-1])
|
||||
weight = wo_a.weight.view(n_groups, kwargs["o_lora_rank"], -1)
|
||||
z = torch.einsum("tgr,gdr->tgd", x, weight)
|
||||
return wo_b(z.flatten(1))
|
||||
|
||||
_patched_o_proj._prime_rl_has_bf16_fallback = True
|
||||
o_proj_module.deep_gemm_fp8_o_proj = _patched_o_proj
|
||||
|
||||
# Both attention modules did `from ...ops.o_proj import deep_gemm_fp8_o_proj` at
|
||||
# import time, so patching the defining module alone would not reach the names
|
||||
# their `_o_proj` methods actually call.
|
||||
flashmla.deep_gemm_fp8_o_proj = _patched_o_proj
|
||||
flashinfer_sparse.deep_gemm_fp8_o_proj = _patched_o_proj
|
||||
|
||||
|
||||
def monkey_patch_nano_v3_reasoning_parser():
|
||||
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
|
||||
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
|
||||
@@ -795,126 +689,3 @@ def monkey_patch_dp_coordinator_startup_timeout():
|
||||
zmq_addr_pipe.close()
|
||||
|
||||
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
|
||||
|
||||
|
||||
_DEEPSEEK_V4_YARN_ROPE_TYPES = frozenset({"yarn", "deepseek_yarn", "deepseek_llama_scaling"})
|
||||
|
||||
|
||||
def _deepseek_v4_rope_parameters(rope_parameters, *, compress_ratio, max_position_embeddings):
|
||||
"""Flat, single-layer rope parameters for `build_deepseek_v4_rope`.
|
||||
|
||||
Handles both on-disk schemas. The real checkpoint ships a flat legacy `rope_scaling`, which
|
||||
vLLM's config shim normalizes in place. HF's own `DeepseekV4Config` nests the parameters
|
||||
under `main`/`compress` rope-type labels instead, and so does this repo's port. vLLM's shim
|
||||
cannot read that: `is_rope_parameters_nested` only recognizes nesting by *attention* layer
|
||||
type, so transformers leaves the sub-dicts alone and injects a top-level
|
||||
`rope_type="default"` beside them. Upstream then builds unscaled RoPE for every layer and
|
||||
hands `get_rope` a cache key containing a dict, which is unhashable. Selecting the branch
|
||||
this layer wants resolves both. Upstream picks the base from `config.rope_theta` /
|
||||
`config.compress_rope_theta` on its own either way.
|
||||
"""
|
||||
rope_parameters = rope_parameters if isinstance(rope_parameters, dict) else {}
|
||||
# `compress_ratio` is already clamped to >= 1 by the caller, so <= 1 is "no compressor",
|
||||
# i.e. the reference's `else` branch. vLLM lumps the MTP layers in here too.
|
||||
is_sliding = compress_ratio <= 1
|
||||
|
||||
if any(isinstance(value, dict) for value in rope_parameters.values()):
|
||||
label = "main" if is_sliding else "compress"
|
||||
branch = rope_parameters.get(label)
|
||||
if not isinstance(branch, dict):
|
||||
raise ValueError(
|
||||
f"DeepSeek V4 rope_parameters is nested by rope type but has no {label!r} "
|
||||
f"sub-dict; found {sorted(rope_parameters)}."
|
||||
)
|
||||
parameters = dict(branch)
|
||||
else:
|
||||
parameters = dict(rope_parameters)
|
||||
|
||||
rope_type = parameters.get("rope_type", parameters.get("type", "default"))
|
||||
if is_sliding or rope_type not in _DEEPSEEK_V4_YARN_ROPE_TYPES:
|
||||
# Plain RoPE, written as YaRN with `factor=1` rather than as `rope_type="default"`.
|
||||
# The table is the same either way, since `_compute_inv_freq`'s interpolated and
|
||||
# extrapolated frequencies coincide at `factor=1` and `yarn_get_mscale` returns 1.0,
|
||||
# but `"default"` would route `get_rope` to a plain `RotaryEmbedding`, whose cache
|
||||
# follows the ambient dtype and so fails the fp32 assertion in
|
||||
# `vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py`.
|
||||
# `original_max_position_embeddings` is widened because the cache is
|
||||
# `original_max * factor` rows and must still span the context.
|
||||
rope_type = "yarn"
|
||||
parameters["factor"] = 1
|
||||
parameters["original_max_position_embeddings"] = max_position_embeddings
|
||||
parameters["rope_type"] = rope_type
|
||||
return parameters
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_per_layer_rope():
|
||||
"""Give each DeepSeek V4 layer the RoPE its reference implementation uses.
|
||||
|
||||
DeepSeek ships the reference inside the checkpoint we serve, at
|
||||
https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731/tree/main/inference. Its
|
||||
`model.py:481-485` picks the frequencies per layer:
|
||||
|
||||
if self.compress_ratio:
|
||||
original_seq_len, rope_theta = args.original_seq_len, args.compress_rope_theta
|
||||
else:
|
||||
# disable YaRN and use base rope_theta in pure sliding-window attention
|
||||
original_seq_len, rope_theta = 0, args.rope_theta
|
||||
|
||||
and `precompute_freqs_cis` (`model.py:206-235`) applies the NTK-by-parts ramp only when
|
||||
`original_seq_len > 0`. So a pure sliding-window layer gets plain RoPE at `rope_theta` and
|
||||
every compressed layer gets YaRN at `compress_rope_theta`. HF's `DeepseekV4Config` splits its
|
||||
`rope_parameters` into `main`/`compress` for the same reason, and so does this repo's trainer.
|
||||
|
||||
`vllm/models/deepseek_v4/common/rope.py`'s `build_deepseek_v4_rope` branches the base on
|
||||
`compress_ratio` but never the scaling, so on the real checkpoint it hands YaRN to layers 0
|
||||
and 1 as well. No config value can correct that: `rope_type` is one global field there.
|
||||
So this patch resolves `rope_parameters` per layer instead, which also gives upstream a
|
||||
schema and a dtype it can handle; see `_deepseek_v4_rope_parameters` above.
|
||||
|
||||
Measured against the reference's own frequencies, at the test's `factor=16`,
|
||||
`original_max_position_embeddings=4096` geometry, this takes the sliding layers from 5.1e-03
|
||||
max absolute error to 6e-08, the float32 residual the compressed layers already have. The
|
||||
rope tests in `tests/unit/train/models/test_deepseek_v4.py` are that comparison, over both
|
||||
on-disk schemas and both scaled and unscaled configs.
|
||||
|
||||
Note that nothing in vLLM's DeepSeek V4 calls the module's `forward`; every consumer reads
|
||||
`cos_sin_cache` and hands it to a fused kernel. The class choice is therefore about the
|
||||
cache's dtype and row count, not about which channels the module would rotate.
|
||||
|
||||
Remove this patch once the pin includes vllm-project/vllm#54815, which ships in 0.29.1.
|
||||
"""
|
||||
from vllm.models.deepseek_v4.common import rope as dsv4_rope
|
||||
|
||||
original_build = dsv4_rope.build_deepseek_v4_rope
|
||||
|
||||
if getattr(original_build, "_prime_rl_matches_deepseek_reference", False):
|
||||
return
|
||||
|
||||
def _patched_build(config, *, head_dim, rope_head_dim, max_position_embeddings, compress_ratio):
|
||||
# Swapping a copy in also spares `config.rope_parameters` upstream's in-place mutation,
|
||||
# which otherwise leaves the last-built layer's `rope_theta` on the shared config.
|
||||
original_parameters = config.rope_parameters
|
||||
config.rope_parameters = _deepseek_v4_rope_parameters(
|
||||
original_parameters,
|
||||
compress_ratio=compress_ratio,
|
||||
max_position_embeddings=max_position_embeddings,
|
||||
)
|
||||
try:
|
||||
return original_build(
|
||||
config,
|
||||
head_dim=head_dim,
|
||||
rope_head_dim=rope_head_dim,
|
||||
max_position_embeddings=max_position_embeddings,
|
||||
compress_ratio=compress_ratio,
|
||||
)
|
||||
finally:
|
||||
config.rope_parameters = original_parameters
|
||||
|
||||
_patched_build._prime_rl_matches_deepseek_reference = True
|
||||
dsv4_rope.build_deepseek_v4_rope = _patched_build
|
||||
|
||||
# `attention.py` imports the builder into its own namespace, so the defining module alone
|
||||
# would not reach the already-bound reference.
|
||||
from vllm.models.deepseek_v4 import attention as dsv4_attention
|
||||
|
||||
dsv4_attention.build_deepseek_v4_rope = _patched_build
|
||||
|
||||
@@ -26,7 +26,7 @@ from prime_rl.inference.patches import (
|
||||
)
|
||||
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.29 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
# Still needed in vLLM 0.30 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -20,10 +20,8 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import random
|
||||
import time
|
||||
from collections.abc import Callable, Iterator, Sequence
|
||||
from itertools import islice
|
||||
from pathlib import Path
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
@@ -41,11 +39,6 @@ from prime_rl.utils.pathing import env_address_file
|
||||
# before serving.
|
||||
ENV_SERVER_STARTUP_TIMEOUT = 600.0
|
||||
|
||||
# Fixed seed for shuffle=True sources: the finite taskset is shuffled once at
|
||||
# startup and the shuffled order is fixed for the whole run (train curricula and
|
||||
# eval selection both consume it).
|
||||
TASKSET_SHUFFLE_SEED = 42
|
||||
|
||||
|
||||
async def wait_for_address(path: Path, timeout: float) -> str:
|
||||
"""The address a launcher-managed env server published, polling for the file the
|
||||
@@ -74,11 +67,11 @@ class Env:
|
||||
is None."""
|
||||
self.sampling_args: dict = {}
|
||||
self.num_tasks: int | None = 0
|
||||
"""Task count; ``None`` means the taskset is infinite."""
|
||||
"""Task count; ``None`` means the selected tasks never end."""
|
||||
self.tasks: Iterator[vf.Task] | None = None
|
||||
"""The env's tasks, client-side, set at ``start()``. A finite taskset is
|
||||
materialized (``num_tasks`` is its count) and iterated from there; an infinite
|
||||
one streams off its generator. Consumed once — by ``TrainSource`` (train) or
|
||||
"""The env's selected tasks (``select``), client-side, set at
|
||||
``start()``. A bounded selection is materialized (``num_tasks`` is its count)
|
||||
and iterated from there; an unbounded one streams off the taskset. Consumed once — by ``TrainSource`` (train) or
|
||||
``EvalEnv.start`` (eval)."""
|
||||
self._env_client: EnvClient | None = None
|
||||
|
||||
@@ -102,19 +95,15 @@ class Env:
|
||||
# The server may still be coming up (the launcher spawns it concurrently with
|
||||
# the orchestrator), so poll until it answers.
|
||||
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
|
||||
taskset = vf.load_taskset(self.config.env.taskset)
|
||||
if type(taskset).INFINITE:
|
||||
if self.config.shuffle:
|
||||
raise ValueError(f"Env {self.name} has an infinite taskset — cannot shuffle it")
|
||||
self.tasks = iter(taskset)
|
||||
self.num_tasks = None
|
||||
else:
|
||||
taskset = vf.load_taskset(self.config.env.taskset).select(self.config.select)
|
||||
if taskset.bounded:
|
||||
# Materialize off the event loop — iterating may pull a dataset.
|
||||
materialized = await asyncio.to_thread(lambda: list(taskset))
|
||||
if self.config.shuffle:
|
||||
random.Random(TASKSET_SHUFFLE_SEED).shuffle(materialized)
|
||||
self.tasks = iter(materialized)
|
||||
self.num_tasks = len(materialized)
|
||||
else:
|
||||
self.tasks = iter(taskset)
|
||||
self.num_tasks = None
|
||||
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
|
||||
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
|
||||
|
||||
@@ -186,12 +175,10 @@ class EvalEnv(Env):
|
||||
|
||||
async def start(self) -> None:
|
||||
await super().start()
|
||||
n = self.config.num_examples
|
||||
if self.num_tasks is None and n < 0:
|
||||
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
|
||||
if self.num_tasks is None:
|
||||
raise ValueError(f"Eval env {self.name} has an infinite taskset — set select.limit to bound it")
|
||||
# A fixed eval set, pulled off the tasks once and reused every epoch.
|
||||
tasks = list(self.tasks) if n < 0 else list(islice(self.tasks, n))
|
||||
self.examples = tasks
|
||||
self.examples = list(self.tasks)
|
||||
|
||||
|
||||
EnvT = TypeVar("EnvT", bound=Env)
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -31,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 (
|
||||
@@ -1088,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).
|
||||
@@ -1111,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
|
||||
|
||||
@@ -5,11 +5,15 @@ from typing import TypedDict
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.vlm import get_final_logit_softcapping
|
||||
|
||||
# Same as torch's cross entropy loss
|
||||
IGNORE_INDEX = -100
|
||||
|
||||
|
||||
class PrimeLmOutput(TypedDict, total=False):
|
||||
"""Output from LM head - a TypedDict so pytree can find tensors for FSDP2 hooks."""
|
||||
@@ -35,6 +39,13 @@ def cast_float_and_contiguous(output: PrimeLmOutput) -> PrimeLmOutput:
|
||||
|
||||
|
||||
class FusedOutputLinear(torch.nn.Linear):
|
||||
"""Chunked LM head that never materializes the full [N, V] logits.
|
||||
|
||||
With ``labels`` and no ``temperature`` it returns the summed cross-entropy over labels != IGNORE_INDEX
|
||||
as ``loss``, computing the gradients chunk by chunk in the forward pass (see ``_ChunkedCrossEntropySumFn``).
|
||||
With ``temperature`` it returns per-token ``logprobs`` and ``entropy``.
|
||||
"""
|
||||
|
||||
def __init__(self, in_features: int, out_features: int, chunk_size: int):
|
||||
super().__init__(in_features, out_features, bias=False)
|
||||
self.chunk_size = chunk_size
|
||||
@@ -47,11 +58,16 @@ class FusedOutputLinear(torch.nn.Linear):
|
||||
sampling_mask: Tensor | None = None,
|
||||
) -> PrimeLmOutput:
|
||||
assert labels is not None, "FusedOutputLinear requires labels for chunked logprob computation"
|
||||
assert temperature is not None, "FusedOutputLinear requires per-token temperatures"
|
||||
|
||||
b, s, h = hidden_states.shape
|
||||
hidden_states = hidden_states.reshape(b * s, h).contiguous()
|
||||
labels = labels.reshape(b * s).contiguous()
|
||||
|
||||
if temperature is None:
|
||||
assert sampling_mask is None, "sampling-mask replay requires per-token temperatures"
|
||||
loss = _ChunkedCrossEntropySumFn.apply(hidden_states, self.weight, labels, self.chunk_size)
|
||||
return PrimeLmOutput(loss=loss)
|
||||
|
||||
inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N]
|
||||
if sampling_mask is not None:
|
||||
sampling_mask = sampling_mask.reshape(b * s, sampling_mask.shape[-1]).contiguous()
|
||||
@@ -66,6 +82,9 @@ class FusedOutputLinear(torch.nn.Linear):
|
||||
|
||||
|
||||
class VanillaOutputLinear(torch.nn.Linear):
|
||||
"""LM head that returns the full logits, or with ``labels`` and no ``temperature`` the summed fp32
|
||||
cross-entropy over labels != IGNORE_INDEX as ``loss``."""
|
||||
|
||||
def __init__(self, in_features: int, out_features: int):
|
||||
super().__init__(in_features, out_features, bias=False)
|
||||
|
||||
@@ -76,9 +95,18 @@ class VanillaOutputLinear(torch.nn.Linear):
|
||||
temperature: Tensor | None = None,
|
||||
sampling_mask: Tensor | None = None,
|
||||
) -> PrimeLmOutput:
|
||||
# VanillaOutputLinear just returns logits. train.py applies temperature
|
||||
# scaling and sampling-mask replay.
|
||||
return PrimeLmOutput(logits=super().forward(hidden_states))
|
||||
logits = super().forward(hidden_states)
|
||||
if labels is not None and temperature is None:
|
||||
return PrimeLmOutput(loss=cross_entropy_sum(logits, labels))
|
||||
# train.py applies temperature scaling and sampling-mask replay to the logits.
|
||||
return PrimeLmOutput(logits=logits)
|
||||
|
||||
|
||||
def cross_entropy_sum(logits: Tensor, labels: Tensor) -> Tensor:
|
||||
"""Summed fp32 cross-entropy over labels != IGNORE_INDEX."""
|
||||
return F.cross_entropy(
|
||||
logits.view(-1, logits.shape[-1]).float(), labels.reshape(-1), ignore_index=IGNORE_INDEX, reduction="sum"
|
||||
)
|
||||
|
||||
|
||||
def _online_logsumexp_and_weighted_update(
|
||||
@@ -266,6 +294,71 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
return grad_hidden, grad_weight, None, None, None, None
|
||||
|
||||
|
||||
class _ChunkedCrossEntropySumFn(torch.autograd.Function):
|
||||
"""Summed cross-entropy over labels != IGNORE_INDEX, with the gradients computed during forward.
|
||||
|
||||
Per chunk of ``chunk_size`` tokens: one full-vocab logits GEMM, the loss, and the gradient
|
||||
(softmax minus one-hot) folded straight into ``grad_hidden`` and ``grad_weight``. Only one chunk's
|
||||
logits are alive at a time and backward does no recompute: it scales the stored gradients by the
|
||||
incoming scalar. That drops the head's matmul passes from four to three (forward logits, dX, dW).
|
||||
Same approach as torchtitan's ChunkedLossWrapper.
|
||||
|
||||
Backward only accepts a scalar upstream gradient (e.g. ``loss_sum / k``). Per-token weighted losses
|
||||
must pass a temperature and go through the logprob path instead.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def forward( # type: ignore[override]
|
||||
ctx,
|
||||
hidden: torch.Tensor, # [N, H]
|
||||
weight: torch.Tensor, # [V, H]
|
||||
labels: torch.Tensor, # [N], IGNORE_INDEX where the token has no loss
|
||||
chunk_size: int,
|
||||
) -> torch.Tensor:
|
||||
assert hidden.dim() == 2 and weight.dim() == 2 and labels.dim() == 1
|
||||
assert hidden.shape[0] == labels.shape[0] and hidden.shape[1] == weight.shape[1]
|
||||
assert chunk_size > 0
|
||||
|
||||
needs_hidden, needs_weight = ctx.needs_input_grad[0], ctx.needs_input_grad[1]
|
||||
grad_hidden = torch.empty_like(hidden) if needs_hidden else None
|
||||
grad_weight = torch.zeros_like(weight) if needs_weight else None
|
||||
loss = torch.zeros((), device=hidden.device, dtype=torch.float32)
|
||||
|
||||
for start in range(0, hidden.shape[0], chunk_size):
|
||||
end = min(start + chunk_size, hidden.shape[0])
|
||||
hidden_chunk = hidden[start:end]
|
||||
labels_chunk = labels[start:end]
|
||||
valid = labels_chunk != IGNORE_INDEX
|
||||
target = labels_chunk.clamp(min=0).unsqueeze(-1)
|
||||
|
||||
logits = (hidden_chunk @ weight.t()).float()
|
||||
logz = torch.logsumexp(logits, dim=-1)
|
||||
target_logits = logits.gather(1, target).squeeze(1)
|
||||
loss += torch.where(valid, logz - target_logits, 0.0).sum()
|
||||
|
||||
if needs_hidden or needs_weight:
|
||||
# dx(loss)/dx(logits) is softmax minus one-hot on valid rows and zero elsewhere so it reuses the logits buffer
|
||||
grad_logits = logits.sub_(logz.unsqueeze(-1)).exp_()
|
||||
grad_logits.scatter_add_(1, target, torch.full_like(target, -1, dtype=grad_logits.dtype))
|
||||
grad_logits = grad_logits.mul_(valid.unsqueeze(-1)).to(hidden.dtype)
|
||||
if needs_hidden:
|
||||
torch.mm(grad_logits, weight, out=grad_hidden[start:end])
|
||||
if needs_weight:
|
||||
grad_weight.addmm_(grad_logits.t(), hidden_chunk)
|
||||
|
||||
ctx.save_for_backward(grad_hidden, grad_weight)
|
||||
return loss
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_loss: torch.Tensor):
|
||||
grad_hidden, grad_weight = ctx.saved_tensors
|
||||
if grad_hidden is not None:
|
||||
grad_hidden = grad_hidden * grad_loss.to(grad_hidden.dtype)
|
||||
if grad_weight is not None:
|
||||
grad_weight = grad_weight * grad_loss.to(grad_weight.dtype)
|
||||
return grad_hidden, grad_weight, None, None
|
||||
|
||||
|
||||
def inject_prime_lm_head(
|
||||
model: nn.Module,
|
||||
chunk_size: int | None = None,
|
||||
@@ -279,7 +372,7 @@ def inject_prime_lm_head(
|
||||
Args:
|
||||
model: The model to wrap.
|
||||
chunk_size: When set to an int, uses FusedOutputLinear with sequence-token chunked
|
||||
logprob/entropy computation.
|
||||
loss/logprob/entropy computation.
|
||||
"""
|
||||
# Guards so we have nicer error messages when a non-standard model is used
|
||||
assert hasattr(model, "model"), f"model doesnt have backbone in model.model:\n{model}"
|
||||
|
||||
@@ -5,9 +5,11 @@ import torch.nn as nn
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.models.layers.lm_head import (
|
||||
IGNORE_INDEX,
|
||||
PrimeLmOutput,
|
||||
_online_logsumexp_and_weighted_update,
|
||||
_patch_model_forward,
|
||||
cross_entropy_sum,
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -26,14 +28,21 @@ class GemmaFusedOutputLinear(torch.nn.Linear):
|
||||
sampling_mask: Tensor | None = None,
|
||||
) -> PrimeLmOutput:
|
||||
assert labels is not None, "GemmaFusedOutputLinear requires labels for chunked logprob computation"
|
||||
assert temperature is not None, "GemmaFusedOutputLinear requires per-token temperatures"
|
||||
assert sampling_mask is None, "sampling-mask replay is not supported with Gemma softcapped lm_heads"
|
||||
|
||||
b, s, h = hidden_states.shape
|
||||
hidden_states = hidden_states.reshape(b * s, h).contiguous()
|
||||
labels = labels.reshape(b * s).contiguous()
|
||||
inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N]
|
||||
|
||||
if temperature is None:
|
||||
# Summed cross-entropy through the logprob path; IGNORE_INDEX rows are masked at the sum.
|
||||
inv_t = torch.ones(b * s, device=hidden_states.device, dtype=torch.float32)
|
||||
logprobs, _ = _GemmaChunkedLogProbEntropyFn.apply(
|
||||
hidden_states, self.weight, labels, inv_t, self.chunk_size, self.softcap
|
||||
)
|
||||
return PrimeLmOutput(loss=-logprobs[labels != IGNORE_INDEX].sum())
|
||||
|
||||
inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N]
|
||||
logprobs, entropy = _GemmaChunkedLogProbEntropyFn.apply(
|
||||
hidden_states, self.weight, labels, inv_t, self.chunk_size, self.softcap
|
||||
)
|
||||
@@ -57,6 +66,8 @@ class GemmaVanillaOutputLinear(torch.nn.Linear):
|
||||
) -> PrimeLmOutput:
|
||||
logits = super().forward(hidden_states)
|
||||
logits = self.softcap * torch.tanh(logits / self.softcap)
|
||||
if labels is not None and temperature is None:
|
||||
return PrimeLmOutput(loss=cross_entropy_sum(logits, labels))
|
||||
return PrimeLmOutput(logits=logits)
|
||||
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
+144
-65
@@ -6,7 +6,14 @@ from beartype import beartype as typechecker
|
||||
from jaxtyping import Bool, Float, Int, jaxtyped
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, IcePopLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.configs.trainer import (
|
||||
CISPOLossConfig,
|
||||
CustomLossConfig,
|
||||
IcePopLossConfig,
|
||||
IPOLossConfig,
|
||||
LossConfig,
|
||||
PPOLossConfig,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import sampling_replay_mask
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
@@ -39,7 +46,7 @@ class LossOutputs:
|
||||
|
||||
class Loss(Protocol):
|
||||
"""Interface for the config-initialized rl loss objects built by
|
||||
``setup_rl_loss_fn``: ``IPOLoss``, ``IcePopLoss`` and ``CustomLoss``."""
|
||||
``setup_rl_loss_fn``."""
|
||||
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs: ...
|
||||
|
||||
@@ -125,54 +132,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 +204,88 @@ 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)
|
||||
|
||||
|
||||
class PPOLoss:
|
||||
"""Token-level PPO clipped surrogate with bounded importance weights."""
|
||||
|
||||
def __init__(self, config: PPOLossConfig):
|
||||
self.config = config
|
||||
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs:
|
||||
config = self.config
|
||||
logprobs = inputs.trainer_logprobs[inputs.loss_mask]
|
||||
log_ratio = logprobs - inputs.inference_logprobs[inputs.loss_mask]
|
||||
advantages = config.adv_tau * inputs.advantages[inputs.loss_mask]
|
||||
|
||||
ratio = _capped_importance_ratio(log_ratio, config.max_importance_ratio)
|
||||
clipped_ratio = ratio.clamp(config.ratio_low, config.ratio_high)
|
||||
per_token_loss = -torch.minimum(advantages * ratio, advantages * clipped_ratio)
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights[inputs.loss_mask]
|
||||
|
||||
clipped = ((advantages > 0) & (log_ratio.detach() > log_ratio.new_tensor(config.ratio_high).log())) | (
|
||||
(advantages < 0) & (log_ratio.detach() < log_ratio.new_tensor(config.ratio_low).log())
|
||||
)
|
||||
metrics = {
|
||||
"is_clipped": clipped.sum() / max(clipped.numel(), 1),
|
||||
"ratio_capped": (log_ratio.detach() > log_ratio.new_tensor(config.max_importance_ratio).log()).sum()
|
||||
/ max(log_ratio.numel(), 1),
|
||||
}
|
||||
return LossOutputs(loss=per_token_loss.sum(), metrics=metrics)
|
||||
|
||||
|
||||
class CISPOLoss:
|
||||
"""CISPO uses a detached clipped importance weight on the current logprob."""
|
||||
|
||||
def __init__(self, config: CISPOLossConfig):
|
||||
self.config = config
|
||||
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs:
|
||||
config = self.config
|
||||
logprobs = inputs.trainer_logprobs[inputs.loss_mask]
|
||||
log_ratio = logprobs - inputs.inference_logprobs[inputs.loss_mask]
|
||||
advantages = config.adv_tau * inputs.advantages[inputs.loss_mask]
|
||||
|
||||
detached_log_ratio = log_ratio.detach()
|
||||
log_ratio_high = log_ratio.new_tensor(config.ratio_high).log()
|
||||
clipped_log_ratio = detached_log_ratio.clamp(max=log_ratio_high)
|
||||
is_clipped = detached_log_ratio > log_ratio_high
|
||||
if config.ratio_low:
|
||||
log_ratio_low = log_ratio.new_tensor(config.ratio_low).log()
|
||||
clipped_log_ratio = clipped_log_ratio.clamp(min=log_ratio_low)
|
||||
is_clipped = is_clipped | (detached_log_ratio < log_ratio_low)
|
||||
importance_weight = clipped_log_ratio.exp()
|
||||
|
||||
per_token_loss = -importance_weight * advantages * logprobs
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights[inputs.loss_mask]
|
||||
|
||||
metrics = {
|
||||
"is_clipped": is_clipped.sum() / max(is_clipped.numel(), 1),
|
||||
}
|
||||
return LossOutputs(loss=per_token_loss.sum(), metrics=metrics)
|
||||
|
||||
@@ -222,39 +299,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)
|
||||
@@ -298,6 +373,10 @@ def setup_rl_loss_fn(loss_config: LossConfig) -> Loss:
|
||||
return IPOLoss(loss_config)
|
||||
case IcePopLossConfig():
|
||||
return IcePopLoss(loss_config)
|
||||
case PPOLossConfig():
|
||||
return PPOLoss(loss_config)
|
||||
case CISPOLossConfig():
|
||||
return CISPOLoss(loss_config)
|
||||
case _:
|
||||
raise TypeError(f"Unsupported RL loss config: {type(loss_config).__name__}")
|
||||
|
||||
|
||||
@@ -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,
|
||||
is_tt_moe_model,
|
||||
get_global_moe_stats,
|
||||
is_tt_moe_model,
|
||||
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")
|
||||
|
||||
@@ -362,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
|
||||
@@ -390,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,
|
||||
@@ -444,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,
|
||||
@@ -500,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)
|
||||
@@ -528,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
|
||||
|
||||
@@ -6,8 +6,6 @@ import asyncio
|
||||
from contextlib import nullcontext
|
||||
from datetime import timedelta
|
||||
|
||||
from torch.nn import CrossEntropyLoss
|
||||
|
||||
# Import environment before any other imports
|
||||
# ruff: noqa: I001
|
||||
|
||||
@@ -21,6 +19,7 @@ from prime_rl.configs.trainer import CheckpointConfig
|
||||
from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender
|
||||
from prime_rl.utils.cp import setup_context_parallel, setup_cp_params, shard_for_cp
|
||||
from prime_rl.trainer.lora import get_lora_state
|
||||
from prime_rl.trainer.models.layers.lm_head import IGNORE_INDEX
|
||||
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
|
||||
from prime_rl.utils.logger import format_time, setup_logger
|
||||
from prime_rl.trainer.optim import setup_optimizer
|
||||
@@ -279,39 +278,21 @@ def train(config: SFTConfig):
|
||||
|
||||
token_count = loss_mask.sum(dtype=torch.int64)
|
||||
|
||||
# Labels without a temperature make the LM head return the summed cross-entropy directly.
|
||||
labels = target_ids.masked_fill(~loss_mask, IGNORE_INDEX)
|
||||
|
||||
with maybe_activation_offloading(config.model.ac_offloading):
|
||||
if isinstance(config.model.fused_lm_head_token_chunk_size, int):
|
||||
# Same path as the RL trainer: the chunked LM head computes per-token
|
||||
# logprobs without materializing the [N, V] logits, and per-token
|
||||
# cross-entropy is the negative target logprob.
|
||||
temperature = torch.ones_like(target_ids, dtype=torch.float32)
|
||||
out = forward(
|
||||
model,
|
||||
input_ids,
|
||||
position_ids,
|
||||
seq_lens=seq_lens,
|
||||
labels=target_ids,
|
||||
temperature=temperature,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_type_ids,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
loss_sum = -out["logprobs"][loss_mask].sum()
|
||||
else:
|
||||
out = forward(
|
||||
model,
|
||||
input_ids,
|
||||
position_ids,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_type_ids,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
logits = out["logits"]
|
||||
B, L, V = logits.shape
|
||||
token_loss = CrossEntropyLoss(reduction="none")(logits.view(-1, V), target_ids.view(-1)).view(B, L)
|
||||
loss_sum = token_loss[loss_mask].sum()
|
||||
del logits
|
||||
out = forward(
|
||||
model,
|
||||
input_ids,
|
||||
position_ids,
|
||||
seq_lens=seq_lens,
|
||||
labels=labels,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_type_ids,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
loss_sum = out["loss"]
|
||||
|
||||
del out
|
||||
return loss_sum, token_count
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest() -> None
|
||||
_record("math", "m0"),
|
||||
_record("math", "m0"), # a third rollout of m0 exceeds group_size 2
|
||||
_record("math", "m1"),
|
||||
_record("math", "m9"), # no longer selected (num_examples shrank)
|
||||
_record("math", "m9"), # no longer selected (select.limit shrank)
|
||||
_record("code", "c0", ok=False), # errored: owed again
|
||||
]
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -193,6 +193,12 @@ def test_icepop_is_an_optional_loss_with_validated_ratio_bounds():
|
||||
with pytest.raises(ValidationError, match="ratio_low must not exceed ratio_high"):
|
||||
TrainerConfig.model_validate({"loss": {"type": "icepop", "ratio_low": 5.0, "ratio_high": 0.2}})
|
||||
|
||||
assert TrainerConfig.model_validate({"loss": {"type": "ppo"}}).loss.type == "ppo"
|
||||
assert TrainerConfig.model_validate({"loss": {"type": "cispo"}}).loss.type == "cispo"
|
||||
|
||||
with pytest.raises(ValidationError, match="max_importance_ratio must be at least ratio_high"):
|
||||
TrainerConfig.model_validate({"loss": {"type": "ppo", "max_importance_ratio": 1.0, "ratio_high": 1.2}})
|
||||
|
||||
|
||||
def test_moe_runtime_defaults_are_independent_from_dense_quantization():
|
||||
config = TrainerModelConfig.model_validate({"quantization": {"type": "mxfp8"}})
|
||||
|
||||
@@ -451,8 +451,7 @@ def test_deepseek_v4_init_buffers_post_meta_restores_every_rotary():
|
||||
#
|
||||
# `precompute_freqs_cis` (`model.py:206-235`) applies the NTK-by-parts ramp only when
|
||||
# `original_seq_len > 0`, so a pure sliding-window layer gets plain RoPE at `rope_theta` and every
|
||||
# compressed layer gets YaRN at `compress_rope_theta`. vLLM's `build_deepseek_v4_rope` branches the
|
||||
# base but not the scaling, which `monkey_patch_deepseek_v4_per_layer_rope` corrects.
|
||||
# compressed layer gets YaRN at `compress_rope_theta`. vLLM's `build_deepseek_v4_rope` must match.
|
||||
#
|
||||
# The real checkpoint's beta range and factor, but a reduced `original_max_position_embeddings`:
|
||||
# the cos/sin cache is `original_max * factor` rows of fp32, which at the checkpoint's 65536 would
|
||||
@@ -474,13 +473,15 @@ ROPE_SCALING = {
|
||||
}
|
||||
|
||||
# The nested `main`/`compress` schema, which HF's own `DeepseekV4Config` and this repo's port both
|
||||
# write and which vLLM's config shim cannot read. A config.json can also carry the flat legacy
|
||||
# `rope_scaling` the real checkpoint ships, or no YaRN parameters at all; the nested scaled form
|
||||
# is asserted here because it is the one the patch has the most normalization to do on.
|
||||
# write. A config.json can also carry the flat legacy `rope_scaling` the real checkpoint ships.
|
||||
ROPE_NESTED_PLAIN = {"rope_type": "default", "partial_rotary_factor": 0.125}
|
||||
ROPE_PARAMETERS = {
|
||||
"main": dict(ROPE_NESTED_PLAIN),
|
||||
"compress": {**ROPE_SCALING, "partial_rotary_factor": 0.125},
|
||||
"compress": {
|
||||
"rope_type": "yarn",
|
||||
**{key: value for key, value in ROPE_SCALING.items() if key != "type"},
|
||||
"partial_rotary_factor": 0.125,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -522,12 +523,11 @@ def _vllm_rope_freqs(rotary_emb) -> torch.Tensor:
|
||||
|
||||
@pytest.fixture
|
||||
def vllm_rope_builder():
|
||||
"""`build_deepseek_v4_rope`, patched, under the live vLLM config its `CustomOp` base asserts on.
|
||||
"""`build_deepseek_v4_rope` under the live vLLM config its `CustomOp` base asserts on.
|
||||
|
||||
The builder is resolved off the module at call time rather than bound at import, because the
|
||||
patch rebinds that attribute. The config goes through vLLM's own `patch_rope_parameters`, the
|
||||
same normalization the engine runs: it renames the legacy `type` key and, for the nested
|
||||
schema, injects a top-level `rope_type="default"` beside the sub-dicts.
|
||||
The config goes through vLLM's own `patch_rope_parameters`, the same normalization the engine
|
||||
runs: it renames the legacy `type` key and, for the nested schema, injects a top-level
|
||||
`rope_type="default"` beside the sub-dicts.
|
||||
"""
|
||||
from vllm.config import VllmConfig, set_current_vllm_config
|
||||
from vllm.model_executor.layers import rotary_embedding
|
||||
@@ -536,9 +536,6 @@ def vllm_rope_builder():
|
||||
from vllm.transformers_utils.configs.deepseek_v4 import DeepseekV4Config as VllmDeepseekV4Config
|
||||
from vllm.utils.torch_utils import set_default_torch_dtype
|
||||
|
||||
from prime_rl.inference.patches import monkey_patch_deepseek_v4_per_layer_rope
|
||||
|
||||
monkey_patch_deepseek_v4_per_layer_rope()
|
||||
rotary_embedding._ROPE_DICT.clear()
|
||||
|
||||
def build(compress_ratio: int):
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, IcePopLossConfig, IPOLossConfig
|
||||
from prime_rl.configs.trainer import CISPOLossConfig, CustomLossConfig, IcePopLossConfig, IPOLossConfig, PPOLossConfig
|
||||
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,164 @@ 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_ppo_clips_by_advantage_sign_and_keeps_unclipped_gradients():
|
||||
ratios = torch.tensor([0.5, 0.9, 1.0, 1.1, 2.0, 2.0], device="cuda")
|
||||
trainer_logprobs = (-10 + ratios.log()).requires_grad_()
|
||||
inputs = LossInputs(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=torch.full_like(trainer_logprobs, -10),
|
||||
ref_logprobs=None,
|
||||
advantages=torch.tensor([1.0, 1.0, 1.0, 1.0, 1.0, -1.0], device="cuda"),
|
||||
loss_mask=torch.ones(6, dtype=torch.bool, device="cuda"),
|
||||
)
|
||||
|
||||
result = setup_rl_loss_fn(PPOLossConfig()).loss(inputs)
|
||||
|
||||
torch.testing.assert_close(result.loss, torch.tensor(-2.7, device="cuda"))
|
||||
torch.testing.assert_close(result.metrics["is_clipped"], torch.tensor(1 / 6, device="cuda"))
|
||||
result.loss.backward()
|
||||
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([-0.5, -0.9, -1.0, -1.1, 0.0, 2.0], device="cuda"))
|
||||
|
||||
|
||||
def test_ppo_caps_unbounded_negative_advantage_ratio():
|
||||
trainer_logprobs = torch.tensor([-10.0, float("nan")], device="cuda", requires_grad=True)
|
||||
inputs = LossInputs(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=torch.tensor([-100.0, float("nan")], device="cuda"),
|
||||
ref_logprobs=None,
|
||||
advantages=torch.tensor([-1.0, 1.0], device="cuda"),
|
||||
loss_mask=torch.tensor([True, False], device="cuda"),
|
||||
)
|
||||
|
||||
result = setup_rl_loss_fn(PPOLossConfig()).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], device="cuda"))
|
||||
|
||||
|
||||
def test_cispo_clips_detached_weight_without_dropping_gradients():
|
||||
ratios = torch.tensor([0.1, 1.0, 5.0, 10.0], device="cuda")
|
||||
trainer_logprobs = (-10 + ratios.log()).requires_grad_()
|
||||
advantages = torch.tensor([1.0, -1.0, 1.0, 1.0], device="cuda")
|
||||
inputs = LossInputs(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=torch.full_like(trainer_logprobs, -10),
|
||||
ref_logprobs=None,
|
||||
advantages=advantages,
|
||||
loss_mask=torch.ones(4, dtype=torch.bool, device="cuda"),
|
||||
)
|
||||
|
||||
result = setup_rl_loss_fn(CISPOLossConfig()).loss(inputs)
|
||||
|
||||
expected_weight = torch.tensor([0.1, 1.0, 5.0, 5.0], device="cuda")
|
||||
torch.testing.assert_close(result.loss, -(expected_weight * advantages * trainer_logprobs.detach()).sum())
|
||||
torch.testing.assert_close(result.metrics["is_clipped"], torch.tensor(0.25, device="cuda"))
|
||||
result.loss.backward()
|
||||
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([-0.1, 1.0, -5.0, -5.0], device="cuda"))
|
||||
|
||||
|
||||
def test_cispo_handles_extreme_ratio_and_optional_lower_clip():
|
||||
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(
|
||||
[-10.0 - torch.log(torch.tensor(0.1)).item(), -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(CISPOLossConfig(ratio_low=0.2)).loss(inputs)
|
||||
|
||||
assert torch.isfinite(result.loss)
|
||||
assert all(torch.isfinite(value) for value in result.metrics.values())
|
||||
result.loss.backward()
|
||||
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([-0.2, -5.0, 0.0], device="cuda"))
|
||||
|
||||
|
||||
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()]
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from prime_rl.trainer.models.layers.lm_head import IGNORE_INDEX, FusedOutputLinear, VanillaOutputLinear
|
||||
from prime_rl.trainer.models.layers.lm_head_gemma import GemmaFusedOutputLinear, GemmaVanillaOutputLinear
|
||||
|
||||
B, S, H, V = 2, 7, 8, 37
|
||||
SOFTCAP = 5.0
|
||||
UPSTREAM = 0.25 # stands in for the 1 / grad_accum_steps scaling in the SFT loop
|
||||
|
||||
HEADS = {
|
||||
"fused": (lambda chunk_size: FusedOutputLinear(H, V, chunk_size=chunk_size), None),
|
||||
"vanilla": (lambda chunk_size: VanillaOutputLinear(H, V), None),
|
||||
"gemma_fused": (lambda chunk_size: GemmaFusedOutputLinear(H, V, chunk_size=chunk_size, softcap=SOFTCAP), SOFTCAP),
|
||||
"gemma_vanilla": (lambda chunk_size: GemmaVanillaOutputLinear(H, V, softcap=SOFTCAP), SOFTCAP),
|
||||
}
|
||||
|
||||
|
||||
def _reference_and_grads(hidden, weight, target_ids, loss_mask, softcap):
|
||||
hidden = hidden.detach().clone().requires_grad_(True)
|
||||
weight = weight.detach().clone().requires_grad_(True)
|
||||
logits = hidden @ weight.t()
|
||||
if softcap is not None:
|
||||
logits = softcap * torch.tanh(logits / softcap)
|
||||
loss = F.cross_entropy(logits.view(-1, V), target_ids.view(-1), reduction="none")[loss_mask.view(-1)].sum()
|
||||
(loss * UPSTREAM).backward()
|
||||
return loss.detach(), hidden.grad, weight.grad
|
||||
|
||||
|
||||
def _inputs():
|
||||
torch.manual_seed(0)
|
||||
hidden = torch.randn(B, S, H)
|
||||
weight = torch.randn(V, H)
|
||||
target_ids = torch.randint(0, V, (B, S))
|
||||
loss_mask = torch.rand(B, S) > 0.3
|
||||
return hidden, weight, target_ids, loss_mask
|
||||
|
||||
|
||||
@pytest.mark.parametrize("head", list(HEADS))
|
||||
@pytest.mark.parametrize("chunk_size", [1, 5, 64])
|
||||
def test_lm_head_labels_without_temperature_returns_summed_cross_entropy(head, chunk_size):
|
||||
make_head, softcap = HEADS[head]
|
||||
hidden, weight, target_ids, loss_mask = _inputs()
|
||||
reference, ref_hidden_grad, ref_weight_grad = _reference_and_grads(hidden, weight, target_ids, loss_mask, softcap)
|
||||
|
||||
lm_head = make_head(chunk_size)
|
||||
lm_head.weight = torch.nn.Parameter(weight.clone())
|
||||
hidden = hidden.clone().requires_grad_(True)
|
||||
out = lm_head(hidden, target_ids.masked_fill(~loss_mask, IGNORE_INDEX))
|
||||
assert set(out) == {"loss"}
|
||||
(out["loss"] * UPSTREAM).backward()
|
||||
|
||||
torch.testing.assert_close(out["loss"], reference, rtol=1e-5, atol=1e-5)
|
||||
torch.testing.assert_close(hidden.grad, ref_hidden_grad, rtol=1e-5, atol=1e-5)
|
||||
torch.testing.assert_close(lm_head.weight.grad, ref_weight_grad, rtol=1e-5, atol=1e-5)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chunk_size", [1, 5, 64])
|
||||
def test_fused_lm_head_with_temperature_keeps_logprob_path(chunk_size):
|
||||
hidden, weight, target_ids, loss_mask = _inputs()
|
||||
reference, ref_hidden_grad, ref_weight_grad = _reference_and_grads(hidden, weight, target_ids, loss_mask, None)
|
||||
|
||||
lm_head = FusedOutputLinear(H, V, chunk_size=chunk_size)
|
||||
lm_head.weight = torch.nn.Parameter(weight.clone())
|
||||
hidden = hidden.clone().requires_grad_(True)
|
||||
out = lm_head(hidden, target_ids, temperature=torch.ones(B, S))
|
||||
assert set(out) == {"logprobs", "entropy"}
|
||||
loss = -out["logprobs"][loss_mask].sum()
|
||||
(loss * UPSTREAM).backward()
|
||||
|
||||
torch.testing.assert_close(loss, reference, rtol=1e-5, atol=1e-5)
|
||||
torch.testing.assert_close(hidden.grad, ref_hidden_grad, rtol=1e-5, atol=1e-5)
|
||||
torch.testing.assert_close(lm_head.weight.grad, ref_weight_grad, rtol=1e-5, atol=1e-5)
|
||||
@@ -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
|
||||
@@ -151,7 +151,7 @@ members = [
|
||||
overrides = [
|
||||
{ name = "apache-tvm-ffi", specifier = "==0.1.11" },
|
||||
{ name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux'", specifier = ">=9.15" },
|
||||
{ name = "nvidia-cutlass-dsl", specifier = "==4.6.2" },
|
||||
{ name = "nvidia-cutlass-dsl", specifier = "==4.7.1" },
|
||||
{ name = "openenv-core" },
|
||||
{ name = "tilelang", specifier = "==0.1.12" },
|
||||
{ name = "torch", marker = "sys_platform != 'linux'", specifier = ">=2.13.0" },
|
||||
@@ -176,8 +176,8 @@ requires-dist = ["nixl-cu13==0.10.1"]
|
||||
|
||||
[[manifest.dependency-metadata]]
|
||||
name = "nvidia-cutlass-dsl"
|
||||
version = "4.6.2"
|
||||
requires-dist = ["nvidia-cutlass-dsl-libs-base==4.6.2", "nvidia-cutlass-dsl-libs-cu13==4.6.2"]
|
||||
version = "4.7.1"
|
||||
requires-dist = ["nvidia-cutlass-dsl-libs-base==4.7.1", "nvidia-cutlass-dsl-libs-cu13==4.7.1"]
|
||||
|
||||
[[package]]
|
||||
name = "absl-py"
|
||||
@@ -563,7 +563,7 @@ dependencies = [
|
||||
{ name = "google-search-results" },
|
||||
{ name = "html2text" },
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "mistralai" },
|
||||
{ name = "mpmath" },
|
||||
{ name = "networkx" },
|
||||
@@ -1263,7 +1263,7 @@ dependencies = [
|
||||
{ name = "fsspec", extra = ["http"] },
|
||||
{ name = "httpx" },
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "multiprocess" },
|
||||
{ name = "numpy" },
|
||||
{ name = "packaging" },
|
||||
@@ -1396,7 +1396,7 @@ version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/reasoning/deshuffle_papers" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
@@ -1527,7 +1527,7 @@ version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/science/drug_discovery_bench" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
@@ -1858,7 +1858,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "flashinfer-python"
|
||||
version = "0.6.18"
|
||||
version = "0.6.18.post1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi" },
|
||||
@@ -1878,9 +1878,9 @@ dependencies = [
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "tqdm" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3e/72/12066c5f42a49e7eabe6ec445ac73c59785480bba1b763bd7e0a512f13c1/flashinfer_python-0.6.18.tar.gz", hash = "sha256:70a2074d78cb17ed39c98e5ed47f626c6e8bb29015cf028c49cbf8f2629405a1", size = 13286160, upload-time = "2026-08-29T02:09:18.376Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ad/7e/a756567c193b2af546f98c08158505e998c2dd4a7f8fc6fe6c72105dce8b/flashinfer_python-0.6.18.post1.tar.gz", hash = "sha256:1ebfb8ff3fa3a896e5abbd0dec123a5f3e3734029871349dad6968b252b82097", size = 13294037, upload-time = "2026-09-05T03:26:09.049Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/31/7d/3dae45fc293cd5f16cefe4dcf59683d964ca8faf2303ed7fff54f4bca490/flashinfer_python-0.6.18-py3-none-any.whl", hash = "sha256:d5d26edb48f8def0bf28b2c94415aef7f0754e2cd9e3cb3d6e7081262d068aad", size = 18347767, upload-time = "2026-08-29T02:09:15.868Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/64/3f/bd0a74bfbb4f3813bfe61267ff696fb229ab70c0f1f44848287221928c95/flashinfer_python-0.6.18.post1-py3-none-any.whl", hash = "sha256:adb6d2952b47131138e108bd2999b1fe18b71f1a4c0b2684f168753db9563991", size = 18348022, upload-time = "2026-09-05T03:26:06.084Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2386,7 +2386,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "huggingface-hub"
|
||||
version = "1.28.0"
|
||||
version = "1.32.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'x86_64' and sys_platform == 'linux'",
|
||||
@@ -2403,9 +2403,9 @@ dependencies = [
|
||||
{ name = "tqdm" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/c6/ae/222a91937ebee7f62c0ca8f5ee0afd97577caf24c0abb927d1f5c7e9f6d2/huggingface_hub-1.28.0.tar.gz", hash = "sha256:46a2e950c09234de54093d587d1675382f0d08dbd600d9fb599b5932f5b2c6cb", size = 959609, upload-time = "2026-08-18T12:27:15.101Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/fe/0f/e83fdd856da8fca26bf78d71709ebd120432a0ce535e72b9597cab1eb5bf/huggingface_hub-1.32.0.tar.gz", hash = "sha256:ed70a45498abe86039df7c2f4e5f7575de524be908d3840e8f828d5525eafd6a", size = 1038662, upload-time = "2026-09-17T10:27:48.049Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/51/0e/eafef18f1a75e125e68395db21131db0cf868a128ecd2fce69b4df6c584b/huggingface_hub-1.28.0-py3-none-any.whl", hash = "sha256:58a8bacb03072edfc38067065e9dc24bbb34805410fcd36a1632de0b329660bb", size = 793202, upload-time = "2026-08-18T12:27:12.719Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1b/cf/d98dd561d6d0d7b7d7a64d1563f8aaaa7c235daee41c1c9bcc3da62420ed/huggingface_hub-1.32.0-py3-none-any.whl", hash = "sha256:b0c7c80561969d9cdacdd55fce67ba9584cca0b9d4ea80957a3a5c1445fac5c8", size = 842906, upload-time = "2026-09-17T10:27:46.102Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3081,7 +3081,7 @@ version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/code/livecodebench" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
@@ -3587,7 +3587,7 @@ version = "0.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "grpcio" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "nixl" },
|
||||
{ name = "numpy" },
|
||||
{ name = "protobuf" },
|
||||
@@ -4099,19 +4099,19 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "nvidia-cutlass-dsl"
|
||||
version = "4.6.2"
|
||||
version = "4.7.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "nvidia-cutlass-dsl-libs-base" },
|
||||
{ name = "nvidia-cutlass-dsl-libs-cu13" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b2/ec/14e6ecbfed31ec35bbd1bb6965ae61f879370906a8f9c2e851e292704ba4/nvidia_cutlass_dsl-4.6.2-py3-none-any.whl", hash = "sha256:06ac62deb182a852dfb053032cf945bf02b9aa1bf502a18b129d280d7babb26c", size = 10460, upload-time = "2026-08-05T14:39:41.657Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/af/ef/903dab832a19e0f1d798c9acc96edbda5dfb29f2e030b46e163946555817/nvidia_cutlass_dsl-4.7.1-py3-none-any.whl", hash = "sha256:765850c74868a0b5a02fefbfc1b380842b64e5f7a1c8b1655e322a3b14c01726", size = 10460, upload-time = "2026-08-26T03:11:56.593Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nvidia-cutlass-dsl-libs-base"
|
||||
version = "4.6.2"
|
||||
version = "4.7.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cuda-python" },
|
||||
@@ -4122,13 +4122,13 @@ dependencies = [
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/aa/f3/4be98f2faa283471e355a42ecbc20956fb2c3b6dbc71861f483be277e99a/nvidia_cutlass_dsl_libs_base-4.6.2-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:e129db7155d56ba4478be098c0f819e37690a6ce5d43a9a9a83bf1300d32c57f", size = 3321894, upload-time = "2026-08-05T14:12:30.139Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/54/1b/cf4a0837054bb4b9dc36cdd86f9d2e7fead3629e3373aaa7f7ec1e5e1542/nvidia_cutlass_dsl_libs_base-4.6.2-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:24dfaddad6077fd0de14eecaf66a72762f2f5f30ae1872231f5bf8b243ac2eac", size = 2824987, upload-time = "2026-08-05T14:12:49.618Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9f/6e/5d3f67caba70fe9a5cc21b845d2be35d88049da536185196a2644b0d461c/nvidia_cutlass_dsl_libs_base-4.7.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:e86c55a5010a7edfc067648a75cb29d0c5bd67d75210168cf507b0d0e4d15ba7", size = 3329548, upload-time = "2026-08-26T02:53:14.176Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/55/b5/af332a4dbb0dba45828994d9789d1969dfecca006a6221cd8b92e4825d3f/nvidia_cutlass_dsl_libs_base-4.7.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:c2b67dacabfc905e4d132784fe4848647f40b0b97b1cdde3ce4a482642536b84", size = 2832971, upload-time = "2026-08-26T02:53:52.164Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nvidia-cutlass-dsl-libs-core"
|
||||
version = "4.6.2"
|
||||
version = "4.7.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cuda-python" },
|
||||
@@ -4138,12 +4138,12 @@ dependencies = [
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7c/ef/10c0089234a32f1379e1f213f28f8c7521a9ff0154e3acc58f613d5ef3be/nvidia_cutlass_dsl_libs_core-4.6.2-py3-none-any.whl", hash = "sha256:571d4b46fca1bfbb123d0dc348eaa7fd80af0014ddffc07b849e8195b2364333", size = 772393, upload-time = "2026-08-05T14:09:50.76Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6b/14/b669cc890f7fd74008d7bc52f493d0a7ff256de10f3941c6676249419c07/nvidia_cutlass_dsl_libs_core-4.7.1-py3-none-any.whl", hash = "sha256:c65662abc9ab18fd997c57547895736928e559f4624bbe2aa1aa91418ea014ca", size = 1235214, upload-time = "2026-08-26T02:50:56.241Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nvidia-cutlass-dsl-libs-cu13"
|
||||
version = "4.6.2"
|
||||
version = "4.7.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cuda-python" },
|
||||
@@ -4154,8 +4154,8 @@ dependencies = [
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/46/38/bbe5b8f1ef1a15e7bd1e2ea86686c38f15eeee0a4ba440a5d00d8222cb8e/nvidia_cutlass_dsl_libs_cu13-4.6.2-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:b9543257622ce70d696c6a2bda7e9617ef5b1cc9f29bfe66f4b38d1d1e29a8cb", size = 86712108, upload-time = "2026-08-05T14:27:35.488Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ca/05/7874c37d50e112177a64a96dd6c7eaeacb1661ebb864e0fe5cfd9f706767/nvidia_cutlass_dsl_libs_cu13-4.6.2-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:a299a623fad75eb752c1a4e447b924e9049ed396b037509c41a48da82d1f340a", size = 88036030, upload-time = "2026-08-05T14:27:58.991Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/30/ea/c7c2b4da3d6c9818e152e20cd5f797fb6d9ef75c3a5c80d2d6a9cb211489/nvidia_cutlass_dsl_libs_cu13-4.7.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:e675bf04dc6c91f7c4d5540699b7a031f2b8b44cd2687b32c20892f112f7e0d9", size = 86957786, upload-time = "2026-08-26T03:07:23.015Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/10/71/e178bb0858fd7b96857e98e3acec70b23f13b88540a2fcc53569f8e8ea34/nvidia_cutlass_dsl_libs_cu13-4.7.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:20c14e16125cb8e36bc9947a9f0a57a660f44651365337b911c84abde4967f5f", size = 88260436, upload-time = "2026-08-26T03:07:59.639Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4237,7 +4237,7 @@ version = "0.1.1"
|
||||
source = { editable = "deps/prime-envs/environments/search/officeqa_pro_v2" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
@@ -4269,7 +4269,7 @@ version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/long_context/oolong_pairs" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
@@ -4371,7 +4371,7 @@ version = "0.1.5"
|
||||
source = { editable = "deps/prime-envs/environments/swe/openswe" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
@@ -4658,7 +4658,7 @@ version = "0.1.1"
|
||||
source = { editable = "deps/prime-envs/environments/search/pi_officeqa_pro_v2" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
@@ -4928,8 +4928,8 @@ all = [
|
||||
{ name = "torchdata", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchtitan", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchvision", marker = "sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.29.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.29.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
@@ -4978,8 +4978,8 @@ gpu = [
|
||||
{ name = "torchdata", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchtitan", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchvision", marker = "sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.29.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.29.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
kernels = [
|
||||
{ name = "prime-kernels", version = "0.1.0+cu130torch2.13.0", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
@@ -5049,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" },
|
||||
@@ -5075,9 +5075,9 @@ requires-dist = [
|
||||
{ name = "uvicorn", marker = "extra == 'dashboard'", specifier = ">=0.30" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", extras = ["harbor"], editable = "deps/verifiers" },
|
||||
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.29.0" },
|
||||
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.30.0" },
|
||||
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'disagg'" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
@@ -5118,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.2.dev143" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev152" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5141,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" },
|
||||
@@ -5153,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]]
|
||||
@@ -5191,7 +5191,7 @@ version = "1.2.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "jinja2" },
|
||||
{ name = "junitparser" },
|
||||
{ name = "pydantic" },
|
||||
@@ -5211,7 +5211,7 @@ version = "0.2.0"
|
||||
source = { editable = "deps/prime-envs/environments/code/programbench_env" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "programbench" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
@@ -5845,7 +5845,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "quack-kernels"
|
||||
version = "0.6.4"
|
||||
version = "0.6.5"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi" },
|
||||
@@ -5854,9 +5854,9 @@ dependencies = [
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "torch-c-dlpack-ext" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/75/5c/67c4a0d54cbb8d4d05af73132d620d1900a193b33e0d5ea6a25829b941d2/quack_kernels-0.6.4.tar.gz", hash = "sha256:8bf08a0e1a85aecc892ce84f4b6ed7abb6a44ec7c68b83040abe174bc8c2b936", size = 845485, upload-time = "2026-08-07T23:25:31.94Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/5f/18/6c2a20d00dff254f154fb3b951f4e5a0377a60122c17385e5f08d5f5b5e1/quack_kernels-0.6.5.tar.gz", hash = "sha256:dd9405a4a6fa35fc3a5a18fe35b46a14b0bf7e3ad9fe2451903e355047ac471d", size = 846876, upload-time = "2026-09-11T05:08:20.621Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/28/f5/36ec7e075e90bd92bdf30fee0606f189348c2bbb0af6aebaf7382927c622/quack_kernels-0.6.4-py3-none-any.whl", hash = "sha256:e77c5d1f1299b0b38487fe8737df6c6975daa16bca7f7eb883bd1a74d09e7e78", size = 728458, upload-time = "2026-08-07T23:25:30.549Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/73/d8/f5e56c38b286308d115a171e3c5c44f24e9d03980c3cfd22588df40261fa/quack_kernels-0.6.5-py3-none-any.whl", hash = "sha256:df1ddd31366c82eb9692fe087c671209189dcbde53c909c81a865d4ee66b158d", size = 729615, upload-time = "2026-09-11T05:08:19.306Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6135,7 +6135,7 @@ version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/search/s1_deepresearch" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
@@ -6257,7 +6257,7 @@ version = "5.6.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "numpy" },
|
||||
{ name = "scikit-learn" },
|
||||
{ name = "scipy" },
|
||||
@@ -6860,7 +6860,7 @@ version = "0.1.2"
|
||||
source = { editable = "deps/prime-envs/environments/terminal/terminal_lego" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
@@ -6983,7 +6983,7 @@ version = "0.22.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" }
|
||||
wheels = [
|
||||
@@ -7283,7 +7283,7 @@ version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/judges/trace_cheating_recall_500" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "orjson" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
@@ -7310,7 +7310,7 @@ version = "5.6.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "numpy" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pyyaml" },
|
||||
@@ -7699,7 +7699,7 @@ version = "0.1.1"
|
||||
source = { editable = "deps/prime-envs/environments/multimodal/virl39k" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
@@ -7726,8 +7726,8 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "vllm"
|
||||
version = "0.29.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
version = "0.30.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'aarch64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -7746,7 +7746,7 @@ dependencies = [
|
||||
{ name = "fastsafetensors" },
|
||||
{ name = "filelock" },
|
||||
{ name = "flashinfer-python" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "humming-kernels", extra = ["cu13"] },
|
||||
{ name = "ijson" },
|
||||
{ name = "instanttensor" },
|
||||
@@ -7809,7 +7809,7 @@ dependencies = [
|
||||
{ name = "xgrammar" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e6b0dfc2b6fd307315e9b34b73cd2bfe7b6b08958eda721828e61732bba426b0" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:eb3e11bab695d085098579a6eda2d602419adec3826ebfbcce9a3ffa543eb62e" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -7818,7 +7818,7 @@ requires-dist = [
|
||||
{ name = "anthropic", specifier = ">=0.71.0" },
|
||||
{ name = "apache-tvm-ffi", specifier = "==0.1.11" },
|
||||
{ name = "av", marker = "extra == 'audio'" },
|
||||
{ name = "b12x", marker = "extra == 'b12x'", specifier = "==1.2.6" },
|
||||
{ name = "b12x", marker = "extra == 'b12x'", specifier = "==1.3.0" },
|
||||
{ name = "blake3" },
|
||||
{ name = "cachetools" },
|
||||
{ name = "cbor2" },
|
||||
@@ -7831,9 +7831,9 @@ requires-dist = [
|
||||
{ name = "fastsafetensors", specifier = ">=0.3.3" },
|
||||
{ name = "fastsafetensors", marker = "extra == 'fastsafetensors'", specifier = ">=0.3.3" },
|
||||
{ name = "filelock", specifier = ">=3.16.1" },
|
||||
{ name = "flashinfer-python", specifier = "==0.6.18" },
|
||||
{ name = "flashinfer-python", specifier = "==0.6.18.post1" },
|
||||
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.4.0" },
|
||||
{ name = "huggingface-hub", specifier = ">=1.28.0" },
|
||||
{ name = "huggingface-hub", specifier = ">=1.31.0" },
|
||||
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.12" },
|
||||
{ name = "ijson" },
|
||||
{ name = "instanttensor", specifier = ">=0.1.9" },
|
||||
@@ -7843,7 +7843,7 @@ requires-dist = [
|
||||
{ name = "llguidance", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=1.7.0,<1.8.0" },
|
||||
{ name = "lm-format-enforcer", specifier = "==0.11.3" },
|
||||
{ name = "matplotlib", marker = "extra == 'bench'" },
|
||||
{ name = "mcp" },
|
||||
{ name = "mcp", specifier = ">=2.0.0,<3.0.0" },
|
||||
{ name = "mistral-common", extras = ["audio"], marker = "extra == 'audio'" },
|
||||
{ name = "mistral-common", extras = ["image"], specifier = ">=1.11.6" },
|
||||
{ name = "model-hosting-container-standards", specifier = ">=0.1.14,<1.0.0" },
|
||||
@@ -7852,10 +7852,10 @@ requires-dist = [
|
||||
{ name = "numba", specifier = "==0.65.0" },
|
||||
{ name = "numpy" },
|
||||
{ name = "nvidia-cudnn-frontend", specifier = ">=1.19.1" },
|
||||
{ name = "nvidia-cutlass-dsl", extras = ["cu13"], specifier = "==4.6.2" },
|
||||
{ name = "nvidia-cutlass-dsl", extras = ["cu13"], specifier = "==4.7.1" },
|
||||
{ name = "nvidia-deepstream-videodecode-cu13", marker = "extra == 'deepstream'", specifier = ">=9.0.2" },
|
||||
{ name = "nvtx", specifier = "==0.2.15" },
|
||||
{ name = "openai", specifier = ">=2.0.0" },
|
||||
{ name = "openai", specifier = ">=2.25.0" },
|
||||
{ name = "openai-harmony", specifier = ">=0.0.3" },
|
||||
{ name = "opencv-python-headless", specifier = ">=4.13.0" },
|
||||
{ name = "opentelemetry-api", specifier = ">=1.27.0" },
|
||||
@@ -7882,7 +7882,7 @@ requires-dist = [
|
||||
{ name = "python-json-logger" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "pyzmq", specifier = ">=25.0.0" },
|
||||
{ name = "quack-kernels", specifier = "==0.6.4" },
|
||||
{ name = "quack-kernels", specifier = "==0.6.5" },
|
||||
{ name = "regex" },
|
||||
{ name = "requests", specifier = ">=2.26.0" },
|
||||
{ name = "runai-model-streamer", extras = ["azure", "gcs", "s3"], marker = "extra == 'runai'", specifier = ">=0.15.7" },
|
||||
@@ -7919,8 +7919,8 @@ provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttens
|
||||
|
||||
[[package]]
|
||||
name = "vllm"
|
||||
version = "0.29.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
version = "0.30.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'x86_64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -7939,7 +7939,7 @@ dependencies = [
|
||||
{ name = "fastsafetensors" },
|
||||
{ name = "filelock" },
|
||||
{ name = "flashinfer-python" },
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "huggingface-hub", version = "1.32.0", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "humming-kernels", extra = ["cu13"] },
|
||||
{ name = "ijson" },
|
||||
{ name = "instanttensor" },
|
||||
@@ -8002,7 +8002,7 @@ dependencies = [
|
||||
{ name = "xgrammar" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:09d48617fc2be9c6cdcd5db480651ab0d84817b257204f2cc2e3ecbb70bbb635" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ef52ee58c410ead0b8afb190838fa4cbcb52075596f67862a03859d984966ac4" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -8011,7 +8011,7 @@ requires-dist = [
|
||||
{ name = "anthropic", specifier = ">=0.71.0" },
|
||||
{ name = "apache-tvm-ffi", specifier = "==0.1.11" },
|
||||
{ name = "av", marker = "extra == 'audio'" },
|
||||
{ name = "b12x", marker = "extra == 'b12x'", specifier = "==1.2.6" },
|
||||
{ name = "b12x", marker = "extra == 'b12x'", specifier = "==1.3.0" },
|
||||
{ name = "blake3" },
|
||||
{ name = "cachetools" },
|
||||
{ name = "cbor2" },
|
||||
@@ -8024,9 +8024,9 @@ requires-dist = [
|
||||
{ name = "fastsafetensors", specifier = ">=0.3.3" },
|
||||
{ name = "fastsafetensors", marker = "extra == 'fastsafetensors'", specifier = ">=0.3.3" },
|
||||
{ name = "filelock", specifier = ">=3.16.1" },
|
||||
{ name = "flashinfer-python", specifier = "==0.6.18" },
|
||||
{ name = "flashinfer-python", specifier = "==0.6.18.post1" },
|
||||
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.4.0" },
|
||||
{ name = "huggingface-hub", specifier = ">=1.28.0" },
|
||||
{ name = "huggingface-hub", specifier = ">=1.31.0" },
|
||||
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.12" },
|
||||
{ name = "ijson" },
|
||||
{ name = "instanttensor", specifier = ">=0.1.9" },
|
||||
@@ -8036,7 +8036,7 @@ requires-dist = [
|
||||
{ name = "llguidance", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=1.7.0,<1.8.0" },
|
||||
{ name = "lm-format-enforcer", specifier = "==0.11.3" },
|
||||
{ name = "matplotlib", marker = "extra == 'bench'" },
|
||||
{ name = "mcp" },
|
||||
{ name = "mcp", specifier = ">=2.0.0,<3.0.0" },
|
||||
{ name = "mistral-common", extras = ["audio"], marker = "extra == 'audio'" },
|
||||
{ name = "mistral-common", extras = ["image"], specifier = ">=1.11.6" },
|
||||
{ name = "model-hosting-container-standards", specifier = ">=0.1.14,<1.0.0" },
|
||||
@@ -8045,10 +8045,10 @@ requires-dist = [
|
||||
{ name = "numba", specifier = "==0.65.0" },
|
||||
{ name = "numpy" },
|
||||
{ name = "nvidia-cudnn-frontend", specifier = ">=1.19.1" },
|
||||
{ name = "nvidia-cutlass-dsl", extras = ["cu13"], specifier = "==4.6.2" },
|
||||
{ name = "nvidia-cutlass-dsl", extras = ["cu13"], specifier = "==4.7.1" },
|
||||
{ name = "nvidia-deepstream-videodecode-cu13", marker = "extra == 'deepstream'", specifier = ">=9.0.2" },
|
||||
{ name = "nvtx", specifier = "==0.2.15" },
|
||||
{ name = "openai", specifier = ">=2.0.0" },
|
||||
{ name = "openai", specifier = ">=2.25.0" },
|
||||
{ name = "openai-harmony", specifier = ">=0.0.3" },
|
||||
{ name = "opencv-python-headless", specifier = ">=4.13.0" },
|
||||
{ name = "opentelemetry-api", specifier = ">=1.27.0" },
|
||||
@@ -8075,7 +8075,7 @@ requires-dist = [
|
||||
{ name = "python-json-logger" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "pyzmq", specifier = ">=25.0.0" },
|
||||
{ name = "quack-kernels", specifier = "==0.6.4" },
|
||||
{ name = "quack-kernels", specifier = "==0.6.5" },
|
||||
{ name = "regex" },
|
||||
{ name = "requests", specifier = ">=2.26.0" },
|
||||
{ name = "runai-model-streamer", extras = ["azure", "gcs", "s3"], marker = "extra == 'runai'", specifier = ">=0.15.7" },
|
||||
|
||||
Reference in New Issue
Block a user