Compare commits

..
Author SHA1 Message Date
Xuan-Phi NguyenandGitHub e3dd67633d fix(rl): stabilize IPO, IcePop, and ref-KL loss masking (#3696)
## Motivation

Packed RL batches can contain masked tokens with invalid or extreme log
probabilities. IPO, IcePop, and ref-KL previously formed importance
ratios before removing those tokens, so a nominally excluded token could
still produce `0 * inf` or `0 * NaN`. Accepted rare actions could also
overflow `exp(log p_trainer - log p_inference)`, including in
mismatch-KL diagnostics.

## Design

- Select eligible tokens before ratio and KL arithmetic; IcePop and
ref-KL also select accepted tokens before exponentiating their policy
terms.
- Compute IPO's absolute probability-difference gate using `exp(max(log
p, log q)) * -expm1(min(log p, log q) - max(log p, log q))`, retaining
the same `eps` decision with better behavior for nearby small
probabilities.
- Add `IPOLossConfig.max_importance_ratio` (default `1e4`) and cap
accepted IPO/ref-KL forward weights while retaining the capped
policy-gradient coefficient. Bound squared-log-ratio terms and mismatch
diagnostics so they remain finite for extreme finite log ratios.
- Keep masked/unmasked diagnostics, namespace ref-KL metrics, and treat
the shared mismatch-KL helper as internal; leave model precision
settings unchanged.

## Validation completed

- GPU loss tests: **17 passed**, including extreme-ratio forward and
gradient cases. Expanded config suite: **205 passed**. Ruff check and
format passed.
- The stacked CISPO and IPOv2 two-update smoke runs both completed with
finite trainer metrics and no episode errors:
[CISPO](https://wandb.ai/primeintellect/qwen30b-math/runs/0c0bb28ed7734551b600cbe52253d7f5),
[IPOv2](https://wandb.ai/primeintellect/qwen30b-math/runs/3ab7fbd7805d4ebca1d7ff2d1dc0cc84).
These validate this fix in downstream training paths; there was no
standalone PR1 training run.

## Ongoing experiments and config provenance

The 300-step CISPO and IPOv2 runs use this fix through stacked commits.
[IPOv2](https://wandb.ai/primeintellect/qwen30b-math/runs/9045de5680a44a1d9a9f6bd84e9c30f2)
is running; the CISPO job is queued for an 8-GPU node. Long-run outcomes
are pending.

The actual run TOMLs at
`docs/study/examples/qwen3-30b-a3b/math16k_slurm.toml`,
`math_cispo.toml`, and `math_ipov2.toml` are **local and uncommitted**.
Relative to the checked-in [advanced math
example](https://github.com/PrimeIntellect-ai/prime-rl/blob/f87fd0eb3372cded4cf6cfb20e41189796354eae/examples/advanced/qwen3-30b-a3b/math.toml),
the shared local base uses one 8-H200 node (2 trainer, 6 inference GPUs)
instead of two trainer plus two inference nodes; 16,384 sequence tokens
and 15,000 completion tokens instead of 32,768 each; EP 2 + Ulysses CP 2
instead of EP 8; batch size 32, zero allowed off-policy steps, and 64
inflight episodes instead of batch size 512, eight off-policy steps, and
1,024 initial inflight episodes (group size 8 is shared); and vLLM TP 2
/ DP 3 instead of TP 8. It runs 300 steps without the example's AIME
eval source. The model, math taskset, AdamW learning rate (`1e-6`), and
W&B project are shared. The private overlays select CISPO
(`ratio_high=5`) or IPOv2 (`eps=.3`, `ratio_cap=5`, entropy floor `.15`)
and point SLURM at this worktree.
2026-09-28 12:24:58 -07:00
Mika SenghaasandGitHub 0a437ae340 fix: bump verifiers and prime-envs for timeouts (#3709)
## Summary

- Bump Verifiers to
[`c35ebd32`](https://github.com/PrimeIntellect-ai/verifiers/commit/c35ebd320126ee17f6a570a4f3fb8ef0fe0b0ae1).
This includes [the merged timeout
fix](https://github.com/PrimeIntellect-ai/verifiers/pull/2697): an unset
agent rollout timeout no longer falls back to four hours.
- Bump prime-envs to
[`565e8a74`](https://github.com/PrimeIntellect-ai/prime-envs/commit/565e8a74c001b25706d7c958f36d7bb0cd504ddc).
Its Lean helper now works with Verifiers' taskset API.

## Breaking

- An unset agent rollout timeout now inherits the task timeout, or has
no separate limit. Set a positive `env.<agent>.timeout.rollout` to
retain a stage limit.
- `env.<agent>.timeout.rollout = 0` is rejected. Remove the field to
request no separate stage limit.

## Verification

- `uv lock --check --offline` passed with the updated submodules.
- A focused UV smoke test confirmed that an unset agent timeout resolves
to no limit, a positive override resolves as given, and zero fails
validation.
- `git diff --check` passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Behavior change to rollout timeout defaults affects how long agent
stages can run; misconfigured envs may run longer or fail validation
until configs are updated.
> 
> **Overview**
> Updates **Verifiers** and **prime-envs** dependency pins to pick up
upstream fixes and API alignment.
> 
> The Verifiers bump fixes agent rollout timeout resolution: an
**unset** `env.<agent>.timeout.rollout` no longer silently defaults to
four hours—it now follows the task timeout or has no separate stage cap.
**`env.<agent>.timeout.rollout = 0` is now invalid**; omit the field
instead of using zero to mean “no separate limit.” Configs that relied
on the old default or zero need an explicit positive rollout timeout if
they still want a stage limit.
> 
> The **prime-envs** bump updates its Lean helper for Verifiers’ taskset
API.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
dead789c54f98ce0e57ab3fe47f9e819a9b802eb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-28 12:02:31 -07:00
9a55a0899c [ENG-6355] feat(docker): in-place PRIME_RL_REF source overlay for chart pods (#3686)
## Summary

Reworks the entrypoint's `PRIME_RL_REF` runtime source override so the
prime-rl-fft chart can run a branch on hosted FFT without building an
image for it. Inert unless `PRIME_RL_REF` is set; the default `docker
run` / chart path is unchanged.

The hook already existed (#2850) but was tuned for long-lived
containers: it cloned the full repo (~700 MB of `.git`) and `cp -a`'d
the 20 GB baked venv into a per-ref dir before syncing. As a per-pod
startup step that is unusable. Kubernetes `command:` also replaces the
image ENTRYPOINT, so the fft chart never ran this script at all; the
companion chart PR (PrimeIntellect-ai/fft#101) routes every prime-rl
container through it with a dispatcher-pinned sha.

## Changes

- **Shallow fetch by ref.** Fresh `git init` + `fetch --depth 1 origin
<ref>` + `checkout FETCH_HEAD`, then `submodule update --init
--recursive --depth 1` for the same four public submodules
`build_image.yaml` inits. GitHub serves branches, tags and full shas
alike; abbreviated shas are not fetchable and the comment says so. The
checkout is always fresh: a container is, and the fetch is seconds.
- **Sync into the baked venv instead of copying it.**
`UV_PROJECT_ENVIRONMENT=/app/.venv uv sync --inexact --locked ...` from
the checkout, with the same extras list as `Dockerfile.cuda`. uv
re-points the first-party editables at the checkout and reinstalls only
third-party pins that differ; flash-attn, deep-ep, mamba-ssm and friends
stay as baked. The chart's `uv run --no-sync <entrypoint>` commands
resolve the project from the new cwd.
- **Heavy-pin preflight.** Before syncing, compare the checkout's
`uv.lock` against `/app/uv.lock` for torch, torchvision, torchaudio,
triton, vllm, vllm-router, flash-attn, flash-attn-3, flashinfer-python,
tilelang, deep-ep, deep-gemm, mamba-ssm, nixl, prime-kernels and
quack-kernels. Any difference exits with a message to build an image
instead. The validator in fft runs the same check at dispatch
(PrimeIntellect-ai/fft#102); this is the backstop.
- **Pretend versions like the image build.** The shallow submodule
clones carry no tags, so hatch-vcs stamped verifiers/renderers
`0.0.1.dev1` and every `verifiers>=…` floor in the tree was unmet.
Resolve the same versions the Dockerfile does
(`docker-editable-pretend-versions.sh`), bake them into
`fallback-version` and drop the submodules' git metadata so the fallback
applies. (setuptools-scm's per-dist env vars turned out not to be
honored by hatch-vcs.)
- **Replay the image's prime CLI install, with its verifiers pin
overridden.** `Dockerfile.cuda` installs `prime>=0.7` after its lockfile
sync, which pulls prime-traces / prime-sandboxes / openai past the
lock's pins; the `--locked` sync here rolled them back and `prime env
install` could no longer import. The CLI also pins `verifiers==0.2.0`,
which replaces the editable with the PyPI wheel and breaks prime-rl's
own imports (see below). The replayed install passes `--overrides` with
a one-line file containing `verifiers`. **Workaround, marked
`FIXME(prime#940)` in the script:** remove the override once the prime
CLI drops verifiers as a dependency (PrimeIntellect-ai/prime#940),
together with the matching override in `Dockerfile.cuda` (#3705).
- **Git URL rewrite via `GIT_CONFIG_*` env** instead of `git config
--global`, so pods whose `HOME` is not writable by their uid still clone
the ssh-listed submodules.
- **`PRIME_RL_SOURCE_COMMIT`** is exported and logged so runs record
what actually ran.

## Found along the way: published images ship a broken verifiers

Since #3635 (2026-09-22) the Dockerfile's `uv pip install 'prime>=0.7'`
step replaces the submodule verifiers (0.3.x) with the PyPI
`verifiers==0.2.0` wheel that every prime release since 0.6.30 pins. On
the pristine image and on main-built `v0.9.1.dev128`, `uv run --no-sync
orchestrator --help` and `env-server --help` fail at import
(`verifiers.v1` has no `SingleAgentEnvConfig`; no
`set_base_sandbox_labels`). Runs that install a Hub env at pod start
survive by accident, because that install pulls verifiers 0.3.x back in;
baked-env runs like the nightly FFT configs do not, and nightly FFT has
failed daily since 9/24. The same override fixes the Dockerfile in
#3705.

## Verified on telus (namespace `minh-dev`, image built from this branch
at 478481593, later revisions of the script fetched into the same image)

Overlaying main tip `b94487324`, which adds `get_global_moe_stats` to
the trainer model module, a marker the baked source lacks:

| Check | Result |
|---|---|
| depth-1 fetch + four submodules | 9 s |
| container start → pod command, including the CLI install | ~35 s; ~60
s with a Hub env install |
| `prime_rl`, `verifiers`, `renderers` import from the checkout; marker
present in the overlay, absent in `/app/src` | pass, as root and as uid
1000 (`HOME` on an emptyDir, like the chart's env-servers) |
| vllm / torch / flash-attn versions and site-packages mtimes untouched
| pass |
| editables report `verifiers 0.3.2.dev137`, `renderers 0.1.12.dev2` |
pass |
| `prime --version`, `prime env install --help`, `uv run --no-sync prime
env install primeintellect/wordle` | pass; the install swaps the baked
`wordle` for the Hub's and leaves verifiers alone |
| `uv run --no-sync orchestrator --help`, `env-server --help` | pass
(they fail on the pristine image, see above) |
| `uv pip check` | 7 incompatibilities, down from the image's 107: six
are the image's own lockfile inconsistencies (mamba-ssm/tilelang,
torch/cudnn, vllm/transformers, openai-agents/openai and
python-multipart, flash-attn-4/tvm), the seventh is the intentional
`prime requires verifiers==0.2.0` |
| ref whose lock pins vllm 0.28.0 vs the image's 0.29.0 | refused in 9
s, before any sync, naming `flashinfer-python, vllm` |
| a `PRIME_CLI_SPEC` knob tried in one revision | removed: a
caller-supplied env var must not choose what gets installed into a
hosted pod |

Not exercised: a GPU workload through the overlay (the pods were
CPU-only), and the chart path end to end (needs fft#101 deployed).

## Related

- fft: chart `source` values (PrimeIntellect-ai/fft#101) and validator
`source.ref` resolution with the same lockfile preflight
(PrimeIntellect-ai/fft#102).
- platform `sourceRef` on the dedicated run dispatch and `prime train
--ref` / `--pr` follow.
- Dockerfile fix for the verifiers clobbering: #3705.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how chart/FFT pods bootstrap Python when `PRIME_RL_REF` is set
by mutating `/app/.venv` at startup; mis-synced lockfiles or override
logic could break training entrypoints, though heavy-pin preflight and
the default no-ref path limit blast radius.
> 
> **Overview**
> When **`PRIME_RL_REF`** is set, the Docker entrypoint no longer does a
full repo clone and a 20 GB venv copy into `/tmp`. It
**shallow-fetches** the ref (depth‑1 + four submodules), exports
**`PRIME_RL_SOURCE_COMMIT`**, and **`uv sync`s the checkout into the
baked `/app/.venv`** so editables point at the overlay while heavy GPU
wheels stay untouched.
> 
> Startup adds **guardrails and parity with the image build**: compare
checkout vs image **`uv.lock`** for torch/vllm/flash-attn-style packages
and **exit early** if they drift; apply
**`docker-editable-pretend-versions.sh`** so shallow submodules satisfy
`verifiers`/`renderers` floors; **reinstall `prime>=0.7`** with a
**`verifiers` pip override** so the CLI does not clobber editables.
GitHub SSH URLs are rewritten via **`GIT_CONFIG_*`** (writable without a
global git config), and the process **`cd`s into the checkout** instead
of swapping **`VIRTUAL_ENV`** to a per-ref venv.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b2fddf150dcaadfbe66cc7945ac34dac649d2fc6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 10:29:40 -07:00
Andrew KirillovandGitHub 666297d09c Require prime-sandboxes>=0.3.2 (#3682)
Raises the pyproject floor to `prime-sandboxes>=0.3.2` and refreshes the
lock accordingly (resolves 0.3.2, wheel/sdist hashes cross-checked
against PyPI).

## Why

The hosted-eval stress runner bootstraps this repo with `uv sync
--no-dev --frozen`, so the 429-retry fixes in prime-sandboxes 0.3.2
(status-aware backoff on platform API and gateway retries) only reach
eval rollouts through this lock. 0.3.0 satisfied the old `>=0.3.0` floor
indefinitely - `lock-check` enforces consistency, not freshness - so the
behavioral fix could not arrive without either this bump or a new
automation mechanism.

The floor raise (rather than a lock-only refresh) encodes the actual
requirement: the runtime depends on the 429-retry semantics, and any
future lock regeneration can no longer backslide below 0.3.2. Precedent
for this shape: #3571 (`chore: require prime-runs 0.1.3`).

## What changed

- `pyproject.toml`: `prime-sandboxes>=0.3.0` -> `>=0.3.2`
- `uv.lock`: the matching specifier line; the prime-sandboxes resolution
entries already point at 0.3.2

## Validation

- `uv lock --check` passes (581 packages)
- `uv sync --no-dev --frozen` resolves prime-sandboxes 0.3.2
- `uv run pytest tests/unit/eval -v`: 9 passed
- Regenerated with uv 0.12.19 (older uv reorders unrelated lock tables)

Linear: ENG-5966 (eval-based stress testing).
2026-09-28 09:08:05 -07:00
Scott CabrinhaandGitHub 202f108f33 fix(docker): build NIXL from source by default; isolate the prime CLI install (#3667)
## What

- **NIXL from source (default on).** `Dockerfile.cuda` builds NIXL
0.10.1 against the baked `/opt/ucx` (UCX 1.19.1) by default. The wheel
is renamed to `nixl-cu13` before building, and the build asserts the UCX
plugin links `/opt/ucx/lib/libucp.so`.
`scripts/install_nixl_from_source.sh` gets the same rename for the SLURM
path.
- **prime CLI as an isolated uv tool.** It's installed into
`/app/.tools` instead of `uv pip install`-ing it into `/app/.venv`, with
the executable linked into `/app/.venv/bin`. The build asserts the
workspace `verifiers` is still the one installed.

## Why

**NIXL.** The PyPI `nixl-cu13` wheel bundles its own UCX, which
segfaults on the prefill→decode KV transfer (#2883). The existing
`INCLUDE_NIXL_FROM_SOURCE` option was:
1. **Off by default, never enabled in CI.** Every published image ships
the PyPI wheel. On SLURM, research works around this with a
`pre_run_command` reinstall after each `uv sync`.
2. **Broken when enabled.** NIXL 0.10.1's pyproject names the package
`nixl-cu12`, so the `nixl_cu13-*.whl` glob matched nothing.
3. **A no-op even when installed.** The `nixl` shim imports `nixl_cu13`
before `nixl_cu12`, so the source build sat unused. Upstream's
`contrib/build-wheel.sh` renames via `contrib/tomlutil.py --wheel-name
nixl-cu<major>`, and this PR does the same.

The plugin has `RUNPATH=/opt/ucx/lib`, so it doesn't depend on
`LD_LIBRARY_PATH`.

**prime CLI (regression from #3635).** Every `prime` 0.7.x on PyPI pins
`verifiers==0.2.0`. Running `uv pip install 'prime>=0.7'` into the app
venv resolves against it and replaces:
- workspace `verifiers` (0.3.2.dev) → 0.2.0
- `openai` 2.54 → 3.15
- workspace `prime-pydantic-config` → the PyPI one
- `prime-sandboxes` / `prime-traces` → newer versions

As a result, `prime_rl.configs.orchestrator` fails to import (`module
'verifiers.v1' has no attribute 'SingleAgentEnvConfig'`), and every
component crashes at startup. This affects every image built since
#3635.

## Test plan

- [x] Image `commit-0039ddc20-amd64` (NIXL fix only): the build passed,
and inference pods on telus confirmed the UCX plugin links `/opt/ucx`
1.19.1. The run then crashed on the `verifiers` downgrade above.
- [x] On `commit-a1822f7a0-amd64` (pre-#3635): `uv tool install
'prime>=0.7'` gives a working CLI 0.7.5, and `uv run --no-sync prime env
install primeintellect/reverse-text` installs into `/app/.venv`.
`verifiers` still has `SingleAgentEnvConfig`, and `openai` stays at
2.54.0.
- [x] Earlier, a GLM-5.3 10-node P/D run on FFT/telus with the same NIXL
build (installed in-pod): a chat request through the PD router
succeeded, with 1 NIXL KV transfer of 5.65 MB / 18.8 ms and no segfault
(ENG-6348).
- [x] Image `commit-cef7100c7-amd64` (both fixes, newest main): build
passed, including the new workspace-verifiers assertion. The GLM-5.3
10-node P/D run on telus used it with no in-pod bootstrap: the NIXL UCX
plugin links `/opt/ucx` 1.19.1, all components import cleanly, the
PD-router chat request returned correctly, and NIXL KV transfers
succeeded. Prefill also needed `VLLM_USE_BREAKABLE_CUDAGRAPH=0` on vLLM
0.29; that is separate, in #3669.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Scott Cabrinha <scott.cabrinha@primeintellect.ai>
2026-09-27 19:35:41 -07:00
11 changed files with 299 additions and 129 deletions
+13 -10
View File
@@ -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
+1 -1
@@ -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."""
+1 -1
View File
@@ -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",
+119 -45
View File
@@ -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 \
+5 -1
View File
@@ -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 ==="
+70 -63
View File
@@ -125,54 +125,64 @@ def shift_tensor_right(t: Float[Tensor, "batch seq"], pad_value: float | None =
def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
"""Mean of values over a boolean mask; returns 0 when mask is empty."""
denom = torch.clamp_min(mask.sum(), 1)
return values[mask].sum() / denom
return (values[mask] / denom).sum()
def compute_importance_ratio_and_mismatch_kl(
trainer_logprobs: Tensor, inference_logprobs: Tensor
) -> tuple[Tensor, Tensor, Tensor]:
log_importance_ratio = trainer_logprobs - inference_logprobs
importance_ratio = torch.exp(log_importance_ratio)
mismatch_kl = importance_ratio - log_importance_ratio - 1
return log_importance_ratio, importance_ratio, mismatch_kl
def _mismatch_kl_from_log_ratio(log_importance_ratio: Tensor) -> Tensor:
# Keep headroom for FP32 reductions across tokens and ranks.
metric_limit = log_importance_ratio.new_tensor(1e30)
mismatch_kl = torch.expm1(log_importance_ratio.clamp(max=metric_limit.log())) - log_importance_ratio
return mismatch_kl.clamp(max=metric_limit)
def _capped_importance_ratio(log_importance_ratio: Tensor, max_ratio: float) -> Tensor:
capped_log_ratio = log_importance_ratio.detach().clamp(max=log_importance_ratio.new_tensor(max_ratio).log())
return torch.exp(capped_log_ratio + (log_importance_ratio - log_importance_ratio.detach()))
class IPOLoss:
"""IPO loss type: a symmetric trust region (mask tokens whose probability
moved more than ``eps`` in absolute terms), policy gradient via
the importance ratio, and a squared-log-ratio KL regularizer."""
a capped importance ratio, and a squared-log-ratio KL regularizer."""
def __init__(self, config: IPOLossConfig):
self.config = config
def loss(self, inputs: LossInputs) -> LossOutputs:
loss_config = self.config
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
advantages = inputs.advantages
loss_mask = inputs.loss_mask
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
trainer_logprobs, inference_logprobs
)
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
trainer_logprobs = inputs.trainer_logprobs[inputs.loss_mask]
inference_logprobs = inputs.inference_logprobs[inputs.loss_mask]
advantages = inputs.advantages[inputs.loss_mask]
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
log_importance_ratio = trainer_logprobs - inference_logprobs
larger_logprob = torch.maximum(trainer_logprobs, inference_logprobs)
smaller_logprob = torch.minimum(trainer_logprobs, inference_logprobs)
# |e^logp - e^logq| = e^max(logp, logq) - e^min(logp, logq)
# = e^max(logp, logq) * (1 - e^(min(logp, logq) - max(logp, logq)))
# = e^max(logp, logq) * -expm1(min(logp, logq) - max(logp, logq)).
# expm1 avoids cancellation in 1 - e^x when x is near zero.
abs_probs_diff = torch.exp(larger_logprob) * -torch.expm1(smaller_logprob - larger_logprob)
is_masked = abs_probs_diff > loss_config.eps
keep_mask = loss_mask & ~is_masked
keep_mask = ~is_masked
advantages = loss_config.adv_tau * advantages
pg_loss = keep_mask * advantages * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights
loss = per_token_loss.sum()
importance_ratio = _capped_importance_ratio(log_importance_ratio[keep_mask], loss_config.max_importance_ratio)
pg_loss = -loss_config.adv_tau * advantages[keep_mask] * importance_ratio
if weights is not None:
pg_loss = pg_loss * weights[keep_mask]
loss = pg_loss.sum()
if loss_config.kl_tau:
kl_loss = loss_config.kl_tau * log_importance_ratio.clamp(-1e4, 1e4).square()
if weights is not None:
kl_loss = kl_loss * weights
loss = loss + kl_loss.sum()
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
"is_masked": _safe_mean(is_masked, loss_mask),
"masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
"is_masked": is_masked.sum() / max(is_masked.numel(), 1),
}
return LossOutputs(loss=loss, metrics=metrics)
@@ -187,28 +197,27 @@ class IcePopLoss:
def loss(self, inputs: LossInputs) -> LossOutputs:
loss_config = self.config
log_importance_ratio, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
inputs.trainer_logprobs, inputs.inference_logprobs
)
log_importance_ratio = inputs.trainer_logprobs[inputs.loss_mask] - inputs.inference_logprobs[inputs.loss_mask]
advantages = inputs.advantages[inputs.loss_mask]
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
log_ratio_low = log_importance_ratio.new_tensor(loss_config.ratio_low).log()
log_ratio_high = log_importance_ratio.new_tensor(loss_config.ratio_high).log()
detached_log_ratio = log_importance_ratio.detach()
is_masked = (detached_log_ratio < log_ratio_low) | (detached_log_ratio > log_ratio_high)
keep_mask = inputs.loss_mask & ~is_masked
keep_mask = ~is_masked
# Mask before exponentiation so rejected extreme ratios cannot produce
# 0 * inf = NaN in the loss or its gradient.
safe_log_ratio = torch.where(keep_mask, log_importance_ratio, torch.zeros_like(log_importance_ratio))
importance_ratio = torch.exp(safe_log_ratio)
per_token_loss = -(keep_mask * loss_config.adv_tau * inputs.advantages * importance_ratio)
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights
importance_ratio = torch.exp(log_importance_ratio[keep_mask])
per_token_loss = -loss_config.adv_tau * advantages[keep_mask] * importance_ratio
if weights is not None:
per_token_loss = per_token_loss * weights[keep_mask]
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, inputs.loss_mask & is_masked),
"masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
"is_masked": _safe_mean(is_masked, inputs.loss_mask),
"is_masked": is_masked.sum() / max(is_masked.numel(), 1),
}
return LossOutputs(loss=per_token_loss.sum(), metrics=metrics)
@@ -222,39 +231,37 @@ def ref_kl_loss_fn(inputs: LossInputs) -> LossOutputs:
inference probability; a squared-log-ratio term regularizes drift. Scalar
advantages are not read — ref_kl algorithms ship none.
"""
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
ref_logprobs = inputs.ref_logprobs
loss_mask = inputs.loss_mask
if ref_logprobs is None:
if inputs.ref_logprobs is None:
raise ValueError("ref_kl loss type requires ref_logprobs — use the 'opd' or 'opsd' algorithm.")
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
trainer_logprobs, inference_logprobs
)
trainer_logprobs = inputs.trainer_logprobs[inputs.loss_mask]
inference_logprobs = inputs.inference_logprobs[inputs.loss_mask]
ref_logprobs = inputs.ref_logprobs[inputs.loss_mask]
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
log_importance_ratio = trainer_logprobs - inference_logprobs
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
is_masked = probs_diff < -0.2
drop_mask = loss_mask & is_masked
keep_mask = loss_mask & ~is_masked
keep_mask = ~is_masked
ref_kl = ref_logprobs - trainer_logprobs
pg_loss = keep_mask * ref_kl.detach() * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
per_token_loss = -pg_loss + 1e-3 * kl_loss
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights
loss = per_token_loss.sum()
importance_ratio = _capped_importance_ratio(log_importance_ratio[keep_mask], 1e4)
pg_loss = -ref_kl[keep_mask].detach() * importance_ratio
kl_loss = 1e-3 * log_importance_ratio.clamp(-1e4, 1e4).square()
if weights is not None:
pg_loss = pg_loss * weights[keep_mask]
kl_loss = kl_loss * weights
loss = pg_loss.sum() + kl_loss.sum()
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
# Namespaced: the rl loss fn emits same-named trust-region metrics with a
# different definition, and mixed batches run both fns in one step.
metrics = {
"ref_kl/masked_mismatch_kl": _safe_mean(mismatch_kl, drop_mask),
"ref_kl/masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
"ref_kl/unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
"ref_kl/is_masked": _safe_mean(is_masked, loss_mask),
"ref_kl": _safe_mean(ref_kl, loss_mask),
"ref_kl/is_masked": is_masked.sum() / max(is_masked.numel(), 1),
"ref_kl": ref_kl.sum() / max(ref_kl.numel(), 1),
}
return LossOutputs(loss=loss, metrics=metrics)
+4 -3
View File
@@ -29,7 +29,7 @@ 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,
@@ -528,8 +528,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
+78
View File
@@ -6,8 +6,10 @@ from prime_rl.trainer.rl.loss import (
IcePopLoss,
LossInputs,
LossOutputs,
_mismatch_kl_from_log_ratio,
compute_entropy,
compute_loss,
ref_kl_loss_fn,
setup_rl_loss_fn,
)
@@ -124,10 +126,86 @@ def test_icepop_loss_masks_extreme_ratio_without_nan():
result = IcePopLoss(IcePopLossConfig()).loss(inputs)
assert torch.equal(result.loss, torch.zeros_like(result.loss))
assert all(torch.isfinite(value) for value in result.metrics.values())
result.loss.backward()
assert torch.equal(trainer_logprobs.grad, torch.zeros_like(trainer_logprobs.grad))
@pytest.mark.parametrize("config", [IPOLossConfig(kl_tau=0.01), IcePopLossConfig()])
def test_ipo_icepop_match_original_on_finite_ratios(config):
torch.manual_seed(23)
trainer_logprobs = (-8 * torch.rand(128, device="cuda")).requires_grad_()
inference_logprobs = -8 * torch.rand(128, device="cuda")
advantages = torch.randn(128, device="cuda")
loss_mask = torch.rand(128, device="cuda") > 0.3
weights = torch.rand(128, device="cuda")
inputs = LossInputs(trainer_logprobs, inference_logprobs, None, advantages, loss_mask, weights)
result = setup_rl_loss_fn(config).loss(inputs)
log_ratio = trainer_logprobs - inference_logprobs
ratio = log_ratio.exp()
if isinstance(config, IPOLossConfig):
keep = loss_mask & ((trainer_logprobs.exp() - inference_logprobs.exp()).abs() <= config.eps)
expected = (
(-(keep * config.adv_tau * advantages * ratio) + loss_mask * config.kl_tau * log_ratio.square()) * weights
).sum()
else:
keep = (
loss_mask
& (log_ratio.detach() >= torch.tensor(config.ratio_low, device="cuda").log())
& (log_ratio.detach() <= torch.tensor(config.ratio_high, device="cuda").log())
)
expected = (-(keep * config.adv_tau * advantages * ratio) * weights).sum()
torch.testing.assert_close(result.loss, expected, rtol=1e-5, atol=1e-5)
actual_grad = torch.autograd.grad(result.loss, trainer_logprobs, retain_graph=True)[0]
expected_grad = torch.autograd.grad(expected, trainer_logprobs)[0]
torch.testing.assert_close(actual_grad, expected_grad, rtol=1e-5, atol=1e-5)
def test_ipo_excludes_masked_tokens_and_caps_accepted_extreme_ratio():
trainer_logprobs = torch.tensor([-10.0, 0.0, float("nan")], device="cuda", requires_grad=True)
inputs = LossInputs(
trainer_logprobs=trainer_logprobs,
inference_logprobs=torch.tensor([-100.0, -100.0, float("nan")], device="cuda"),
ref_logprobs=None,
advantages=torch.ones(3, device="cuda"),
loss_mask=torch.tensor([True, True, False], device="cuda"),
)
result = setup_rl_loss_fn(IPOLossConfig()).loss(inputs)
torch.testing.assert_close(result.loss, torch.tensor(-1e4, device="cuda"))
assert all(torch.isfinite(value) for value in result.metrics.values())
result.loss.backward()
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([-1e4, 0.0, 0.0], device="cuda"))
def test_ref_kl_loss_stays_finite_with_extreme_ratios_and_masked_nan():
trainer_logprobs = torch.tensor([-10.0, 0.0, float("nan")], device="cuda", requires_grad=True)
inputs = LossInputs(
trainer_logprobs=trainer_logprobs,
inference_logprobs=torch.tensor([-100.0, -100.0, float("nan")], device="cuda"),
ref_logprobs=torch.tensor([-1.0, -1.0, float("nan")], device="cuda"),
advantages=torch.zeros(3, device="cuda"),
loss_mask=torch.tensor([True, True, False], device="cuda"),
)
result = ref_kl_loss_fn(inputs)
assert torch.isfinite(result.loss)
assert all(torch.isfinite(value) for value in result.metrics.values())
result.loss.backward()
assert torch.isfinite(trainer_logprobs.grad).all()
def test_mismatch_kl_retains_small_positive_values():
log_ratio = torch.tensor([1e-4], device="cuda")
torch.testing.assert_close(
_mismatch_kl_from_log_ratio(log_ratio), torch.tensor([5e-9], device="cuda"), rtol=1e-3, atol=0
)
def test_ce_component_matches_masked_nll():
trainer_logprobs = [torch.tensor([-0.1, -0.5, -0.2], dtype=torch.float32).cuda()]
inference_logprobs = [torch.zeros(3, dtype=torch.float32).cuda()]
Generated
+4 -4
View File
@@ -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" },
@@ -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]]