Compare commits

...
Author SHA1 Message Date
94f359e8d6 feat: scope verifiers limiters by run id and bump verifiers to main (#3641)
## Summary
- Bump the verifiers submodule to main (`9cf0df22b`), which includes
PrimeIntellect-ai/verifiers#2657: creation limiters wait on backlog
instead of raising past 300s, and their bucket is scoped by
`$VF_RUN_ID`. `uv.lock` is regenerated; verifiers dropped its `lean`
extra.
- The env-server entrypoint sets `VF_RUN_ID` from `PRL_RUN_ID`, minting
a uuid only when neither is set. Its pool workers inherit it.
- The multi-node SFT SLURM script exports `PRL_RUN_ID` and
`PRL_RUN_NAME` unconditionally, as the RL script does. Only the W&B
shared-mode variables stay behind the wandb condition, now named
`wandb_shared` in the template.

## Why
With the bump, a run whose sandbox creation outpaces `creates_per_min`
throttles instead of failing every rollout past the 300s backlog.
Scoping the bucket by run id keeps one run's backlog from delaying
another.

The env server is the one prime-rl process that creates sandboxes, and
every launcher hands it `PRL_RUN_ID`: the `rl`, `sft`, and `eval`
entrypoints export it before spawning, and the SLURM scripts export it
at the top of the sbatch script, which `srun` propagates to the `uv run
env-server` tasks. Deriving `VF_RUN_ID` there covers every launch path
with one line. The SFT script previously exported the run id only for a
shared W&B run, so its online-eval env servers would otherwise each have
minted their own scope.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes run-id propagation for SLURM-launched env servers and sandbox
creation throttling behavior; mis-set env vars could affect multi-run
cluster behavior but not auth or data integrity.
> 
> **Overview**
> Aligns prime-rl with verifiers’ run-scoped sandbox **creation
limiters** (keyed on `$VF_RUN_ID`) so throttling and backlog are per run
instead of shared across jobs.
> 
> The **env-server** entrypoint now sets `VF_RUN_ID` from `PRL_RUN_ID`,
or mints a UUID when launched standalone, so pool workers inherit the
same scope on every launch path.
> 
> **Multi-node SFT** previously exported `PRL_RUN_ID` only when shared
Weights & Biases logging was enabled, which left online-eval env servers
without a consistent run id. The SLURM template now always exports
`PRL_RUN_ID` and `PRL_RUN_NAME` (matching RL), while W&B shared-mode env
vars are gated on a new `wandb_shared` flag passed from `sft.py`.
> 
> **Lockfile** metadata drops the removed `lean` extra from the bumped
verifiers dependency.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
364f0b58699ad556746116a1bf6208e37b5afc6b. 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 Fable 5.1 <noreply@anthropic.com>
2026-09-23 13:34:19 -07:00
Matej SirovatkaandGitHub cf400e7db9 perf: reduce DSV4 indexer stalls and overlap CP gathers (#3643)
Packed sequence lengths were causing repeated FP8-indexer autotuning
during training. Other DP groups then arrived late at the layer-4 FSDP
prefetch, making a normal ~1–3 ms parameter gather appear to take 1.78
s. Together with narrower checkpoint state, avoiding a query-layout
copy, and overlapping CP communication, the matched BF16 benchmark
improves from **22.741 s / 40.23% MFU** after #3638 to **18.999 s /
47.79% MFU**.

- Bucket the indexer's autotune key by compressed-key length, also
keying on head count and dimension. Exact key lengths still control
addressing and masks. An all-rank trace showed the last rank arriving
1.718 s late and completing the gather in 1.34 ms; it had been
benchmarking the first CSA indexer.
- Register the FP8 indexer as an opaque operation and make its final
int32 selection a mandatory checkpoint save. This preserves the top-k
replay requirement while retaining compact IDs and skipping indexer
scoring on replay.
- Apply query RoPE directly in the sparse kernel's `(batch, tokens,
heads, dim)` layout, removing the transpose/contiguous round trip in
attention and the indexer.
- Launch the main KV CP gather with PyTorch's asynchronous functional
collective before query/compressor computation, and wait just before
consuming KV. Its registered backward performs the corresponding sum
reduce-scatter. Compilation stays enabled; communication uses NCCL's
existing stream.

### SAC configuration

Exact configuration for the measured run:

```toml
[model.ac]
mode = "selective"
freq = 1
targets = [
  "prime_rl::dsv4_sparse_attn",
  "prime_rl_collectives::all_to_all_single_equal",
  "aten::sort.stable",
]
```

`prime_rl::fp8_indexer` is saved automatically by the mandatory policy
in both full and selective checkpointing. The qualified stable-sort
overload matters: `aten::sort` does not match `aten::sort.stable`.

### Measurements

| Variant | Mean step time | Logged tokens/s | Logged MFU |
| --- | ---: | ---: | ---: |
| PR #3638 only (job 653) | 22.741 s | 86,890 | 40.23% |
| Indexer tuning buckets, full AC (665) | 20.718 s | 95,043 | 44.01% |
| Buckets + sparse-attention/EP-count SAC (675) | 20.042 s | 97,636 |
45.21% |
| All changes + SAC above (691) | **18.999 s** | **103,210** |
**47.79%** |

This is a **1.197× step-time speedup** over #3638 alone and **1.055×**
over the prior SAC run. Peak rank-0 reserved memory is **232.5 GiB /
267.7 GiB**. All five losses are finite. These are short benchmark
results, not a long-run convergence measurement. Measurements use the
pinned job-492 environment; this branch is rebased onto current main,
whose touched modeling files were identical to that baseline.

### Validation

- CPU checkpoint-policy tests: 4 passed on the PR branch, including
mandatory indexer retention under custom SAC targets. Ruff lint and
formatting checks passed for all changed files.
- Existing FP8-indexer GPU correctness cases: 2 passed. Changing key
lengths 1060 → 1064 → 1073 reused one autotune entry (2.015 s initial
tuning, then 0.919 ms and 0.634 ms).
- Existing sparse/eager attention parity cases: 9 passed, covering CSA,
HCA, sliding attention, packed documents, and empty compression.
- Existing CP packing checks: 6 passed across CP2/CP4 and all three
attention types; rerun successfully after inlining the gather and wait
calls directly in attention forward.
- Two-rank async-collective probe: outputs and input/weight gradients
passed with full/selective checkpointing, eager execution and
`torch.compile(fullgraph=True)`.
- Compiled two-rank BF16 attention checks: all three attention types
passed under full/selective checkpointing against the blocking
implementation; maximum relative L2 difference across outputs and
gradients was 0.026%. The sliding cases ran in a separate process after
the combined test harness reached its compiled-variant limit.
- Query-layout microcheck: bitwise-equal outputs and input gradients in
BF16/FP32, including the production query shape.



<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes touch CP collectives, compile/custom-op boundaries, and SAC
correctness for non-replayable top-k; numerics are covered by existing
kernel and CP tests but production timing depends on NCCL stream overlap
behavior.
> 
> **Overview**
> This PR targets **DeepSeek V4 training step time** by cutting FP8
indexer autotune churn, overlapping context-parallel communication, and
tightening activation-checkpoint behavior around sparse indexing.
> 
> The **FP8 Lightning indexer** is registered as `prime_rl::fp8_indexer`
and added to the **mandatory** selective-activation-checkpoint save list
so replay keeps the final int32 top-k without re-running scoring. Triton
autotune now keys on **`next_power_of_2(S_k)`** plus head count and
dimension so packed batches with slightly different compressed-key
lengths reuse one tuned config.
> 
> In **attention**, queries stay in **`(batch, tokens, heads, dim)`**
through RoPE and into `dsv4_sparse_attn`, dropping the
transpose/contiguous path. Under CP, **KV all-gather** starts
asynchronously via `_c10d_functional.all_gather_into_tensor` before
query and compressor work, with **`wait_tensor`** immediately before KV
is consumed.
> 
> Tests assert mandatory checkpoint retention for the new op and extend
CP parity mocks for the async gather path.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6449f9212c3430c812b9623a1b5bd274e350b780. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 16:07:21 -04:00
samsjaandGitHub 8da21f16b8 feat(eval): make task dispatch rate configurable (#3602)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Optional config with default unchanged; reuses existing orchestrator
dispatch rate limiting with no auth or data-path changes.
> 
> **Overview**
> Eval runs can now cap how fast episodes are dispatched via a new
**`tasks_per_minute`** setting on **`ServedEvalConfig`** (shared by
standalone eval and SFT online eval). **`None`** keeps the previous
behavior with no rate limit; a positive value throttles dispatch through
the existing **`Dispatcher`** **`AsyncLimiter`**, intended to pace
sandbox provisioning during autoscaling.
> 
> The eval **`runner`** passes **`config.tasks_per_minute`** into the
dispatcher instead of hard-coding **`None`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
31f8041b908234dc4c45f128540af8e4daa6435b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 09:30:15 -07:00
ae37b35a34 fix(trainer): match vLLM's per-token FP8 activation quantization bit for bit (#3623)
RL compares trainer and inference logprobs token by token, so any
disagreement between the two FP8
quantizers is model-independent noise. The trainer's per-token
activation cast is now bit-identical to
vLLM's production CUDA op, `torch.ops._C.per_token_group_fp8_quant`.

- Three kernels in `fp8_utils.py` floor `amax` at `1e-10` and use
`tl.math.div_rn` for scale and quotient.
Triton's `/` lowers to multiply-by-reciprocal, one fp32 ULP off the
correctly rounded value.
- The weight kernel is untouched: vLLM's weight path is itself a
reciprocal-multiply and already matched.
- A new GPU test pins the equality against the CUDA op; the trainer
still imports vLLM nowhere.

Share of 128-wide groups whose scale is bitwise equal to vLLM's, and
share of elements whose fp8 byte
is, on four 4096x4096 bf16 activation tensors on an H200:

| tensor | scales: before | after | bytes: before | after |
|---|---|---|---|---|
| randn x0.02 | 42.8329% | 100.0000% | 98.1890% | 100.0000% |
| randn x1.0 | 41.0797% | 100.0000% | 99.8822% | 100.0000% |
| randn x30.0 | 43.6028% | 100.0000% | 99.8869% | 100.0000% |
| randn heavytail 16ch x50 | 42.7979% | 100.0000% | 99.8999% | 100.0000%
|

Every pre-fix mismatch was exactly one e4m3 step, so weights stay at
100% and dequantization error is
unchanged. Agreement with vLLM's Triton fallback drops to about 42% on
scales, which is forced since
vLLM's two backends are not bit-identical to each other and only the
CUDA op runs in production. Costs
3.1% of quant-kernel time at 4096x4096 and 8.7% at [8192, 7168].
Verified on sm90 with
`use_ue8m0=False`; sm100 takes a different vLLM kernel.

## Effect on training gradients

The old floor applied to the scale, not to `amax`, so any 128-wide group
with `amax < 0.0448` was
quantized against an inflated scale: its values were squeezed into a
corner of the e4m3 range
instead of spanning it, and everything below `1e-7` rounded to zero.
Forward activations sit above
that threshold; gradients do not, and both the input-gradient (dgrad)
and weight-gradient (wgrad)
paths cast `grad_output` through these kernels. The error is one-sided
toward zero, so it shrinks
gradients rather than adding noise.

Measured end to end: a 131k-context SWE RL run with an FP8 trainer on
pre-fix code logged
`optim/grad_norm` averaging 0.0079 over 100 steps, against 0.0465 and
0.0528 for otherwise
identical runs with a bf16 trainer. A rerun of that config on the fixed
kernels is at 0.0421 over
its first 17 steps, where the pre-fix run read 0.0094 and the bf16
reference 0.0468 over the same
window. Mismatch KL is blind to all of this, since it depends on the
forward alone: lr = 0 probes
read 0.0089 before the fix and 0.0091 after.

### Why the floor's location matters

Per 128-element group:

```
# before
amax  = max(|x|)
scale = max(amax / 448, 1e-4)      # floor on the SCALE
y     = x / scale

# after
amax  = max(max(|x|), 1e-10)       # floor on the AMAX
scale = div_rn(amax, 448)
y     = clamp(div_rn(x, scale), -448, 448)
```

A floor exists only to keep an all-zero group from dividing by zero. The
correct scale, `amax / 448`,
maps the group's largest element to exactly 448 and spans the full e4m3
range. Pinning the scale at
`1e-4` makes it too large whenever `amax < 0.0448`, and a scale that is
too large makes `y = x / scale`
too small, so the group occupies a corner of the range.

Take a gradient group with `amax = 1e-5`:

- correct scale is `1e-5 / 448 = 2.2e-8`, giving `y_max = 448`, the full
range
- old scale is `1e-4`, giving `y_max = 0.1`, a sliver of it
- e4m3's smallest subnormal is `2^-9 = 0.00195`, so any `|y|` below
about `0.001` rounds to zero
- that is every `|x|` below `1e-7`, which is 1% of this group's maximum
- at `amax = 1e-6` the same `1e-7` cutoff erases everything below 10% of
the maximum

Two properties make this worse than rounding noise. It is one-sided,
always toward zero, so it biases
the gradient short rather than jittering it. And it is non-uniform:
groups above `0.0448` are exact
while groups far below it are gutted, so the surviving gradient also
points in a different direction.
AdamW's per-parameter normalization absorbs much of the magnitude loss,
which is why a run carrying
this bug trains through it while looking healthy.

## Launch-config retune

This PR also reconfigures the kernel launch specs for perf (for H200).

Measuring the cost of correct rounding exposed a separate problem: these
kernels were already launched
at block sizes that spill registers. The per-channel cast used a `[128,
128]` fp32 tile, and
`div.rn.f32` needs more live temporaries than `div.full.f32`, which is
why correct rounding looked
expensive there. Retuning `BLOCK_M`, `BLOCK_N` and `num_warps` in five
host wrappers, with no kernel
body change, recovers more than correct rounding costs.

Measured on an H200 at this model's dimensions (hidden 4096, MoE
intermediate 2048, 8 local experts
with ragged routing), 102 configs against a noise-control arm:

| kernel | wins | regressions | noise | best delta |
|---|---|---|---|---|
| `grouped_per_channel` k-major | 24 | 0 | 2 | -54.1% |
| `grouped_per_channel` row-major | 21 | 0 | 5 | -35.3% |
| `per_token` transposed | 6 | 0 | 6 | -44.8% |
| `grouped_per_token` | 7 | 0 | 19 | -12.0% |
| `per_token` | 3 | 0 | 9 | -12.4% |

Ragged expert groups gain more than equal ones: at K=4096 with 4096
tokens per rank, the k-major
per-channel cast is -28.5% on an equal split and -54.1% under realistic
routing. A launch config cannot
change the arithmetic, so bit identity against the CUDA op is
unaffected.

## Verification

```
uv run --no-sync python -m pytest tests/unit/train/models/test_fp8_utils.py -q
```

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 11:14:43 -04:00
Matej SirovatkaandGitHub 77788ba020 fix: retain two reduce-scatter input buffers for FP32 MoE routers (#3638)
FP32 MoE routing uses a separate FSDP unit. Its post-backward hook can
request a reduce-scatter input buffer while the expert reduction is
still in flight; FSDP's default limit of one inserts a compute-stream
wait before attention backward can run.

Set `set_reduce_scatter_max_input_buffers(2)` on that router unit
immediately after sharding. FSDP resolves the shared buffer limit to the
maximum across its units, allowing the router to pack gradients while
the expert reduction completes. This adds two lines on top of main, with
no new configuration or numerical dtype changes. The tradeoff is
additional memory for in-flight reduction inputs.

### Measured timings

Same saved packed tokens and checkpoint, GLM-5.3 EP8/CP8 on 32 B300
GPUs, FP32 routing, full activation checkpointing, and activation
offloading enabled in both runs. Two warmup passes followed by one
profiled forward/backward; no optimizer update.

| Metric | One buffer | Two buffers |
| --- | ---: | ---: |
| Warm forward + backward, median across 32 ranks | 14.699 s | 12.649 s
|
| Profiled forward + backward, median across 32 ranks | 14.808 s |
12.717 s |
| Expert reduce-scatter overlap with main-stream compute, rank 0 | 11.1%
| 93.7% |
| Maximum reserved GPU memory across ranks/passes | 204.49 GiB | 205.29
GiB |

Warm forward/backward is **13.9% shorter**, equivalent to **16.2% higher
throughput**, at **0.80 GiB** more peak reserved memory in this run.

### Timeline of the stall

Actual CUDA kernel intervals for layer 77, rank 0. Each panel is aligned
independently to that layer's expert reduce-scatter launch. Blue is
other main-stream compute, green is attention backward, and orange is
expert gradient reduce-scatter.

![Measured one-buffer versus two-buffer reduce-scatter
overlap](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/1bebf826b530cb7c52d18d8cf92d562174a7efbe/reduce-scatter-overlap.png)

With one buffer, the router's post-backward hook queues a compute-stream
wait while the **4.5 GiB expert reduction** is in flight. This creates a
**40.7 ms main-stream compute gap**. The router's own reduction is only
**6 MiB / 0.66 ms**. Attention backward starts **48.87 ms** after the
expert reduction launch; with two buffers it starts at **8.15 ms**
instead. The layer's expert-reduction overlap rises from **7.3% to
96.3%**. These layer-specific percentages differ from the aggregate
values in the table.

These are single-run comparisons, not repeated statistical benchmarks.
The measured experiment set the cap at the root; this PR applies the
same effective shared cap through the router unit. Ruff and `git diff
--check` pass; this exact main-based patch has not had a new distributed
run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Two-line FSDP scheduling tweak in MoE setup only; no numerical or API
changes, with modest extra peak memory for reduction buffers.
> 
> **Overview**
> When **FP32 MoE routers** are sharded as their own FSDP unit
(alongside expert-parallel expert shards), backward can stall: the
router’s post-backward reduce-scatter needs an input buffer while the
much larger expert gradient reduction is still using FSDP’s default
single buffer, forcing a **compute-stream wait** before attention
backward can proceed.
> 
> Right after `fully_shard` on `block_mlp.router`, the PR calls
**`set_reduce_scatter_max_input_buffers(2)`** so the router can queue
its small reduction without blocking on the in-flight expert
reduce-scatter. FSDP’s shared limit becomes the max across units—same
effective behavior as raising the cap at the root, but scoped to the
router shard path. **Tradeoff:** slightly more memory for in-flight
reduction inputs; no new config or dtype changes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
51a9e3daef8a53a254d7e7ff35d1ee3c8afce18c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 17:02:46 +02:00
Scott CabrinhaandGitHub ab85b3b369 fix(docker): install the Prime CLI into the image venv for hosted-run env bootstrap (#3635)
## Problem

Since #3585 removed the `prime` CLI as a prime-rl dependency ("Stop
installing the `prime` CLI with prime-rl. Run `uv tool install prime`
when the CLI is needed"), the published GHCR images ship no `prime`
executable. That breaks Hosted Training runs on these images at
bootstrap:

The platform's env-server and orchestrator pods prepend an
**authenticated** Hub env install to their pod command,

```
uv run --no-sync prime env install '<owner/name>' && ... && uv run --no-sync env-server @ config
```

because verifiers' own `ensure_installed` resolver fetches the Hub
**unauthenticated** and 404s on private environments — the pre-install
into the pod's venv is what makes v1 Hub tasksets resolvable at boot
(envs baked into the image never hit this path).

With the executable absent from `/app/.venv/bin`, every pod dies at
spawn and the run wedges at `CREATING`. Observed on
`ghcr.io/primeintellect-ai/prime-rl:v0.9.1.dev100` dispatching a run
with a Hub taskset:

```
error: Failed to spawn: `prime`
```

(the orchestrator's entire log is two lines: the no-checkpoints warning,
then that spawn failure).

## Fix

Install the CLI into the image venv at build time — **not** as a project
dependency, so #3585's "CLI as a separate tool" boundary stands for
library code; the image just ships the executable and its runtime deps
so the platform bootstrap can run.

- One `RUN` after the main `uv sync`, using the same uv cache mount as
the rest of the file.
- `prime>=0.7` — pure-Python CLI, few MB; most deps
(httpx/pydantic/etc.) are already in the venv.
- The runtime stage copies `/app` wholesale, and `PATH` already puts
`/app/.venv/bin` first, so `uv run --no-sync prime env install ...` and
direct `prime` calls both resolve.

## Alternatives considered

- Reverting #3585's dependency removal: rejected — keeps the boundary;
the image need, not the library, is what broke.
- Platform-side init container with a dedicated prime-cli image (cleaner
long-term: keeps the CLI out of the framework image entirely) — worth
tracking on the platform side; this PR is the minimal unblock for hosted
Hub-env runs today.

## Verification

- `VIRTUAL_ENV=<venv> uv pip install 'prime>=0.7'` smoke-tested locally
(CLI 0.7.0 boots).
- Placement reviewed against the builder stage: runs after the locked
sync chain, before the optional NIXL block; nothing downstream
overwrites the venv.
2026-09-22 19:06:08 -06:00
Mika SenghaasandGitHub de5cdb8bae fix: read serialized dashboard token counts (#3632)
## Summary

- pin Verifiers `main` at the merge of [Verifiers
#2652](https://github.com/PrimeIntellect-ai/verifiers/pull/2652),
including the computed fields from [Verifiers
#2651](https://github.com/PrimeIntellect-ai/verifiers/pull/2651)
- read serialized token counts directly from completed episode and live
trace records
- remove dashboard-specific token reconstruction and prompt-token
summation

The previous implementation summed every full prompt in a multi-turn
trace.
This counted the shared conversation once per request and inflated long
rollouts.

## Verification

Before this change, a two-turn trace with prompt usages of 100 and 150
tokens
reported 250 input tokens. After this change, the serialized record and
both
dashboard paths report 130 input tokens and 50 output tokens.

- tested the dashboard flow end to end
- `ruff check` and `py_compile` passed for both changed modules
2026-09-22 15:50:19 -07:00
18 changed files with 136 additions and 67 deletions
+4
View File
@@ -137,6 +137,10 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
# Needed for private environments hub auth
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
VIRTUAL_ENV=/app/.venv uv pip install 'prime>=0.7'
# 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
+1 -1
@@ -21,6 +21,11 @@ class ServedEvalConfig(EvalSourcesConfig):
"""Adaptive in-flight episode concurrency, sized by the same controller as
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on episode dispatch, in tasks per minute. Use it for
sandbox-backed environments to pace provisioning during autoscaling. None disables
rate limiting."""
@property
def env_addresses(self) -> dict[tuple[str, str], str | None]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
+5
View File
@@ -1,6 +1,7 @@
import os
import queue
import threading
import uuid
from functools import partial
from pathlib import Path
@@ -53,6 +54,10 @@ def run_server(config: EnvServerConfig):
def main():
"""Main entry-point for the env server. Run using `uv run env-server`"""
set_proc_title("EnvServer")
# verifiers keys run-scoped state (creation limiters) by $VF_RUN_ID. Every launcher,
# the Python entrypoints and the SLURM templates alike, hands env servers $PRL_RUN_ID;
# a standalone server is a run of its own.
os.environ.setdefault("VF_RUN_ID", os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex)
run_server(cli(EnvServerConfig))
+4 -5
View File
@@ -137,7 +137,7 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
def write_slurm_script(
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str, wandb_shared: bool
) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -210,6 +210,7 @@ def write_slurm_script(
gpus_per_node=config.deployment.gpus_per_node,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
prl_run_id=prl_run_id,
wandb_shared=wandb_shared,
run_name=config.run.name,
online_eval=online_eval,
use_nccl_broadcast=(
@@ -249,16 +250,14 @@ def sft_slurm(config: SFTConfig):
write_config(config, config_path, exclude=exclude)
# Trainer and online-eval processes log to a single shared W&B run.
prl_run_id: str | None = None
if online_eval and config.monitors.wandb is not None:
prl_run_id = os.environ["PRL_RUN_ID"]
wandb_shared = online_eval and config.monitors.wandb is not None
launcher_dir = get_launcher_dir(config.run_dir)
if online_eval:
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
script_path = launcher_dir / SFT_SBATCH
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
write_slurm_script(config, config_path, log_dir, script_path, os.environ["PRL_RUN_ID"], wandb_shared)
logger.info(f"Wrote SLURM script to {script_path}")
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
+1 -1
View File
@@ -114,7 +114,7 @@ class EvalRunner:
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
tasks_per_minute=None,
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=0,
run_id=self.run_id,
run_name=self.run_name,
+3 -11
View File
@@ -50,7 +50,9 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
``line`` numbers the episode within the stream from 1, so the last of n reads as
n — it is what a reader sees and what addresses the episode."""
rewards, advantages = [], []
input_tokens = output_tokens = turns = branches = 0
input_tokens = rec.get("num_input_tokens")
output_tokens = rec.get("num_output_tokens")
turns = branches = 0
stop_condition = None
truncated = False
reward_parts: dict[str, list[float]] = {}
@@ -86,20 +88,10 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
if advantage is not None:
advantages.append(advantage)
for node in nodes:
n_tokens = len(node.get("token_ids") or [])
if node.get("sampled"):
output_tokens += n_tokens
else:
input_tokens += n_tokens
if (node.get("message") or {}).get("role") == "assistant":
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
truncated = truncated or trace_truncated(trace)
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
for call in trace.get("calls") or []:
usage = call.get("usage") or {}
input_tokens += usage.get("prompt_tokens") or 0
output_tokens += usage.get("completion_tokens") or 0
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
return {
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
+12 -12
View File
@@ -176,31 +176,31 @@ def message_text(message: dict[str, Any]) -> str:
return ""
def trace_row(trace: dict[str, Any]) -> dict[str, Any]:
def trace_row(record: dict[str, Any]) -> dict[str, Any]:
"""The live table's view of one trace: phase, turns, tokens, cost, last message."""
calls = trace.get("calls") or []
calls = record.get("calls") or []
usage = [call.get("usage") or {} for call in calls]
# The newest node is usually a tool result; the assistant's latest words say more.
last = ""
for node in reversed(trace.get("nodes") or []):
for node in reversed(record.get("nodes") or []):
message = node.get("message") or {}
if message.get("role") == "assistant" and (last := " ".join(message_text(message).split())):
break
costs = [u["cost"] for u in usage if u.get("cost") is not None]
nodes = trace.get("nodes") or []
nodes = record.get("nodes") or []
parents = {node.get("parent") for node in nodes if node.get("parent") is not None}
return {
"trace": trace.get("id"),
"agent": (trace.get("agent") or {}).get("name", "agent"),
"stage": stage(trace),
"trace": record.get("id"),
"agent": (record.get("agent") or {}).get("name", "agent"),
"stage": stage(record),
"turns": len(calls),
"branches": sum(1 for index in range(len(nodes)) if index not in parents),
"input_tokens": sum(u.get("prompt_tokens") or 0 for u in usage),
"output_tokens": sum(u.get("completion_tokens") or 0 for u in usage),
"input_tokens": record.get("num_input_tokens"),
"output_tokens": record.get("num_output_tokens"),
"cost": sum(costs) if costs else None,
"stop_condition": trace.get("stop_condition"),
"errors": len(trace.get("errors") or []),
"pending": len(trace.get("pending") or []),
"stop_condition": record.get("stop_condition"),
"errors": len(record.get("errors") or []),
"pending": len(record.get("pending") or []),
"last": last[:SNIPPET_CHARS],
}
@@ -60,11 +60,11 @@ export EVAL_DONE=$LAUNCHER_DIR/.sft_eval_done_$SLURM_JOB_ID
mkdir -p "$LAUNCHER_DIR"
rm -f "$TRAINER_DONE"{% if online_eval %} "$EVAL_DONE"{% endif %}
{% if prl_run_id %}
# Trainer and online-eval log to one shared W&B run. The trainer creates the run,
# and the online-eval process finalizes it after the final epoch.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
{% if wandb_shared %}
# Trainer and online-eval log to one shared W&B run. The trainer creates the run,
# and the online-eval process finalizes it after the final epoch.
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
@@ -32,6 +32,7 @@ MANDATORY_SAVE_NAMESPACES = frozenset({"deepep"})
MANDATORY_SAVE_OPERATIONS = frozenset(
{
"aten::topk",
"prime_rl::fp8_indexer",
"prime_rl::record_moe_routing_statistics",
}
)
+2
View File
@@ -520,6 +520,8 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
reshard_after_forward=config.reshard_after_forward,
shard_placement_fn=shard_placement_fn,
)
# Keep the router reduction from waiting for the expert reduction's input buffer.
block_mlp.router.set_reduce_scatter_max_input_buffers(2)
fully_shard(
transformer_block,
@@ -128,6 +128,7 @@ from dataclasses import dataclass
import torch
import torch.distributed as dist
import torch.distributed._functional_collectives as funcol
from torch import Tensor, nn
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
@@ -540,8 +541,8 @@ class DeepseekV4Indexer(nn.Module):
n_entries = compressed_kv.shape[1]
cos, sin = packed.position_embeddings[self.compressor.rope_layer_type]
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim).transpose(1, 2)
q = apply_rotary_pos_emb_interleaved(q, cos, sin).transpose(1, 2)
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim)
q = apply_rotary_pos_emb_interleaved(q, cos, sin, unsqueeze_dim=2)
w = self.weights_proj(hidden_states)
layout = packed.compression_layouts[self.compressor.compress_rate]
@@ -712,17 +713,21 @@ class DeepseekV4Attention(nn.Module):
hidden_shape = (*input_shape, -1, self.head_dim) # (b, t, h, d), the query view
cos, sin = packed.position_embeddings[self.rope_layer_type] # (1, t, qk_rope_head_dim // 2) each
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
# Normalizing before the transpose keeps the input contiguous for the quack kernel.
q = self.q_b_norm(self.q_b_proj(q_residual).view(*hidden_shape)).transpose(1, 2) # (b, h, t, d)
q = apply_rotary_pos_emb_interleaved(q, cos, sin)
kv = self.kv_norm(self.kv_proj(hidden_states)) # (b, t, d)
kv = kv.view(*kv.shape[:2], 1, self.head_dim) # (b, t, 1, d)
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
if self.cp_context.cp_enabled:
kv = gather_for_cp(kv, self.cp_context.cp_group) # (b, T, 1, d)
kv = kv.transpose(1, 2) # (b, 1, T, d)
# Launch on NCCL's communication stream; query/compressor work does not read KV.
kv = torch.ops._c10d_functional.all_gather_into_tensor(
kv.movedim(1, 0).contiguous(),
self.cp_context.cp_world_size,
self.cp_context.cp_group.group_name,
)
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
# Keep the query in the sparse kernel's (batch, tokens, heads, dim) layout.
q = self.q_b_norm(self.q_b_proj(q_residual).view(*hidden_shape))
q = apply_rotary_pos_emb_interleaved(q, cos, sin, unsqueeze_dim=2)
compressed = (
self.compressor(
@@ -736,6 +741,9 @@ class DeepseekV4Attention(nn.Module):
else None
)
compressed_kv, top_k_indices = compressed if compressed is not None else (None, None)
if self.cp_context.cp_enabled:
kv = funcol.wait_tensor(kv).movedim(0, 1).contiguous() # (b, T, 1, d)
kv = kv.transpose(1, 2) # (b, 1, T, d)
inputs = SparseAttnInputs.build(
kv=kv,
compressed_kv=compressed_kv,
@@ -743,7 +751,7 @@ class DeepseekV4Attention(nn.Module):
window_indices=packed.window_indices,
)
attn_output, _ = dsv4_sparse_attn(
q.transpose(1, 2).contiguous(),
q,
inputs.kv_buf,
inputs.indices,
self.sinks,
@@ -97,7 +97,7 @@ def per_token_group_quant_fp8(
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
],
key=["S_Q", "S_K"],
key=["S_Q", "S_K_BUCKET", "H", "D"],
)
@triton.jit
def _triton_fp8_indexer_kernel(
@@ -116,6 +116,7 @@ def _triton_fp8_indexer_kernel(
stride_ws,
H: tl.constexpr,
D: tl.constexpr,
S_K_BUCKET: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
@@ -168,7 +169,16 @@ def _triton_fp8_indexer_kernel(
tl.store(out_ptrs, acc, mask=out_mask)
def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
@torch.library.custom_op("prime_rl::fp8_indexer", mutates_args=())
def fp8_indexer(
q: torch.Tensor,
k: torch.Tensor,
w: torch.Tensor,
ks: torch.Tensor,
ke: torch.Tensor,
topk: int,
weight_scale: float = 1.0,
) -> torch.Tensor:
"""Triton FP8 indexer: UE8M0 quantization + fused scoring kernel + topk.
Args:
@@ -221,6 +231,9 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
w.stride(0),
H=H,
D=D,
# Packed document tails change S_k between batches. Reuse tuning within
# a size bucket; exact S_k still controls strides and all bounds masks.
S_K_BUCKET=triton.next_power_of_2(S_k),
)
actual_topk = min(topk, S_k)
@@ -236,3 +249,8 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
indices = indices.masked_fill(out_of_range, S_k)
return indices.to(torch.int32)
@fp8_indexer.register_fake
def _fp8_indexer_fake(q, k, w, ks, ke, topk, weight_scale=1.0):
return q.new_empty((q.shape[0], topk), dtype=torch.int32)
@@ -6,7 +6,8 @@ import torch
import triton
import triton.language as tl
FP8_MAX = 448.0
FP8_MAX = tl.constexpr(448.0)
FP8_MIN = tl.constexpr(-448.0)
MIN_SCALE = 1e-4
GROUP_ALIGNMENT = 128
@@ -188,11 +189,11 @@ def _per_token_fp8_kernel(
mask=mask,
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=1)
scale = tl.maximum(amax / 448.0, 1e-4)
amax = tl.maximum(tl.max(tl.abs(x), axis=1), 1e-10)
scale = tl.math.div_rn(amax, FP8_MAX)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[:, None]
y = tl.clamp(tl.math.div_rn(x, scale[:, None]), FP8_MIN, FP8_MAX)
tl.store(
out_ptr + row_offsets_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
y.to(tl.float8e4nv),
@@ -242,11 +243,11 @@ def _grouped_per_token_fp8_kernel(
mask=valid_rows[:, None] & valid_cols[None, :],
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=1)
scale = tl.maximum(amax / 448.0, 1e-4)
amax = tl.maximum(tl.max(tl.abs(x), axis=1), 1e-10)
scale = tl.math.div_rn(amax, FP8_MAX)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[:, None]
y = tl.clamp(tl.math.div_rn(x, scale[:, None]), FP8_MIN, FP8_MAX)
tl.store(
out_ptr + dst_rows_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
y.to(tl.float8e4nv),
@@ -295,11 +296,11 @@ def _grouped_per_channel_fp8_kernel(
mask=valid_rows[:, None] & valid_cols[None, :],
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=0)
scale = tl.maximum(amax / 448.0, 1e-4)
amax = tl.maximum(tl.max(tl.abs(x), axis=0), 1e-10)
scale = tl.math.div_rn(amax, FP8_MAX)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[None, :]
y = tl.clamp(tl.math.div_rn(x, scale[None, :]), FP8_MIN, FP8_MAX)
flat_base = block_start.to(tl.int64) * BLOCK_K * cols
if K_MAJOR:
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
@@ -355,7 +356,7 @@ def _grouped_per_block_fp8_kernel(
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x))
scale = tl.maximum(amax / 448.0, 1e-4)
scale = tl.maximum(amax / FP8_MAX, 1e-4)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale
@@ -426,7 +427,7 @@ def per_token_cast_to_fp8_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_M=32,
BLOCK_K=gran_k,
num_warps=4,
)
@@ -453,7 +454,7 @@ def grouped_per_token_cast_to_fp8_triton(
)
if block_to_group.numel() == 0:
return out, sf
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 8, ceil_div(x.size(1), gran_k))
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 32, ceil_div(x.size(1), gran_k))
_grouped_per_token_fp8_kernel[grid](
x,
block_to_group,
@@ -470,7 +471,7 @@ def grouped_per_token_cast_to_fp8_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_M=32,
BLOCK_K=gran_k,
GROUP_BLOCK_M=GROUP_ALIGNMENT,
num_warps=4,
@@ -496,7 +497,8 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
if block_to_group.numel() == 0:
return out, sf.T
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
block_n = 16
grid = (block_to_group.numel(), ceil_div(x.size(1), block_n))
_grouped_per_channel_fp8_kernel[grid](
x,
block_to_group,
@@ -514,8 +516,8 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
USE_UE8M0=use_ue8m0,
K_MAJOR=True,
BLOCK_K=gran_k,
BLOCK_N=128,
num_warps=4,
BLOCK_N=block_n,
num_warps=2,
)
return out, sf.T
@@ -538,7 +540,8 @@ def grouped_per_channel_cast_to_fp8_rowmajor_triton(
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
if block_to_group.numel() == 0:
return out, sf
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
block_n = 64
grid = (block_to_group.numel(), ceil_div(x.size(1), block_n))
_grouped_per_channel_fp8_kernel[grid](
x,
block_to_group,
@@ -556,7 +559,7 @@ def grouped_per_channel_cast_to_fp8_rowmajor_triton(
USE_UE8M0=use_ue8m0,
K_MAJOR=False,
BLOCK_K=gran_k,
BLOCK_N=128,
BLOCK_N=block_n,
num_warps=4,
)
return out, sf
@@ -672,7 +675,7 @@ def per_token_cast_to_fp8_tp_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_M=32,
BLOCK_K=gran_k,
num_warps=4,
)
@@ -63,6 +63,10 @@ def test_selective_policy_saves_default_and_custom_targets():
_selective_checkpoint_policy(context, torch.ops.aten.topk.default, targets=custom_targets)
is CheckpointPolicy.MUST_SAVE
)
assert (
_selective_checkpoint_policy(context, torch.ops.prime_rl.fp8_indexer.default, targets=custom_targets)
is CheckpointPolicy.MUST_SAVE
)
@pytest.mark.parametrize("mode", ["full", "selective"])
@@ -99,6 +103,7 @@ def test_mandatory_policy_only_retains_non_replayable_ops():
context = SelectiveCheckpointContext(is_recompute=False)
assert _mandatory_checkpoint_policy(context, torch.ops.aten.topk.default) is CheckpointPolicy.MUST_SAVE
assert _mandatory_checkpoint_policy(context, torch.ops.prime_rl.fp8_indexer.default) is CheckpointPolicy.MUST_SAVE
assert (
_mandatory_checkpoint_policy(context, torch.ops.prime_rl.record_moe_routing_statistics.default)
is CheckpointPolicy.MUST_SAVE
@@ -1246,6 +1246,12 @@ def test_context_parallel_shards_reproduce_the_whole_row(layer_idx, cp_world_siz
for cp_rank, chunk in enumerate(chunks):
gather, pending = _fake_gather_for_cp(projections, chunks, cp_rank)
monkeypatch.setattr(dsv4_attention, "gather_for_cp", gather)
monkeypatch.setattr(
torch.ops._c10d_functional,
"all_gather_into_tensor",
lambda tensor, group_size, group_name: gather(tensor.movedim(0, 1), None).movedim(1, 0).contiguous(),
)
monkeypatch.setattr(dsv4_attention.funcol, "wait_tensor", lambda tensor: tensor)
module.cp_context = CPContext(MagicMock(), cp_rank, cp_world_size, "ring")
packed = _packed_context(doc_lens, torch.float32, V4FLASH_CONFIG, cp_rank=cp_rank, cp_world_size=cp_world_size)
+22
View File
@@ -47,3 +47,25 @@ def test_token_tp_cast_matches_materialized_transpose(rows, cols):
assert tp_q.is_contiguous()
assert torch.equal(tp_q.view(torch.uint8), ref_q.view(torch.uint8))
assert torch.equal(tp_s, ref_s)
@pytest.mark.parametrize(
"rows,cols,input_scale",
[(256, 256, 1.0), (256, 512, 0.3), (512, 256, 0.02), (1024, 768, 0.02), (384, 128, 0.005)],
)
def test_token_cast_matches_vllm_cuda_quant(rows, cols, input_scale):
"""The per-token cast is *bit-identical* to vLLM's production CUDA quantizer."""
pytest.importorskip("vllm")
from vllm.model_executor.layers.quantization.utils.fp8_utils import per_token_group_quant_fp8
torch.manual_seed(rows + cols)
x = torch.randn(rows, cols, device="cuda", dtype=torch.bfloat16) * input_scale
assert x.is_contiguous()
ref_q, ref_s = per_token_group_quant_fp8(x, 128, use_ue8m0=False)
q, s = per_token_cast_to_fp8_triton(x, False)
assert q.shape == ref_q.shape == (rows, cols)
assert s.shape == ref_s.shape == (rows, cols // 128)
assert torch.equal(s, ref_s)
assert torch.equal(q.view(torch.uint8), ref_q.view(torch.uint8))
Generated
+1 -2
View File
@@ -7740,7 +7740,6 @@ ta = [
requires-dist = [
{ name = "aiohttp", specifier = ">=3.14.1" },
{ name = "anthropic", specifier = ">=1.0.0" },
{ name = "datasets", marker = "extra == 'lean'", specifier = ">=3.3.0,<6.0.0" },
{ name = "gepa", specifier = ">=0.0.6" },
{ name = "h11", specifier = ">=0.16.0" },
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.21.0" },
@@ -7769,7 +7768,7 @@ requires-dist = [
{ name = "typing-extensions", specifier = ">=4.12.2" },
{ name = "uvicorn", specifier = ">=0.52.0" },
]
provides-extras = ["harbor", "lean", "modal", "openenv", "ta"]
provides-extras = ["harbor", "modal", "openenv", "ta"]
[package.metadata.requires-dev]
dev = [