Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3cc565eecb | ||
|
|
f52f6a69df | ||
|
|
9cc215df69 | ||
|
|
13c82f0551 | ||
|
|
7d25aaa0d2 | ||
|
|
5a0c80e54a | ||
|
|
e48c943c48 | ||
|
|
e521297df6 | ||
|
|
1556db6ca7 | ||
|
|
f984dee559 | ||
|
|
c1c1fe7e14 | ||
|
|
bdaafc35ab | ||
|
|
48aa99fbb5 | ||
|
|
94dff2ca54 | ||
|
|
4723b0ee5a | ||
|
|
b695a0aeda | ||
|
|
753cfb5a42 | ||
|
|
33e02a7a18 | ||
|
|
94f359e8d6 | ||
|
|
cf400e7db9 | ||
|
|
8da21f16b8 | ||
|
|
ae37b35a34 | ||
|
|
77788ba020 | ||
|
|
ab85b3b369 | ||
|
|
de5cdb8bae |
@@ -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
|
||||
|
||||
@@ -113,15 +113,6 @@ uv sync --all-extras
|
||||
|
||||
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
|
||||
|
||||
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
|
||||
|
||||
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
|
||||
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`
|
||||
|
||||
```bash
|
||||
uv pip install "flash-attn-3 @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=hopper" --no-build-isolation
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
@@ -148,19 +139,13 @@ uv run python -c "import flash_attn"
|
||||
uv run sft @ configs/debug/fake/sft.toml
|
||||
```
|
||||
|
||||
4. Check that you can run the RL trainer (*this requires 1 GPU*)
|
||||
|
||||
```bash
|
||||
uv run trainer @ configs/debug/fake/rl.toml
|
||||
```
|
||||
|
||||
5. Check that you can run the inference server (*this requires 1 GPU*)
|
||||
4. Check that you can run the inference server (*this requires 1 GPU*)
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
```
|
||||
|
||||
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
|
||||
5. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/reverse-text/rl.toml
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: 1213b7336d...b677502a20
Vendored
+1
-1
Submodule deps/verifiers updated: ceecc4d422...69cc0f948e
+2
-2
@@ -274,8 +274,8 @@ To benchmark a parallelism config before committing a multi-day run, run a short
|
||||
# SFT trainer alone
|
||||
uv run sft @ sft.toml --data.type fake --max-steps 4
|
||||
|
||||
# RL trainer alone (no inference involved)
|
||||
uv run trainer @ train.toml --data.fake --max-steps 4
|
||||
# RL trainer alone (no inference involved) -- launch it under torchrun, like the `rl` launcher does
|
||||
uv run torchrun --nproc-per-node=8 src/prime_rl/trainer/rl/train.py @ train.toml --data.fake --max-steps 4
|
||||
```
|
||||
|
||||
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
|
||||
|
||||
+1
-2
@@ -35,8 +35,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
| `uv run rl` | Wraps the trainer, orchestrator, and inference server in one launch from a merged TOML. | The default for any RL run. Runs locally for single-node experiments; submits to SLURM for single- or multi-node when `[slurm]` is set (see [Scaling § SLURM](scaling.md#slurm)). |
|
||||
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
|
||||
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
|
||||
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
|
||||
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
|
||||
|
||||
|
||||
@@ -100,3 +100,18 @@ Pass several output directories to track parallel experiments side by side (`uv
|
||||
Both RL configs ship without `[ckpt]` — add a `[ckpt]` overlay (e.g. `interval = 100`) for periodic checkpoints. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
|
||||
|
||||
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
|
||||
|
||||
## SFT
|
||||
|
||||
The SFT configs live under [`sft/h200/`](sft/h200) — they are tuned for 8-GPU H200 nodes. Compose the base config with a data overlay:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml
|
||||
```
|
||||
|
||||
This will start a SFT run with the following configuration:
|
||||
|
||||
- The model is `zai-org/GLM-5.3-BF16`
|
||||
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
|
||||
|
||||
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
clean = true
|
||||
|
||||
[env_vars]
|
||||
HF_HOME = "/home/huggingface"
|
||||
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2"
|
||||
cp = 8
|
||||
ep = 8
|
||||
optim_cpu_offload = true
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[optim]
|
||||
type = "sign_sgd"
|
||||
lr = 5e-5
|
||||
weight_decay = 0.01
|
||||
|
||||
[scheduler]
|
||||
type = "linear"
|
||||
warmup_steps = 50
|
||||
decay_steps = 0
|
||||
|
||||
[renderer]
|
||||
name = "glm-5.3"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 8
|
||||
|
||||
[slurm]
|
||||
job_name = "glm53-sft"
|
||||
partition = "all"
|
||||
@@ -0,0 +1,8 @@
|
||||
[model.debug]
|
||||
force_balanced_routing = true
|
||||
|
||||
[data]
|
||||
type = "fake"
|
||||
batch_size = 8
|
||||
micro_batch_size = 1
|
||||
seq_len = 131072
|
||||
@@ -0,0 +1,7 @@
|
||||
[data]
|
||||
type = "sft"
|
||||
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
|
||||
splits = ["math"]
|
||||
batch_size = 8
|
||||
micro_batch_size = 1
|
||||
seq_len = 131072
|
||||
@@ -5,7 +5,7 @@ from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig, RunConfig
|
||||
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
|
||||
@@ -21,6 +21,18 @@ 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."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat for the run: one ping per landed episode — the first
|
||||
landed episode is the first beat, so the run's boot never shows up as a
|
||||
stale-prone silence. When episodes stop landing, the pings stop and the heartbeat
|
||||
goes stale on Better Stack after its grace period. Size that period + grace above
|
||||
the longest legitimate gap between episodes."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str | None]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
|
||||
@@ -311,7 +311,7 @@ class VllmRouterConfig(BaseConfig):
|
||||
|
||||
type: Literal["vllm-router"] = "vllm-router"
|
||||
|
||||
request_timeout_secs: int = Field(1800, ge=1)
|
||||
request_timeout_secs: int = Field(14400, ge=1)
|
||||
"""Maximum lifetime of a routed request, including streamed completions."""
|
||||
|
||||
policy: str = "sticky_least_loaded"
|
||||
|
||||
@@ -91,6 +91,9 @@ class SFTDataConfig(BaseDataConfig):
|
||||
name: str = "PrimeIntellect/Reverse-Text-SFT"
|
||||
"""HF dataset name or path."""
|
||||
|
||||
revision: str | None = None
|
||||
"""HF dataset revision to load. Ignored for a local path."""
|
||||
|
||||
subsets: list[str] | None = None
|
||||
"""Subsets to load from the HF dataset."""
|
||||
|
||||
|
||||
@@ -85,6 +85,9 @@ class CompileConfig(BaseConfig):
|
||||
fullgraph: bool = False
|
||||
"""Compile transformer blocks with ``fullgraph=True``."""
|
||||
|
||||
mode: Literal["reduce-overhead", "max-autotune", "max-autotune-no-cudagraphs", "lite"] | None = None
|
||||
"""``torch.compile`` mode. ``reduce-overhead`` records CUDA graphs to cut kernel launch overhead; ``max-autotune`` modes trade longer compile times for tuned kernels (``max-autotune`` also records CUDA graphs, ``max-autotune-no-cudagraphs`` does not). CUDA-graphed layers re-record on new input shapes. ``None`` uses PyTorch's default mode."""
|
||||
|
||||
|
||||
class FusionsConfig(BaseConfig):
|
||||
enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"]
|
||||
|
||||
+5
-2
@@ -172,10 +172,13 @@ members = [
|
||||
"deps/verifiers/environments/wordle",
|
||||
]
|
||||
# tau2-synth and tau3-bench pin `tau2` forks/revs that conflict with the
|
||||
# canonical tau2-bench; a workspace shares one lock, so these can't coexist.
|
||||
# canonical tau2-bench; apex-agents pins `verifiers` as a git rev instead of
|
||||
# the editable workspace member. A workspace shares one lock, so these can't
|
||||
# coexist.
|
||||
exclude = [
|
||||
"deps/prime-envs/environments/tool_use/tau2_synth",
|
||||
"deps/prime-envs/environments/tool_use/tau3_bench",
|
||||
"deps/prime-envs/environments/tool_use/apex_agents",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
@@ -264,7 +267,7 @@ torchao = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "99e5f7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "6f9242d" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
|
||||
vllm-router = [
|
||||
{ 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'" },
|
||||
|
||||
@@ -1536,7 +1536,7 @@ def row_filter(
|
||||
return False
|
||||
if episode is not None and row.get("id") != episode:
|
||||
return False
|
||||
if errors_only and not (row.get("num_errors") or not row.get("ok")):
|
||||
if errors_only and row.get("ok"):
|
||||
return False
|
||||
arrival = row.get("arrival") or 0
|
||||
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
|
||||
|
||||
@@ -1176,7 +1176,7 @@ function summaryTilesHtml(idx, all, scoreEntries) {
|
||||
}
|
||||
// failure rates count every landed episode, the errors filter notwithstanding
|
||||
if (all.length) {
|
||||
const errored = all.filter((i) => series.ok?.[i] === false || (series.num_errors?.[i] ?? 0) > 0).length;
|
||||
const errored = all.filter((i) => series.ok?.[i] === false).length;
|
||||
const truncated = all.filter((i) => (series.truncated?.[i] ?? TRUNCATING_STOPS.has(series.stop_condition?.[i])) === true).length;
|
||||
for (const [label, n, what] of [["error rate", errored, "errored"], ["truncation rate", truncated, "truncated"]]) {
|
||||
const rate = n / all.length;
|
||||
@@ -3022,10 +3022,12 @@ function fmtSpan(dispatched, arrived, elapsed) {
|
||||
}
|
||||
|
||||
function episodeRowHtml(ep) {
|
||||
const failed = !ep.ok || !!ep.num_errors;
|
||||
// an ok episode keeps the errors of the attempts it recovered from; they mark the
|
||||
// row as retried, not as failed
|
||||
const failed = !ep.ok;
|
||||
const phase = failed ? "error" : "done";
|
||||
const dispatched = ep.dispatch ?? (ep.arrival != null && ep.duration != null ? ep.arrival - ep.duration : null);
|
||||
return `<tr data-line="${ep.line}" class="${failed ? "err" : ""}"${failed ? ` title="${ep.num_errors || 1} error${ep.num_errors === 1 ? "" : "s"}"` : ""}>
|
||||
return `<tr data-line="${ep.line}" class="${episodeRowClass(ep)}" title="${esc(episodeRowTitle(ep))}">
|
||||
<td class="muted">${ep.line}</td>
|
||||
<td><span class="badge stage stage-${phase}">${phase}</span></td>
|
||||
<td class="muted nowrap">${fmtSpan(dispatched, ep.arrival, ep.duration)}</td>
|
||||
@@ -3209,7 +3211,7 @@ async function openLiveTrace(traceId, { refresh = false } = {}) {
|
||||
semanticExpandedRuns.clear();
|
||||
clearSemanticTranscriptOrigin();
|
||||
$("#sg-inspector").hidden = true;
|
||||
$("#tm-messages").innerHTML = `<div class="chart-empty">loading live trace…</div>`;
|
||||
resetTranscript(`<div class="chart-empty">loading live trace…</div>`);
|
||||
$("#tm-timeline").innerHTML = "";
|
||||
$("#tm-meta").innerHTML = "";
|
||||
}
|
||||
@@ -3325,7 +3327,7 @@ function tmItemHtml(item) {
|
||||
}
|
||||
const e = item;
|
||||
return (
|
||||
`<div class="tm-item ${rolloutActive(item) ? "active" : ""}${e.num_errors || !e.ok ? " err" : ""}" data-line="${e.line}">` +
|
||||
`<div class="tm-item ${rolloutActive(item) ? "active" : ""} ${episodeRowClass(e)}" data-line="${e.line}" title="${esc(episodeRowTitle(e))}">` +
|
||||
`<span class="tm-num">#${e.line}</span><span class="tm-env muted" title="${esc(e.env ?? "")}">${esc(e.env ?? "")}</span>` +
|
||||
`<span class="tm-reward ${rewardClass(e.reward)}">${fmtReward(e.reward)}</span></div>`
|
||||
);
|
||||
@@ -3426,7 +3428,7 @@ async function modalStep(delta) {
|
||||
currentLine = null;
|
||||
currentEpisode = null;
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = emptyState("no episodes", "this step has no rollouts for the current filters");
|
||||
resetTranscript(emptyState("no episodes", "this step has no rollouts for the current filters"));
|
||||
$("#tm-meta").innerHTML = "";
|
||||
}
|
||||
}
|
||||
@@ -3474,6 +3476,15 @@ async function ensureTokens() {
|
||||
currentEpisode = episode;
|
||||
}
|
||||
|
||||
/* Every path that replaces the transcript with a placeholder goes through here, so the
|
||||
previous episode's error strip never outlives its episode. */
|
||||
function resetTranscript(html) {
|
||||
const episodeErrors = $("#tm-episode-errors");
|
||||
episodeErrors.hidden = true;
|
||||
episodeErrors.innerHTML = "";
|
||||
$("#tm-messages").innerHTML = html;
|
||||
}
|
||||
|
||||
async function openEpisode(line, target = {}) {
|
||||
currentLive = null;
|
||||
$("#tm-live-label").textContent = "";
|
||||
@@ -3486,7 +3497,7 @@ async function openEpisode(line, target = {}) {
|
||||
currentEpisode = null;
|
||||
renderModalStep();
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
|
||||
resetTranscript(`<div class="chart-empty">loading episode…</div>`);
|
||||
const timelineTarget = $("#tm-timeline");
|
||||
timelineTarget.classList.remove("semantic-canvas");
|
||||
delete timelineTarget.dataset.semanticEpisode;
|
||||
@@ -3940,7 +3951,7 @@ function judgeEvidenceHtml(trace) {
|
||||
|
||||
function renderedTokensHtml(trace, branches) {
|
||||
const rendered = trace.rendered_tokens;
|
||||
const errors = errorBannersHtml(episodeErrors(currentEpisode, trace));
|
||||
const errors = scopedErrorsHtml("trace", scopedErrors(currentEpisode, trace).trace);
|
||||
if (!rendered) return errors + emptyState("rendered text not loaded", "select this view again to load recorded token IDs");
|
||||
const path = currentPath(trace, branches);
|
||||
const tokenCount = path.reduce((count, index) => count + (trace.nodes[index]?.token_ids?.length || 0), 0);
|
||||
@@ -3980,43 +3991,67 @@ function renderedBoxHtml(tokenCount, body, canCopyText) {
|
||||
|
||||
let entriesObserver = null;
|
||||
|
||||
function episodeErrors(ep, trace) {
|
||||
// one failure is often recorded twice, on the episode and on its trace; show it
|
||||
// once, keeping whichever copy carries the traceback
|
||||
const byMessage = new Map();
|
||||
for (const error of [...(ep.errors || []), ...(trace?.errors || [])]) {
|
||||
const record = error && typeof error === "object" ? error : { message: String(error) };
|
||||
const key = `${record.type ?? "Error"}|${record.message ?? ""}`;
|
||||
const kept = byMessage.get(key);
|
||||
if (!kept || (!kept.traceback && record.traceback)) byMessage.set(key, record);
|
||||
/* Errors carried by the episode and by the open trace, each split by what they mean.
|
||||
Verifiers keeps every attempt's errors on the final record and stamps success as `ok`,
|
||||
so the errors of an ok episode or trace are history it recovered from, while a failed
|
||||
one's errors describe its outcome. A failure recorded on both the episode and its
|
||||
trace shows once, as the trace's, keeping whichever copy carries the traceback. */
|
||||
function scopedErrors(ep, trace) {
|
||||
const record = (error) => (error && typeof error === "object" ? error : { message: String(error) });
|
||||
const key = (r) => `${r.type ?? "Error"}|${r.message ?? ""}`;
|
||||
const keep = (map, r) => {
|
||||
const kept = map.get(key(r));
|
||||
if (!kept || (!kept.traceback && r.traceback)) map.set(key(r), r);
|
||||
};
|
||||
const onTrace = new Map();
|
||||
for (const error of trace?.errors || []) keep(onTrace, record(error));
|
||||
const onEpisode = new Map();
|
||||
for (const error of ep.errors || []) {
|
||||
const r = record(error);
|
||||
if (onTrace.has(key(r))) keep(onTrace, r);
|
||||
else keep(onEpisode, r);
|
||||
}
|
||||
return [...byMessage.values()];
|
||||
const split = (records, ok) => ({ failed: ok ? [] : records, recovered: ok ? records : [] });
|
||||
return { episode: split([...onEpisode.values()], ep.ok), trace: split([...onTrace.values()], trace?.ok) };
|
||||
}
|
||||
|
||||
function errorBannersHtml(errors) {
|
||||
if (!errors.length) return "";
|
||||
function errorEntryHtml(scope, record) {
|
||||
const type = record.type ?? "Error";
|
||||
const message = record.message ?? "No error message";
|
||||
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
|
||||
return (
|
||||
`<div class="trace-errors">` +
|
||||
errors
|
||||
.map((error) => {
|
||||
const record = error && typeof error === "object" ? error : { message: String(error) };
|
||||
const type = record.type ?? "Error";
|
||||
const message = record.message ?? "No error message";
|
||||
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
|
||||
return (
|
||||
`<section class="trace-error-banner">` +
|
||||
`<div class="trace-error-message"><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
|
||||
(traceback
|
||||
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
|
||||
: "") +
|
||||
`</section>`
|
||||
);
|
||||
})
|
||||
.join("") +
|
||||
`</div>`
|
||||
`<div class="trace-error-message"><span class="trace-error-scope">${scope} error</span><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
|
||||
(traceback
|
||||
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
|
||||
: "")
|
||||
);
|
||||
}
|
||||
|
||||
function scopedErrorsHtml(scope, { failed, recovered }) {
|
||||
const banners = failed.length
|
||||
? `<div class="trace-errors">${failed.map((record) => `<section class="trace-error-banner">${errorEntryHtml(scope, record)}</section>`).join("")}</div>`
|
||||
: "";
|
||||
const history = recovered.length
|
||||
? `<details class="trace-recovered"><summary><span>recovered from ${recovered.length} ${scope} error${recovered.length === 1 ? "" : "s"} in earlier attempts</span><span class="entry-chev">›</span></summary>` +
|
||||
recovered.map((record) => `<section class="trace-recovered-item">${errorEntryHtml(scope, record)}</section>`).join("") +
|
||||
`</details>`
|
||||
: "";
|
||||
return banners + history;
|
||||
}
|
||||
|
||||
function episodeRowClass(ep) {
|
||||
if (!ep.ok) return "err";
|
||||
return ep.num_errors ? "retried" : "";
|
||||
}
|
||||
|
||||
function episodeRowTitle(ep) {
|
||||
const n = ep.num_errors || 0;
|
||||
const errors = `${n || 1} error${n === 1 ? "" : "s"}`;
|
||||
if (!ep.ok) return errors;
|
||||
return n ? `recovered from ${errors} in earlier attempts` : "";
|
||||
}
|
||||
|
||||
|
||||
function normalizedCallUsage(usage = {}) {
|
||||
let input = usage.prompt_tokens;
|
||||
let cached = usage.cached_input_tokens;
|
||||
@@ -4036,7 +4071,7 @@ function normalizedCallUsage(usage = {}) {
|
||||
function renderMessages(ep, trace, branches) {
|
||||
const container = $("#tm-messages");
|
||||
entriesObserver?.disconnect();
|
||||
const errorsHtml = errorBannersHtml(episodeErrors(ep, trace));
|
||||
const errorsHtml = scopedErrorsHtml("trace", scopedErrors(ep, trace).trace);
|
||||
if (!trace) {
|
||||
container.innerHTML = errorsHtml + emptyState("no traces", "this episode carries no trace data");
|
||||
return;
|
||||
@@ -5487,12 +5522,17 @@ function renderEpisode() {
|
||||
const trace = traces[currentTraceIdx];
|
||||
const branches = trace ? traceBranches(trace) : [];
|
||||
if (currentBranchIdx >= branches.length) currentBranchIdx = 0;
|
||||
// the episode's own errors sit above the agent and branch selectors: they belong to
|
||||
// the whole episode, not to whichever trace is open
|
||||
const episodeErrors = $("#tm-episode-errors");
|
||||
episodeErrors.innerHTML = scopedErrorsHtml("episode", scopedErrors(ep, trace).episode);
|
||||
episodeErrors.hidden = !episodeErrors.innerHTML;
|
||||
const traceTabs = $("#tm-trace-tabs");
|
||||
traceTabs.hidden = traces.length <= 1;
|
||||
traceTabs.innerHTML =
|
||||
traces.length > 1
|
||||
? traces
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.join("")
|
||||
: "";
|
||||
const branchTabs = $("#tm-branch-tabs");
|
||||
@@ -6538,7 +6578,7 @@ async function reopenFirstEpisode() {
|
||||
currentLine = null;
|
||||
currentEpisode = null;
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = emptyState("no episodes", "nothing here for the current filters");
|
||||
resetTranscript(emptyState("no episodes", "nothing here for the current filters"));
|
||||
$("#tm-meta").innerHTML = "";
|
||||
}
|
||||
|
||||
|
||||
@@ -302,6 +302,7 @@
|
||||
<button id="tm-expand" class="btn">expand</button>
|
||||
<button id="drawer-close" class="btn">✕</button>
|
||||
</div>
|
||||
<div id="tm-episode-errors" hidden></div>
|
||||
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
|
||||
<div id="tm-trace-tabs" class="seg" hidden></div>
|
||||
<div id="tm-branch-tabs" class="seg" hidden></div>
|
||||
|
||||
@@ -834,6 +834,7 @@ mark.hit {
|
||||
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
|
||||
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
|
||||
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
|
||||
.tm-item.retried { border-left: 2px dotted var(--grey-4); }
|
||||
.tm-item .tm-reward { margin-left: auto; }
|
||||
.tm-nav { padding: 0 8px; height: 24px; }
|
||||
.tm-stephead { justify-content: space-between; background: var(--grey-2); min-height: 40px; }
|
||||
@@ -1169,7 +1170,7 @@ mark.hit {
|
||||
#sg-open-transcript { margin: 0 12px 12px; min-height: 30px; }
|
||||
|
||||
/* the banners lead the transcript, so they stand off the first entry */
|
||||
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
|
||||
.trace-errors { margin-top: auto; margin-bottom: 14px; }
|
||||
.trace-error-banner {
|
||||
border: 1px solid var(--negative);
|
||||
background: rgba(255, 69, 57, 0.08);
|
||||
@@ -1178,6 +1179,39 @@ mark.hit {
|
||||
.trace-error-banner + .trace-error-banner { margin-top: 8px; }
|
||||
.trace-error-message { padding: 10px 12px; font-size: 12px; white-space: pre-wrap; word-break: break-word; }
|
||||
.trace-error-type { font-weight: 500; color: var(--negative); }
|
||||
.trace-error-scope {
|
||||
display: inline-block;
|
||||
margin-right: 8px;
|
||||
padding: 1px 6px;
|
||||
border: 1px solid currentColor;
|
||||
font-size: 9px;
|
||||
line-height: 11px;
|
||||
letter-spacing: var(--track-mono);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
vertical-align: middle;
|
||||
}
|
||||
.trace-error-banner .trace-error-scope { color: var(--negative); }
|
||||
#tm-episode-errors { padding: 12px 16px 0; border-bottom: 1px solid var(--hairline); }
|
||||
#tm-episode-errors .trace-errors { margin-top: 0; margin-bottom: 12px; }
|
||||
#tm-episode-errors .trace-recovered { margin-bottom: 12px; }
|
||||
.trace-recovered { margin-bottom: 14px; border: 1px solid var(--grey-3); color: var(--grey-6); }
|
||||
.trace-recovered > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 12px;
|
||||
font-size: 11px;
|
||||
color: var(--grey-4);
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
}
|
||||
.trace-recovered > summary::-webkit-details-marker { display: none; }
|
||||
.trace-recovered[open] > summary .entry-chev { transform: rotate(90deg); }
|
||||
.trace-recovered-item { border-top: 1px solid var(--grey-3); }
|
||||
.trace-recovered-item .trace-error-type { color: var(--grey-4); }
|
||||
.trace-recovered-item .trace-error-tb > summary { border-top-color: var(--grey-3); }
|
||||
.seg button.err, .seg button.err.active { color: var(--negative); }
|
||||
.trace-error-tb > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1697,6 +1731,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
|
||||
place of their number set them apart */
|
||||
.live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); animation: live-pulse 2s ease-out infinite; }
|
||||
#episode-table tr.err td:first-child { border-left: 2px solid var(--negative); }
|
||||
#episode-table tr.retried td:first-child { border-left: 2px dotted var(--grey-4); }
|
||||
#episode-table tr.live.landing .live-dot { animation: none; opacity: 0.45; }
|
||||
.badge.stage { font-size: 9px; padding: 2px 5px; line-height: 12px; border-radius: 3px; background: var(--hairline); border-color: transparent; color: var(--accent); }
|
||||
#tm-live-label { margin-left: 8px; }
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -544,8 +543,12 @@ def sft(config: SFTConfig):
|
||||
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.trainer.sft.data import pre_download_data
|
||||
|
||||
pre_download_model(config.model.name, skip_weights=config.model.debug.random_init)
|
||||
pre_download_data(config.data, config.env_vars)
|
||||
if config.val is not None:
|
||||
pre_download_data(config.val.data, config.env_vars)
|
||||
|
||||
if config.slurm is not None:
|
||||
sft_slurm(config)
|
||||
|
||||
@@ -45,6 +45,7 @@ from prime_rl.orchestrator.utils import (
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
)
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_config_dir
|
||||
|
||||
@@ -71,11 +72,20 @@ class EvalRunner:
|
||||
self.dispatcher: Dispatcher | None = None
|
||||
self.inference_metrics: InferenceMetricsCollector | None = None
|
||||
self.periodic_logger: PeriodicLogger | None = None
|
||||
self.heart: Heartbeat | None = None
|
||||
|
||||
async def setup(self, *, skip_first_step: bool = False, is_resumed: bool = False) -> None:
|
||||
config = self.config
|
||||
set_default_executor()
|
||||
|
||||
# The heartbeat is beaten only by landed episodes — the first episode is its
|
||||
# first beat. No startup ping on purpose: the run-start to first-episode gap
|
||||
# (pool boot, env servers, the first episode's full duration) would otherwise
|
||||
# sit inside the ping stream as an abnormally long silence and flip a healthy
|
||||
# run stale. Until then the heartbeat has simply never been pinged.
|
||||
if config.heartbeat is not None:
|
||||
self.heart = Heartbeat(config.heartbeat.url)
|
||||
|
||||
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
|
||||
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
|
||||
self.run_name = os.environ.get("PRL_RUN_NAME")
|
||||
@@ -114,7 +124,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,
|
||||
@@ -224,6 +234,8 @@ class EvalRunner:
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
else:
|
||||
stamp_arrival([item], "eval", eval_work(item).step)
|
||||
if self.heart is not None:
|
||||
self.heart.beat()
|
||||
await self.land(item, pending)
|
||||
continue
|
||||
if eval_batch is not None:
|
||||
|
||||
@@ -20,6 +20,7 @@ def apply_shared_vllm_patches():
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
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()
|
||||
|
||||
@@ -41,6 +42,64 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
allow_deepseek_v4_layer_types()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_request_tools_placement():
|
||||
"""Attach request-level tools to the first existing DSV4 system message.
|
||||
|
||||
vLLM 0.29.0's Python DeepSeek-V4 tokenizer always prepends a synthetic
|
||||
system message for request-level tools. That puts the tool schema before
|
||||
an existing system prompt, unlike DeepSeek's reference encoder, vLLM's
|
||||
Rust renderer, and prime-rl's training renderer. Upstream fixed this in
|
||||
https://github.com/vllm-project/vllm/pull/51856 (commit 2909ad8f).
|
||||
The fix is expected to ship in vLLM 0.31.
|
||||
|
||||
Wrap the tokenizer factory so existing-system requests take the corrected
|
||||
path through the stock implementation: shallow-copy the conversation,
|
||||
attach tools to its first system message, and suppress the stock synthetic
|
||||
insertion. Requests without a system message retain the stock behavior.
|
||||
Remove this patch once the vLLM pin includes the upstream fix (likely 0.31).
|
||||
"""
|
||||
import copy
|
||||
|
||||
from vllm.tokenizers import deepseek_v4 as dsv4_tokenizer
|
||||
|
||||
original_get_tokenizer = dsv4_tokenizer.get_deepseek_v4_tokenizer
|
||||
if getattr(original_get_tokenizer, "_prime_rl_places_request_tools", False):
|
||||
return
|
||||
|
||||
def _get_deepseek_v4_tokenizer(tokenizer):
|
||||
wrapped = original_get_tokenizer(tokenizer)
|
||||
tokenizer_cls = wrapped.__class__
|
||||
original_apply_chat_template = tokenizer_cls.apply_chat_template
|
||||
|
||||
# Each factory call creates a fresh dynamic tokenizer subclass, but be
|
||||
# defensive if vLLM starts caching that class in a future release.
|
||||
if getattr(original_apply_chat_template, "_prime_rl_places_request_tools", False):
|
||||
return wrapped
|
||||
|
||||
def _apply_chat_template(self, messages, tools=None, **kwargs):
|
||||
if tools:
|
||||
conversation = kwargs.get("conversation", messages)
|
||||
system_idx = next(
|
||||
(i for i, message in enumerate(conversation) if message.get("role") == "system"),
|
||||
None,
|
||||
)
|
||||
if system_idx is not None:
|
||||
conversation = conversation.copy()
|
||||
conversation[system_idx] = copy.copy(conversation[system_idx])
|
||||
conversation[system_idx]["tools"] = tools
|
||||
kwargs["conversation"] = conversation
|
||||
tools = None
|
||||
|
||||
return original_apply_chat_template(self, messages, tools=tools, **kwargs)
|
||||
|
||||
_apply_chat_template._prime_rl_places_request_tools = True
|
||||
tokenizer_cls.apply_chat_template = _apply_chat_template
|
||||
return wrapped
|
||||
|
||||
_get_deepseek_v4_tokenizer._prime_rl_places_request_tools = True
|
||||
dsv4_tokenizer.get_deepseek_v4_tokenizer = _get_deepseek_v4_tokenizer
|
||||
|
||||
|
||||
def monkey_patch_online_fp8_parameter_cast():
|
||||
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
|
||||
|
||||
|
||||
@@ -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()},
|
||||
|
||||
@@ -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],
|
||||
}
|
||||
|
||||
|
||||
@@ -432,6 +432,13 @@ class Orchestrator:
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
# ``progress.step`` points at the next (unshipped) step; the last finished step is
|
||||
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
|
||||
# first ship). Saved before finalize, which tells the launcher the run is done.
|
||||
if self.config.ckpt is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
|
||||
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
|
||||
if clean_exit:
|
||||
get_logger().success(f"Orchestrator step loop done in {elapsed}")
|
||||
# The background loggers write through the monitors, so they must
|
||||
@@ -445,13 +452,6 @@ class Orchestrator:
|
||||
await monitors.finalize()
|
||||
else:
|
||||
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
|
||||
# ``progress.step`` points at the next (unshipped) step; the last finished step is
|
||||
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
|
||||
# first ship).
|
||||
if self.config.ckpt is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
|
||||
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
|
||||
await self.stop()
|
||||
if clean_exit:
|
||||
get_logger().success("Orchestrator finished")
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -268,8 +268,12 @@ class TorchTokenDispatcher(TokenDispatcherBase[TorchDispatchState]):
|
||||
ep_degree = self.group.size()
|
||||
with torch.no_grad():
|
||||
num_tokens_per_expert_group = all_to_all_single_equal(num_tokens_per_expert, self.group)
|
||||
input_splits = num_tokens_per_expert.view(ep_degree, -1).sum(dim=1)
|
||||
output_splits = num_tokens_per_expert_group.view(ep_degree, -1).sum(dim=1)
|
||||
input_splits, output_splits = torch.stack(
|
||||
(
|
||||
num_tokens_per_expert.view(ep_degree, -1).sum(dim=1),
|
||||
num_tokens_per_expert_group.view(ep_degree, -1).sum(dim=1),
|
||||
)
|
||||
).cpu() # Transfer to CPU now once, so a2a can read this without sync
|
||||
|
||||
routed_input = self._dispatch_tokens(routed_input, output_splits, input_splits)
|
||||
experts_per_rank = self.num_experts // ep_degree
|
||||
|
||||
@@ -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,
|
||||
@@ -833,8 +835,10 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
language_model = get_language_model(model)
|
||||
for layer_id in range(len(language_model.layers)):
|
||||
# Doing it in-place avoids mangled fqn which can break checkpoint loading
|
||||
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph)
|
||||
get_logger().info(f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph})")
|
||||
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
get_logger().info(
|
||||
f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph}, mode={compile_config.mode})"
|
||||
)
|
||||
|
||||
|
||||
def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
|
||||
@@ -850,9 +854,9 @@ def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
|
||||
replace_linear_with_fp8_blockwise_linear(model, ignore_modules=quant.ignore_patterns)
|
||||
elif isinstance(quant, MXFP8Config):
|
||||
capability = torch.cuda.get_device_capability()
|
||||
if capability != (10, 0):
|
||||
if capability[0] < 10:
|
||||
raise ValueError(
|
||||
f"MXFP8 quantization requires SM100 (Blackwell), but device is SM{capability[0]}{capability[1]}."
|
||||
f"MXFP8 quantization requires Blackwell (SM100+), but device is SM{capability[0]}{capability[1]}."
|
||||
)
|
||||
replace_linear_with_mxfp8_linear(model, recipe=quant.recipe, ignore_modules=quant.ignore_patterns)
|
||||
|
||||
@@ -910,14 +914,13 @@ def _validate_flash_attn_4_installed() -> None:
|
||||
def resolve_auto_attn(config: ModelConfig) -> None:
|
||||
"""Resolve ``attn='auto'`` to a concrete flash attention implementation based on GPU architecture.
|
||||
|
||||
FA4 on datacenter Blackwell (SM100), FA3 on Hopper (SM90), FA2 otherwise.
|
||||
Workstation Blackwell GPUs (e.g. RTX PRO 6000, SM120) lack FA4 kernels and
|
||||
can't run the Hopper-only FA3 kernels, so they fall back to FA2.
|
||||
FA4 on Blackwell or newer (SM100+, incl. SM103 B300/GB300), FA3 on Hopper (SM90),
|
||||
FA2 otherwise.
|
||||
"""
|
||||
if config.attn != "auto":
|
||||
return
|
||||
major, minor = torch.cuda.get_device_capability()
|
||||
if (major, minor) == (10, 0):
|
||||
if major >= 10:
|
||||
resolved = "flash_attention_4"
|
||||
elif major == 9:
|
||||
resolved = "flash_attention_3"
|
||||
|
||||
@@ -51,7 +51,6 @@ layers), built from one `seq_lens` and carrying:
|
||||
|
||||
- `position_ids`: each token's position within its own document.
|
||||
- `tok_doc_idx`: which document each token belongs to.
|
||||
- `position_embeddings`: the RoPE tables, one per rope type, evaluated at `position_ids`.
|
||||
- `window_indices`: for each query, the indices of the tokens its local window covers, causal
|
||||
and clipped at document boundaries, with `IGNORE_SLOT` (-1) marking invalid/masked entries.
|
||||
- `compression_layouts`: one `CompressionLayout` per compress rate in the architecture.
|
||||
@@ -97,13 +96,11 @@ holds it once and shares it across rates.
|
||||
Compression is only part of the story: every attention layer also reads a local sliding window of
|
||||
the most recent tokens directly, and the compressed entries are how it reaches anything older.
|
||||
That window is enumerated per document by `window_indices`, and every rotation in the block needs
|
||||
`position_ids` together with the RoPE tables evaluated at them, `position_embeddings`. None of
|
||||
those belongs to any single compress rate.
|
||||
`position_ids`. Neither belongs to any single compress rate.
|
||||
|
||||
`PackedContext.build` takes `seq_lens` and derives every one of its fields from it. Nothing else is
|
||||
an input, so a position that disagrees with a document boundary, a window slot that spans one, or a
|
||||
RoPE table evaluated at positions other than the ones the causal thresholds count in, cannot be
|
||||
constructed. It runs once per model forward.
|
||||
an input, so a position that disagrees with a document boundary or a window slot that spans one
|
||||
cannot be constructed. It runs once per model forward.
|
||||
|
||||
Context parallelism splits the queries across ranks and leaves everything else alone: every field
|
||||
above has one entry per query token and so covers this rank's `n_queries` tokens, while
|
||||
@@ -128,12 +125,14 @@ 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
|
||||
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4UnweightedRMSNorm
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_rope import dsv4_q_norm_rope, dsv4_rope
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.utils.cp import CPContext, gather_for_cp
|
||||
@@ -234,13 +233,12 @@ class CompressionLayout:
|
||||
class PackedContext:
|
||||
"""Everything an attention layer needs to know about the packed row it is running on.
|
||||
|
||||
The window indices, the positions, the RoPE tables and the layouts all encode the same
|
||||
document boundaries and are only correct together. As separate arguments they can contradict
|
||||
each other: a window enumerated without document boundaries spans documents while a layout
|
||||
does not, a sequence-global `position_ids` feeds `causal_threshold` a count that a
|
||||
per-document `entry_local_idx` cannot be compared against, and a RoPE table evaluated at one
|
||||
set of positions rotates queries the thresholds were not counted at. `build` derives every
|
||||
field from one `seq_lens`, so none of those is reachable. It runs once per model forward.
|
||||
The window indices, the positions and the layouts all encode the same document boundaries and
|
||||
are only correct together. As separate arguments they can contradict each other: a window
|
||||
enumerated without document boundaries spans documents while a layout does not, and a
|
||||
sequence-global `position_ids` feeds `causal_threshold` a count that a per-document
|
||||
`entry_local_idx` cannot be compared against. `build` derives every field from one `seq_lens`,
|
||||
so neither is reachable. It runs once per model forward.
|
||||
|
||||
Context parallelism gives each rank a contiguous run of `n_queries` tokens to use as queries
|
||||
and a full copy of the keys, so every field but `compression_layouts` has one entry per query
|
||||
@@ -250,7 +248,6 @@ class PackedContext:
|
||||
|
||||
position_ids: Tensor # (1, n_queries) int64 - token position within its own document
|
||||
tok_doc_idx: Tensor # (n_queries,) int64 - which document each query token belongs to
|
||||
position_embeddings: dict[str, tuple[Tensor, Tensor]] # (cos, sin) keyed by rope type, at `position_ids`
|
||||
window_indices: Tensor # (n_queries, sliding_window) int32 - global token per window slot, IGNORE_SLOT if unused
|
||||
compression_layouts: dict[int, CompressionLayout] # keyed by compress rate
|
||||
|
||||
@@ -260,17 +257,14 @@ class PackedContext:
|
||||
*,
|
||||
rotary_emb: DeepseekV4RotaryEmbedding,
|
||||
seq_lens: Tensor,
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
cp_rank: int = 0,
|
||||
cp_world_size: int = 1,
|
||||
) -> "PackedContext":
|
||||
"""Derive every field from one `seq_lens`, ensuring mutual consistency.
|
||||
|
||||
`rotary_emb` supplies the RoPE tables and, through the config it was built from, the
|
||||
sliding window and the compress rates in use. Taking the config from it rather than
|
||||
alongside it keeps them from naming different architectures. `dtype` must be the dtype
|
||||
attention runs at, since it types the RoPE tables. The sequence is as long as `seq_lens` says,
|
||||
`rotary_emb` supplies the sliding window, the compress rates in use and the positions its
|
||||
RoPE cache covers, all read from its config. The sequence is as long as `seq_lens` says,
|
||||
padding included: both packers fold their padding into the last document.
|
||||
|
||||
`seq_lens` always describes the whole sequence. `cp_rank` and `cp_world_size` say which
|
||||
@@ -283,6 +277,10 @@ class PackedContext:
|
||||
assert total_tokens % cp_world_size == 0, (
|
||||
f"{total_tokens} tokens do not split evenly across {cp_world_size} CP ranks"
|
||||
)
|
||||
# Document-local positions stay below the row's length; the RoPE kernels index the cache unchecked.
|
||||
assert total_tokens <= config.max_position_embeddings, (
|
||||
f"{total_tokens} tokens exceed the {config.max_position_embeddings} positions of the RoPE cache"
|
||||
)
|
||||
n_queries = total_tokens // cp_world_size
|
||||
q_start = cp_rank * n_queries
|
||||
|
||||
@@ -300,9 +298,6 @@ class PackedContext:
|
||||
# Document-local by construction: a token's position is its distance from its own
|
||||
# document's start, which is what `causal_threshold` and the entry rotation count in.
|
||||
position_ids = (tok_idx - cu_seqlens[tok_doc_idx])[None]
|
||||
position_embeddings = {
|
||||
rope_type: rotary_emb(position_ids, rope_type, dtype=dtype) for rope_type in rotary_emb.layer_types
|
||||
}
|
||||
|
||||
# A token attends the last `sliding_window` positions (itself included), clipped to its own
|
||||
# document.
|
||||
@@ -313,7 +308,6 @@ class PackedContext:
|
||||
return cls(
|
||||
position_ids=position_ids,
|
||||
tok_doc_idx=tok_doc_idx,
|
||||
position_embeddings=position_embeddings,
|
||||
compression_layouts={
|
||||
rate: CompressionLayout.build(cu_seqlens=cu_seqlens, compress_rate=rate) for rate in compress_rates
|
||||
},
|
||||
@@ -427,7 +421,14 @@ class DeepseekV4Compressor(nn.Module):
|
||||
|
||||
rope_layer_type = "compress"
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, head_dim: int, compress_rate: int, n_series: int):
|
||||
def __init__(
|
||||
self,
|
||||
config: DeepseekV4Config,
|
||||
head_dim: int,
|
||||
compress_rate: int,
|
||||
n_series: int,
|
||||
rotary_emb: DeepseekV4RotaryEmbedding,
|
||||
):
|
||||
super().__init__()
|
||||
if n_series not in (1, 2):
|
||||
raise ValueError(f"n_series must be 1 or 2, got {n_series}")
|
||||
@@ -438,7 +439,7 @@ class DeepseekV4Compressor(nn.Module):
|
||||
self.gate_proj = nn.Linear(config.hidden_size, n_series * head_dim, bias=False)
|
||||
self.position_bias = nn.Parameter(torch.zeros(compress_rate, n_series * head_dim))
|
||||
self.kv_norm = RMSNorm(RMSNormConfig(hidden_size=head_dim, eps=config.rms_norm_eps))
|
||||
self.rotary_emb = DeepseekV4RotaryEmbedding(config)
|
||||
self.rotary_emb = rotary_emb
|
||||
|
||||
def _overlap_with_previous_window(
|
||||
self, kv: torch.Tensor, gate: torch.Tensor, layout: CompressionLayout
|
||||
@@ -468,7 +469,6 @@ class DeepseekV4Compressor(nn.Module):
|
||||
cp_world_size: int = 1,
|
||||
) -> torch.Tensor:
|
||||
"""Compress `(batch, seq_len, hidden_size)` to `(batch, n_entries, head_dim)`."""
|
||||
batch = hidden_states.shape[0]
|
||||
layout = packed.compression_layouts[self.compress_rate]
|
||||
|
||||
width = self.n_series * self.head_dim
|
||||
@@ -487,10 +487,8 @@ class DeepseekV4Compressor(nn.Module):
|
||||
compressed = self.kv_norm((kv * weights).sum(dim=2))
|
||||
|
||||
entry_first_tok_pos = layout.entry_local_idx * self.compress_rate
|
||||
cos, sin = self.rotary_emb(
|
||||
entry_first_tok_pos.unsqueeze(0).expand(batch, -1), self.rope_layer_type, dtype=compressed.dtype
|
||||
)
|
||||
return apply_rotary_pos_emb_interleaved(compressed.unsqueeze(1), cos, sin).squeeze(1)
|
||||
cos_sin_cache = self.rotary_emb.cos_sin_cache(self.rope_layer_type)
|
||||
return dsv4_rope(compressed.unsqueeze(2), cos_sin_cache, entry_first_tok_pos).squeeze(2)
|
||||
|
||||
def causal_threshold(self, position_ids: torch.Tensor) -> torch.Tensor:
|
||||
"""Number of compressed entries that query `t` may read, shaped like `position_ids`.
|
||||
@@ -514,13 +512,17 @@ class DeepseekV4Indexer(nn.Module):
|
||||
`IGNORE_SLOT` (-1).
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
def __init__(self, config: DeepseekV4Config, rotary_emb: DeepseekV4RotaryEmbedding):
|
||||
super().__init__()
|
||||
self.head_dim = config.index_head_dim
|
||||
self.num_heads = config.index_n_heads
|
||||
self.index_topk = config.index_topk
|
||||
self.compressor = DeepseekV4Compressor(
|
||||
config, self.head_dim, config.compress_rates["compressed_sparse_attention"], n_series=2
|
||||
config,
|
||||
self.head_dim,
|
||||
config.compress_rates["compressed_sparse_attention"],
|
||||
n_series=2,
|
||||
rotary_emb=rotary_emb,
|
||||
)
|
||||
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
|
||||
self.weights_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
|
||||
@@ -539,9 +541,9 @@ class DeepseekV4Indexer(nn.Module):
|
||||
compressed_kv = self.compressor.compress(hidden_states, packed, cp_group=cp_group, cp_world_size=cp_world_size)
|
||||
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)
|
||||
cos_sin_cache = self.compressor.rotary_emb.cos_sin_cache(self.compressor.rope_layer_type)
|
||||
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim)
|
||||
q = dsv4_rope(q, cos_sin_cache, packed.position_ids)
|
||||
w = self.weights_proj(hidden_states)
|
||||
|
||||
layout = packed.compression_layouts[self.compressor.compress_rate]
|
||||
@@ -569,9 +571,15 @@ class DeepseekV4CSACompressor(DeepseekV4Compressor):
|
||||
because the indexer only selects entries whose source tokens all lie at or before the query.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__(config, config.head_dim, config.compress_rates["compressed_sparse_attention"], n_series=2)
|
||||
self.indexer = DeepseekV4Indexer(config)
|
||||
def __init__(self, config: DeepseekV4Config, rotary_emb: DeepseekV4RotaryEmbedding):
|
||||
super().__init__(
|
||||
config,
|
||||
config.head_dim,
|
||||
config.compress_rates["compressed_sparse_attention"],
|
||||
n_series=2,
|
||||
rotary_emb=rotary_emb,
|
||||
)
|
||||
self.indexer = DeepseekV4Indexer(config, rotary_emb)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -603,8 +611,14 @@ class DeepseekV4HCACompressor(DeepseekV4Compressor):
|
||||
the rest with `IGNORE_SLOT` (-1), as the indexer's surplus picks do.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__(config, config.head_dim, config.compress_rates["heavily_compressed_attention"], n_series=1)
|
||||
def __init__(self, config: DeepseekV4Config, rotary_emb: DeepseekV4RotaryEmbedding):
|
||||
super().__init__(
|
||||
config,
|
||||
config.head_dim,
|
||||
config.compress_rates["heavily_compressed_attention"],
|
||||
n_series=1,
|
||||
rotary_emb=rotary_emb,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -654,7 +668,7 @@ class DeepseekV4Attention(nn.Module):
|
||||
which is how a layer sees past the window.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, layer_idx: int):
|
||||
def __init__(self, config: DeepseekV4Config, layer_idx: int, rotary_emb: DeepseekV4RotaryEmbedding):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
@@ -671,7 +685,7 @@ class DeepseekV4Attention(nn.Module):
|
||||
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=False)
|
||||
self.q_a_norm = RMSNorm(RMSNormConfig(hidden_size=config.q_lora_rank, eps=config.rms_norm_eps))
|
||||
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
|
||||
self.q_b_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
|
||||
self.q_b_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps, out_dtype=torch.float32)
|
||||
self.kv_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
|
||||
self.kv_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.o_a_proj = DeepseekV4GroupedLinear(
|
||||
@@ -681,6 +695,7 @@ class DeepseekV4Attention(nn.Module):
|
||||
)
|
||||
self.o_b_proj = nn.Linear(config.o_groups * config.o_lora_rank, config.hidden_size, bias=False)
|
||||
self.sinks = nn.Parameter(torch.zeros(self.num_heads))
|
||||
self.rotary_emb = rotary_emb
|
||||
# Raised here rather than from the first forward, where it would surface as an ImportError
|
||||
# or a tilelang compile failure a long way from the config that caused it.
|
||||
blocker = _kernel_blocker(self.num_heads, self.head_dim)
|
||||
@@ -688,7 +703,7 @@ class DeepseekV4Attention(nn.Module):
|
||||
raise ValueError(f"DeepSeek V4 cannot run the fused sparse-attention kernel: {blocker}")
|
||||
assert config.attention_dropout == 0.0, "the fused sparse attention kernel implements no dropout"
|
||||
compressor_class = COMPRESSOR_CLASSES[self.layer_type]
|
||||
self.compressor = compressor_class(config) if compressor_class is not None else None
|
||||
self.compressor = compressor_class(config, rotary_emb) if compressor_class is not None else None
|
||||
|
||||
self.cp_context = CPContext()
|
||||
|
||||
@@ -710,19 +725,24 @@ class DeepseekV4Attention(nn.Module):
|
||||
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
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)
|
||||
cos_sin_cache = self.rotary_emb.cos_sin_cache(self.rope_layer_type) # (max_position, qk_rope_head_dim)
|
||||
|
||||
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)
|
||||
kv = dsv4_rope(kv, cos_sin_cache, packed.position_ids)
|
||||
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 = dsv4_q_norm_rope(
|
||||
self.q_b_proj(q_residual).view(*hidden_shape), cos_sin_cache, packed.position_ids, self.q_b_norm.eps
|
||||
) # (b, t, h, d)
|
||||
|
||||
compressed = (
|
||||
self.compressor(
|
||||
@@ -736,6 +756,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 +766,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,
|
||||
@@ -752,7 +775,7 @@ class DeepseekV4Attention(nn.Module):
|
||||
|
||||
# The value stream is the key stream, so it arrived rotated. Rotating the output
|
||||
# by the conjugate angle at the query position cancels that out.
|
||||
attn_output = apply_rotary_pos_emb_interleaved(attn_output, cos, -sin, unsqueeze_dim=2)
|
||||
attn_output = dsv4_rope(attn_output, cos_sin_cache, packed.position_ids, inverse=True)
|
||||
|
||||
# (b, t, g, h * d // g) -> (b, t, g, l) -> (b, t, g * l)
|
||||
grouped = self.o_a_proj(attn_output.reshape(*input_shape, self.config.o_groups, -1)).flatten(2)
|
||||
|
||||
@@ -14,7 +14,43 @@ from torch import Tensor, nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext, SparseAttnInputs
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import apply_rotary_pos_emb_interleaved
|
||||
|
||||
|
||||
def rotate_half_interleaved(x: torch.Tensor) -> torch.Tensor:
|
||||
"""Rotate consecutive channel pairs: `(x0, x1, x2, x3, ...) -> (-x1, x0, -x3, x2, ...)`.
|
||||
|
||||
Not the same as `prime_rl.trainer.models.layers.rotary_emb.rotate_half`, which pairs
|
||||
channel `i` with channel `i + dim / 2` (the GPT-NeoX layout). DeepSeek-V4 stores each
|
||||
rotary pair adjacently, so the two are not interchangeable.
|
||||
"""
|
||||
x1 = x[..., 0::2]
|
||||
x2 = x[..., 1::2]
|
||||
return torch.stack((-x2, x1), dim=-1).flatten(-2)
|
||||
|
||||
|
||||
def apply_rotary_pos_emb_interleaved(
|
||||
x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
|
||||
) -> torch.Tensor:
|
||||
"""Apply interleaved RoPE to the trailing rotary slice of `x`.
|
||||
|
||||
`cos` and `sin` arrive at half width (one entry per interleaved pair) and are widened
|
||||
with `repeat_interleave`. Each head is laid out as `[nope | rope]`, so only the last
|
||||
`2 * cos.shape[-1]` channels rotate and the leading ones pass through untouched.
|
||||
The rotation itself runs in fp32 and is cast back to `x`'s dtype.
|
||||
|
||||
Args:
|
||||
x: Tensor whose last dimension is the head dimension.
|
||||
cos: Half-width cosines, shape `(batch, seq, rope_dim / 2)`.
|
||||
sin: Half-width sines, same shape as `cos`.
|
||||
unsqueeze_dim: Axis of `x` that `cos` / `sin` must broadcast over. Use `1` for a
|
||||
`(batch, heads, seq, head_dim)` layout and `2` for `(batch, seq, heads, head_dim)`.
|
||||
"""
|
||||
cos = cos.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
|
||||
sin = sin.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
|
||||
rope_dim = cos.shape[-1]
|
||||
nope, rope = x[..., :-rope_dim], x[..., -rope_dim:]
|
||||
rotated = ((rope.float() * cos) + (rotate_half_interleaved(rope).float() * sin)).to(x.dtype)
|
||||
return torch.cat([nope, rotated], dim=-1)
|
||||
|
||||
|
||||
def eager_attention_with_sinks(
|
||||
@@ -111,11 +147,11 @@ def eager_attention_forward(
|
||||
"""
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, module.head_dim)
|
||||
cos, sin = packed.position_embeddings[module.rope_layer_type]
|
||||
cos, sin = module.rotary_emb(packed.position_ids, module.rope_layer_type, dtype=torch.float32)
|
||||
|
||||
q_residual = module.q_a_norm(module.q_a_proj(hidden_states))
|
||||
q = module.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2)
|
||||
q = apply_rotary_pos_emb_interleaved(module.q_b_norm(q), cos, sin)
|
||||
q = apply_rotary_pos_emb_interleaved(module.q_b_norm(q), cos, sin).to(q.dtype)
|
||||
|
||||
kv = module.kv_norm(module.kv_proj(hidden_states))
|
||||
kv = kv.view(*kv.shape[:2], 1, module.head_dim)
|
||||
|
||||
@@ -44,10 +44,10 @@ class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
|
||||
dtype before mixing, so the residual keeps the dtype it entered with.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, layer_idx: int):
|
||||
def __init__(self, config: DeepseekV4Config, layer_idx: int, rotary_emb: DeepseekV4RotaryEmbedding):
|
||||
super().__init__()
|
||||
self.layer_idx = layer_idx
|
||||
self.self_attn = DeepseekV4Attention(config, layer_idx)
|
||||
self.self_attn = DeepseekV4Attention(config, layer_idx, rotary_emb)
|
||||
self.mlp = DeepseekV4MoE(config, layer_idx)
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
@@ -163,9 +163,8 @@ class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
# `to_empty()` leaves every buffer uninitialized and this runs before `dcp_load`, so a
|
||||
# buffer is restored either here or by the checkpoint. Rebuilt here are the ones no
|
||||
# checkpoint carries: the rotary tables (non-persistent, and there is one rotary per
|
||||
# compressor and per indexer on top of the model-level one, so every instance has to be
|
||||
# walked) and `tokens_per_expert`. The router's persistent buffers, `selection_bias` and a
|
||||
# checkpoint carries: the rotary tables (non-persistent, and the one rotary every attention
|
||||
# layer shares) and `tokens_per_expert`. The router's persistent buffers, `selection_bias` and a
|
||||
# hash layer's `tid2eid`, are in the checkpoint that `dcp_load` applies next, so they are
|
||||
# left to it.
|
||||
for module in self.modules():
|
||||
@@ -182,11 +181,15 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
# Shared by every attention layer instead of passing RoPE tensors through forward, which FSDP casts to bf16.
|
||||
self.rotary_emb = DeepseekV4RotaryEmbedding(config)
|
||||
self.layers = nn.ModuleList(
|
||||
[DeepseekV4DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
[
|
||||
DeepseekV4DecoderLayer(config, layer_idx, self.rotary_emb)
|
||||
for layer_idx in range(config.num_hidden_layers)
|
||||
]
|
||||
)
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.rotary_emb = DeepseekV4RotaryEmbedding(config)
|
||||
self.hc_head = DeepseekV4HyperHead(config)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
@@ -255,7 +258,6 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
|
||||
packed = PackedContext.build(
|
||||
rotary_emb=self.rotary_emb,
|
||||
seq_lens=seq_lens,
|
||||
dtype=inputs_embeds.dtype,
|
||||
device=inputs_embeds.device,
|
||||
cp_rank=cp_rank,
|
||||
cp_world_size=cp_world_size,
|
||||
|
||||
@@ -12,54 +12,19 @@ from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import Deepse
|
||||
SUPPORTED_ROPE_TYPES = frozenset({"default", "linear", "llama3", "proportional", "yarn"})
|
||||
|
||||
|
||||
def rotate_half_interleaved(x: torch.Tensor) -> torch.Tensor:
|
||||
"""Rotate consecutive channel pairs: `(x0, x1, x2, x3, ...) -> (-x1, x0, -x3, x2, ...)`.
|
||||
|
||||
Not the same as `prime_rl.trainer.models.layers.rotary_emb.rotate_half`, which pairs
|
||||
channel `i` with channel `i + dim / 2` (the GPT-NeoX layout). DeepSeek-V4 stores each
|
||||
rotary pair adjacently, so the two are not interchangeable.
|
||||
"""
|
||||
x1 = x[..., 0::2]
|
||||
x2 = x[..., 1::2]
|
||||
return torch.stack((-x2, x1), dim=-1).flatten(-2)
|
||||
|
||||
|
||||
def apply_rotary_pos_emb_interleaved(
|
||||
x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
|
||||
) -> torch.Tensor:
|
||||
"""Apply interleaved RoPE to the trailing rotary slice of `x`.
|
||||
|
||||
`cos` and `sin` arrive at half width (one entry per interleaved pair) and are widened
|
||||
with `repeat_interleave`. Each head is laid out as `[nope | rope]`, so only the last
|
||||
`2 * cos.shape[-1]` channels rotate and the leading ones pass through untouched.
|
||||
The rotation itself runs in fp32 and is cast back to `x`'s dtype.
|
||||
|
||||
Args:
|
||||
x: Tensor whose last dimension is the head dimension.
|
||||
cos: Half-width cosines, shape `(batch, seq, rope_dim / 2)`.
|
||||
sin: Half-width sines, same shape as `cos`.
|
||||
unsqueeze_dim: Axis of `x` that `cos` / `sin` must broadcast over. Use `1` for a
|
||||
`(batch, heads, seq, head_dim)` layout and `2` for `(batch, seq, heads, head_dim)`.
|
||||
"""
|
||||
cos = cos.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
|
||||
sin = sin.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
|
||||
rope_dim = cos.shape[-1]
|
||||
nope, rope = x[..., :-rope_dim], x[..., -rope_dim:]
|
||||
rotated = ((rope.float() * cos) + (rotate_half_interleaved(rope).float() * sin)).to(x.dtype)
|
||||
return torch.cat([nope, rotated], dim=-1)
|
||||
|
||||
|
||||
class DeepseekV4RotaryEmbedding(nn.Module):
|
||||
"""Rotary embedding carrying one inverse-frequency table per RoPE type.
|
||||
|
||||
DeepSeek-V4 keys its RoPE parameters by rope type (`main` / `compress`), which is
|
||||
independent of `config.layer_types`: sliding-window layers read `main`, the two
|
||||
compressed attention variants share `compress` with their compressor. Each type gets
|
||||
its own `<type>_inv_freq` / `<type>_original_inv_freq` buffers and
|
||||
`<type>_attention_scaling` scalar.
|
||||
its own `<type>_inv_freq` buffer and `<type>_attention_scaling` scalar.
|
||||
|
||||
Because the rotation is interleaved, `forward` returns `cos` / `sin` at half the
|
||||
rotary width (one entry per pair). `apply_rotary_pos_emb_interleaved` widens them.
|
||||
rotary width (one entry per pair).
|
||||
|
||||
Each type also keeps a static fp32 `<type>_cos_sin_cache`, `[cos | sin]` at every position in
|
||||
vLLM's layout, which the fused RoPE kernels index by position.
|
||||
|
||||
`rope_type` is checkpoint data rather than architecture: V4 ships `default` on `main` and
|
||||
`default` or `yarn` on `compress`, but the config reads whatever the file says. Anything
|
||||
@@ -70,8 +35,6 @@ class DeepseekV4RotaryEmbedding(nn.Module):
|
||||
def __init__(self, config: DeepseekV4Config, device: torch.device | None = None):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.max_seq_len_cached = config.max_position_embeddings
|
||||
self.original_max_seq_len = config.max_position_embeddings
|
||||
# Only the nested per-rope-type sub-dicts are real rope types; a flat leftover
|
||||
# `rope_type` key at the top level is not one.
|
||||
self.layer_types = [name for name, params in config.rope_parameters.items() if isinstance(params, dict)]
|
||||
@@ -86,8 +49,10 @@ class DeepseekV4RotaryEmbedding(nn.Module):
|
||||
)
|
||||
inv_freq, attention_scaling = self._rope_init_fn(layer_type)(config, device, layer_type=layer_type)
|
||||
self.register_buffer(f"{layer_type}_inv_freq", inv_freq, persistent=False)
|
||||
self.register_buffer(f"{layer_type}_original_inv_freq", inv_freq.clone(), persistent=False)
|
||||
setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
|
||||
self.register_buffer(
|
||||
f"{layer_type}_cos_sin_cache", self._compute_cos_sin_cache(layer_type), persistent=False
|
||||
)
|
||||
|
||||
def _rope_init_fn(self, layer_type: str) -> Callable[..., tuple[torch.Tensor, float]]:
|
||||
rope_type = self.rope_type[layer_type]
|
||||
@@ -96,7 +61,7 @@ class DeepseekV4RotaryEmbedding(nn.Module):
|
||||
return ROPE_INIT_FUNCTIONS[rope_type]
|
||||
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
"""Re-derive the per-rope-type inverse frequencies in place.
|
||||
"""Re-derive the per-rope-type inverse frequencies and cos/sin caches in place.
|
||||
|
||||
The tables are computed eagerly in `__init__` and registered non-persistently, so they
|
||||
survive neither meta-device construction nor a `load_state_dict`. Re-deriving them is
|
||||
@@ -108,8 +73,8 @@ class DeepseekV4RotaryEmbedding(nn.Module):
|
||||
self.config, inv_freq_buffer.device, layer_type=layer_type
|
||||
)
|
||||
inv_freq_buffer.copy_(inv_freq)
|
||||
getattr(self, f"{layer_type}_original_inv_freq").copy_(inv_freq)
|
||||
setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
|
||||
getattr(self, f"{layer_type}_cos_sin_cache").copy_(self._compute_cos_sin_cache(layer_type))
|
||||
|
||||
@staticmethod
|
||||
def compute_default_rope_parameters(
|
||||
@@ -139,17 +104,28 @@ class DeepseekV4RotaryEmbedding(nn.Module):
|
||||
|
||||
device_type = device.type if isinstance(device.type, str) and device.type != "mps" else "cpu"
|
||||
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
||||
# No `cat([freqs, freqs])`: interleaved RoPE needs one theta per pair, and
|
||||
# `apply_rotary_pos_emb_interleaved` widens cos/sin next to the rotation.
|
||||
# No `cat([freqs, freqs])`: interleaved RoPE needs one theta per pair.
|
||||
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
||||
cos = freqs.cos() * attention_scaling
|
||||
sin = freqs.sin() * attention_scaling
|
||||
|
||||
return cos.to(dtype=dtype), sin.to(dtype=dtype)
|
||||
|
||||
def _compute_cos_sin_cache(self, layer_type: str) -> torch.Tensor:
|
||||
"""`(max_position_embeddings, rope_dim)` fp32 `[cos | sin]` of `layer_type` at every position."""
|
||||
inv_freq = getattr(self, f"{layer_type}_inv_freq")
|
||||
if inv_freq.is_meta:
|
||||
return torch.empty(
|
||||
self.config.max_position_embeddings, 2 * inv_freq.shape[0], device="meta", dtype=torch.float32
|
||||
)
|
||||
# TODO: size to the run's seq_len; 1M positions cost 256 MiB per rope type.
|
||||
positions = torch.arange(self.config.max_position_embeddings, device=inv_freq.device)
|
||||
cos, sin = self(positions[None], layer_type, dtype=torch.float32)
|
||||
return torch.cat([cos[0], sin[0]], dim=-1)
|
||||
|
||||
__all__ = [
|
||||
"DeepseekV4RotaryEmbedding",
|
||||
"apply_rotary_pos_emb_interleaved",
|
||||
"rotate_half_interleaved",
|
||||
]
|
||||
def cos_sin_cache(self, layer_type: str) -> torch.Tensor:
|
||||
"""The fp32 `[cos | sin]` cache of `layer_type`, one row per position."""
|
||||
return getattr(self, f"{layer_type}_cos_sin_cache")
|
||||
|
||||
|
||||
__all__ = ["DeepseekV4RotaryEmbedding"]
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
# Adapted from https://github.com/NVIDIA/Megatron-LM/blob/c16d981ca/megatron/core/fusions/fused_mla_yarn_rope_apply.py (BSD-3, Copyright NVIDIA)
|
||||
"""Fused interleaved RoPE for DeepSeek-V4 attention, matching vLLM's numerics.
|
||||
|
||||
DeepSeek-V4 rotates only the trailing `rope_dim` channels of each head, with each rotary pair stored
|
||||
adjacently. Eagerly, every rotation widens the cos/sin tables and rebuilds the whole head with
|
||||
`torch.cat`, a large share of attention time. `dsv4_rope` rotates in one kernel pass, reading
|
||||
fp32 cos and sin from a `[cos | sin]` cache by position, bit for bit with vLLM's `rotary_embedding`.
|
||||
`dsv4_q_norm_rope` puts the query's RMSNorm in the same op so the query is rounded to bf16 once, as vLLM's
|
||||
fused prefill kernel does.
|
||||
"""
|
||||
|
||||
import torch
|
||||
import triton
|
||||
import triton.language as tl
|
||||
|
||||
from prime_rl.trainer.models.layers.norms import get_quack_rmsnorm
|
||||
|
||||
|
||||
@triton.autotune(
|
||||
configs=[triton.Config({"BLOCK_H": block_h}, num_warps=warps) for block_h in (1, 2, 4, 8, 16) for warps in (4, 8)],
|
||||
key=["num_heads", "head_dim"],
|
||||
)
|
||||
@triton.jit
|
||||
def _triton_rope_kernel(
|
||||
X,
|
||||
OUT,
|
||||
COS_SIN,
|
||||
POS,
|
||||
num_heads,
|
||||
head_dim: tl.constexpr,
|
||||
rope_dim: tl.constexpr,
|
||||
INVERSE: tl.constexpr,
|
||||
BLOCK_H: tl.constexpr,
|
||||
):
|
||||
"""Rotate the trailing `rope_dim` channels of `BLOCK_H` heads of one token and copy the rest."""
|
||||
token = tl.program_id(0).to(tl.int64)
|
||||
heads = tl.program_id(1) * BLOCK_H + tl.arange(0, BLOCK_H)
|
||||
rope_pairs = tl.arange(0, head_dim // 2) - (head_dim - rope_dim) // 2
|
||||
is_rope = (rope_pairs >= 0)[None, :]
|
||||
|
||||
cos_sin = COS_SIN + tl.load(POS + token).to(tl.int64) * rope_dim
|
||||
cos = tl.load(cos_sin + rope_pairs, mask=rope_pairs >= 0, other=1.0)
|
||||
sin = tl.load(cos_sin + rope_dim // 2 + rope_pairs, mask=rope_pairs >= 0, other=0.0)
|
||||
if INVERSE:
|
||||
sin = -sin
|
||||
|
||||
offsets = (token * num_heads + heads[:, None]) * head_dim + tl.arange(0, head_dim)[None, :]
|
||||
mask = heads[:, None] < num_heads
|
||||
x = tl.load(X + offsets, mask=mask).to(tl.float32)
|
||||
x1, x2 = tl.split(tl.reshape(x, (BLOCK_H, head_dim // 2, 2)))
|
||||
# vLLM's contraction: letting the compiler pick flips a bf16 ULP on ~1e-5 of the outputs.
|
||||
y1 = tl.where(is_rope, tl.fma(x1, cos, -(x2 * sin)), x1)
|
||||
y2 = tl.where(is_rope, tl.fma(x1, sin, x2 * cos), x2)
|
||||
y = tl.reshape(tl.join(y1, y2), (BLOCK_H, head_dim))
|
||||
tl.store(OUT + offsets, y.to(OUT.dtype.element_ty), mask=mask)
|
||||
|
||||
|
||||
def _triton_rope(
|
||||
x: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
position_ids: torch.Tensor,
|
||||
inverse: bool,
|
||||
out_dtype: torch.dtype | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Rotated copy of `x`, bypassing autograd, rounded once to `out_dtype` (default: `x`'s dtype)."""
|
||||
x = x.contiguous()
|
||||
out = x.new_empty(x.shape, dtype=out_dtype)
|
||||
if out.numel() == 0:
|
||||
return out
|
||||
num_heads, head_dim = x.shape[-2:]
|
||||
grid = lambda meta: (position_ids.numel(), triton.cdiv(num_heads, meta["BLOCK_H"]))
|
||||
_triton_rope_kernel[grid](
|
||||
x,
|
||||
out,
|
||||
cos_sin_cache,
|
||||
position_ids.contiguous(),
|
||||
num_heads,
|
||||
head_dim,
|
||||
cos_sin_cache.shape[-1],
|
||||
INVERSE=inverse,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_rope", mutates_args=())
|
||||
def dsv4_rope(
|
||||
x: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, *, inverse: bool = False
|
||||
) -> torch.Tensor:
|
||||
"""Interleaved RoPE on the trailing `rope_dim` channels of each head, bit for bit with vLLM's `rotary_embedding`.
|
||||
|
||||
With `x1 = x[..., 2i]` and `x2 = x[..., 2i + 1]` of the rotary slice, the output holds
|
||||
`x1 * cos - x2 * sin` and `x2 * cos + x1 * sin`, computed in fp32 with `cos` and `sin` read from row
|
||||
`position_ids[t]` of `cos_sin_cache` for token `t`; the leading channels are copied. `inverse=True`
|
||||
rotates by the opposite angle, which undoes the rotation.
|
||||
|
||||
Args:
|
||||
x: `(..., heads, head_dim)`, one entry of `position_ids` per token; `head_dim` a power of two.
|
||||
cos_sin_cache: `(max_position, rope_dim)` fp32 and contiguous, cos then sin, one entry per pair each.
|
||||
position_ids: int32 or int64, one per token, each in `[0, max_position)`.
|
||||
inverse: rotate by the opposite angle.
|
||||
"""
|
||||
return _triton_rope(x, cos_sin_cache, position_ids, inverse)
|
||||
|
||||
|
||||
@dsv4_rope.register_fake
|
||||
def _dsv4_rope_fake(
|
||||
x: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, *, inverse: bool = False
|
||||
) -> torch.Tensor:
|
||||
return x.new_empty(x.shape)
|
||||
|
||||
|
||||
def _dsv4_rope_setup_context(ctx, inputs, keyword_only_inputs, output) -> None:
|
||||
_, cos_sin_cache, position_ids = inputs
|
||||
ctx.save_for_backward(cos_sin_cache, position_ids)
|
||||
ctx.inverse = keyword_only_inputs["inverse"]
|
||||
|
||||
|
||||
def _dsv4_rope_autograd_backward(ctx, grad: torch.Tensor):
|
||||
cos_sin_cache, position_ids = ctx.saved_tensors
|
||||
return dsv4_rope(grad, cos_sin_cache, position_ids, inverse=not ctx.inverse), None, None
|
||||
|
||||
|
||||
dsv4_rope.register_autograd(_dsv4_rope_autograd_backward, setup_context=_dsv4_rope_setup_context)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_q_norm_rope", mutates_args=())
|
||||
def _dsv4_q_norm_rope(
|
||||
q: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, eps: float
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""The normed and rotated `q` in `q`'s dtype, plus the fp32 per-row `rstd` that backward needs."""
|
||||
rows = q.reshape(-1, q.shape[-1])
|
||||
if get_quack_rmsnorm() is not None:
|
||||
from quack.rmsnorm import rmsnorm_fwd
|
||||
|
||||
normed, _, rstd = rmsnorm_fwd(rows, out_dtype=torch.float32, eps=eps, store_rstd=True)
|
||||
else:
|
||||
rstd = torch.rsqrt(rows.float().square().mean(-1) + eps)
|
||||
normed = rows.float() * rstd[:, None]
|
||||
return _triton_rope(normed.view(q.shape), cos_sin_cache, position_ids, False, out_dtype=q.dtype), rstd
|
||||
|
||||
|
||||
@_dsv4_q_norm_rope.register_fake
|
||||
def _dsv4_q_norm_rope_fake(
|
||||
q: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, eps: float
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return q.new_empty(q.shape), q.new_empty(q.numel() // q.shape[-1], dtype=torch.float32)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_q_norm_rope_backward", mutates_args=())
|
||||
def _dsv4_q_norm_rope_backward(
|
||||
grad: torch.Tensor, q: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, rstd: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
rows = q.reshape(-1, q.shape[-1])
|
||||
grad_normed = _triton_rope(grad, cos_sin_cache, position_ids, True).view(rows.shape)
|
||||
if get_quack_rmsnorm() is not None:
|
||||
from quack.rmsnorm import rmsnorm_bwd
|
||||
|
||||
return rmsnorm_bwd(rows, None, grad_normed, rstd)[0].view(q.shape)
|
||||
normed = rows.float() * rstd[:, None]
|
||||
grad_normed = grad_normed.float()
|
||||
grad_rows = (grad_normed - normed * (grad_normed * normed).mean(-1, keepdim=True)) * rstd[:, None]
|
||||
return grad_rows.to(q.dtype).view(q.shape)
|
||||
|
||||
|
||||
@_dsv4_q_norm_rope_backward.register_fake
|
||||
def _dsv4_q_norm_rope_backward_fake(
|
||||
grad: torch.Tensor, q: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, rstd: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
return q.new_empty(q.shape)
|
||||
|
||||
|
||||
def _dsv4_q_norm_rope_setup_context(ctx, inputs, output) -> None:
|
||||
q, cos_sin_cache, position_ids, _ = inputs
|
||||
ctx.save_for_backward(q, cos_sin_cache, position_ids, output[1])
|
||||
|
||||
|
||||
def _dsv4_q_norm_rope_autograd_backward(ctx, grad: torch.Tensor, grad_rstd: torch.Tensor):
|
||||
q, cos_sin_cache, position_ids, rstd = ctx.saved_tensors
|
||||
return _dsv4_q_norm_rope_backward(grad, q, cos_sin_cache, position_ids, rstd), None, None, None
|
||||
|
||||
|
||||
_dsv4_q_norm_rope.register_autograd(_dsv4_q_norm_rope_autograd_backward, setup_context=_dsv4_q_norm_rope_setup_context)
|
||||
|
||||
|
||||
def dsv4_q_norm_rope(
|
||||
q: torch.Tensor, cos_sin_cache: torch.Tensor, position_ids: torch.Tensor, eps: float
|
||||
) -> torch.Tensor:
|
||||
"""Unweighted RMSNorm over `head_dim`, then interleaved RoPE, both in fp32, rounded once to `q`'s dtype.
|
||||
|
||||
The norm and rotation form one op that autograd and Inductor cannot see into:
|
||||
|
||||
- Autograd: as separate nodes, backward would pass an fp32 gradient of the normalized query between
|
||||
them, twice the size of `q` (4 GiB per layer for 32k tokens of 64 heads of 512). Here the
|
||||
rotation's backward runs on the bf16 gradient and feeds the norm's backward directly.
|
||||
- Inductor: without quack, the norm falls back to torch ops, which Inductor would fuse and reorder,
|
||||
flipping a bf16 ULP on a few hundred outputs so compiled results drift from eager and from vLLM.
|
||||
|
||||
`q` is `(..., heads, head_dim)`; `cos_sin_cache` and `position_ids` are as in `dsv4_rope`.
|
||||
"""
|
||||
out, _ = _dsv4_q_norm_rope(q, cos_sin_cache, position_ids, eps)
|
||||
return out
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -105,8 +105,8 @@ class NemotronHMamba2(nn.Module):
|
||||
bias=config.use_conv_bias,
|
||||
)
|
||||
self.dt_bias = nn.Parameter(torch.empty(self.num_heads))
|
||||
self.A_log = nn.Parameter(torch.log(torch.arange(1, self.num_heads + 1, dtype=torch.float32)))
|
||||
self.D = nn.Parameter(torch.ones(self.num_heads, dtype=torch.float32))
|
||||
self.A_log = nn.Parameter(torch.arange(1, self.num_heads + 1, dtype=torch.get_default_dtype()).log())
|
||||
self.D = nn.Parameter(torch.ones(self.num_heads))
|
||||
self.norm = GatedRMSNorm(
|
||||
self.intermediate_size,
|
||||
group_size=self.intermediate_size // self.num_groups,
|
||||
@@ -142,7 +142,7 @@ class NemotronHMamba2(nn.Module):
|
||||
conv_weight = self.conv1d.weight
|
||||
conv_bias = self.conv1d.bias
|
||||
state_decay = -torch.exp(self.A_log.float())
|
||||
skip = self.D
|
||||
skip = self.D.float()
|
||||
dt_bias = self.dt_bias
|
||||
norm_weight = self.norm.weight
|
||||
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Literal, TypedDict, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from datasets import Dataset, interleave_datasets, load_dataset
|
||||
from huggingface_hub import snapshot_download
|
||||
from jaxtyping import Bool, Int
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
from renderers.base import MultiModalData, PlaceholderRange, Renderer, build_training_sample, create_renderer
|
||||
@@ -19,6 +22,7 @@ from prime_rl.configs.sft import DataConfig, LossMaskConfig, SFTDataConfig
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.chat_template import deserialize_tool_calls, normalize_messages
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import format_time
|
||||
|
||||
|
||||
class Sample(TypedDict):
|
||||
@@ -617,18 +621,41 @@ def cat_collate(samples: list[Sample]) -> Batch:
|
||||
}
|
||||
|
||||
|
||||
def pre_download_data(data: DataConfig, env_vars: dict[str, str]) -> None:
|
||||
if not isinstance(data, SFTDataConfig):
|
||||
return
|
||||
if Path(data.name).exists():
|
||||
get_logger().info(f"Data {data.name} found at local path, skipping download")
|
||||
return
|
||||
|
||||
dataset_name = data.name
|
||||
t0 = time.perf_counter()
|
||||
get_logger().info(f"Pre-downloading data {dataset_name} at revision {data.revision or 'main'}")
|
||||
snapshot = snapshot_download(
|
||||
repo_id=dataset_name,
|
||||
repo_type="dataset",
|
||||
revision=data.revision,
|
||||
cache_dir=env_vars.get("HF_HUB_CACHE"),
|
||||
)
|
||||
data.name = snapshot
|
||||
get_logger().debug(
|
||||
f"Finished pre-downloading data {dataset_name} to {snapshot} in {format_time(time.perf_counter() - t0)}"
|
||||
)
|
||||
|
||||
|
||||
def setup_and_interleave_datasets(
|
||||
dataset_name: str,
|
||||
subsets_and_splits: list[tuple[str | None, str]],
|
||||
probabilities: list[float] | None,
|
||||
stopping_strategy: Literal["first_exhausted", "all_exhausted"],
|
||||
seed: int = 0,
|
||||
revision: str | None = None,
|
||||
) -> Dataset:
|
||||
logger = get_logger()
|
||||
datasets = []
|
||||
for subset, split in subsets_and_splits:
|
||||
logger.debug(f"Loading dataset {dataset_name} with {subset=} and {split=}")
|
||||
dataset = cast(Dataset, load_dataset(dataset_name, subset, split=split))
|
||||
dataset = cast(Dataset, load_dataset(dataset_name, subset, split=split, revision=revision))
|
||||
num_examples = len(dataset)
|
||||
dataset = dataset.add_column("__subset", [subset] * num_examples, new_fingerprint=str(uuid.uuid4()))
|
||||
dataset = dataset.add_column("__split", [split] * num_examples, new_fingerprint=str(uuid.uuid4()))
|
||||
@@ -657,6 +684,7 @@ def load_sft_dataset(config: SFTDataConfig) -> Dataset:
|
||||
subsets_and_splits=[(None, "train")],
|
||||
probabilities=config.probabilities,
|
||||
stopping_strategy=config.stopping_strategy,
|
||||
revision=config.revision,
|
||||
)
|
||||
elif config.subsets is not None and config.splits is None:
|
||||
logger.debug(f"Loading datasets for subsets {config.subsets} with default split 'train'")
|
||||
@@ -665,6 +693,7 @@ def load_sft_dataset(config: SFTDataConfig) -> Dataset:
|
||||
subsets_and_splits=[(subset, "train") for subset in config.subsets],
|
||||
probabilities=config.probabilities,
|
||||
stopping_strategy=config.stopping_strategy,
|
||||
revision=config.revision,
|
||||
)
|
||||
elif config.subsets is None and config.splits is not None:
|
||||
logger.debug(f"Loading datasets for splits {config.splits} with default subset 'None'")
|
||||
@@ -673,6 +702,7 @@ def load_sft_dataset(config: SFTDataConfig) -> Dataset:
|
||||
subsets_and_splits=[(None, split) for split in config.splits],
|
||||
probabilities=config.probabilities,
|
||||
stopping_strategy=config.stopping_strategy,
|
||||
revision=config.revision,
|
||||
)
|
||||
else:
|
||||
assert config.subsets is not None and config.splits is not None
|
||||
@@ -682,6 +712,7 @@ def load_sft_dataset(config: SFTDataConfig) -> Dataset:
|
||||
subsets_and_splits=list(zip(config.subsets, config.splits)),
|
||||
probabilities=config.probabilities,
|
||||
stopping_strategy=config.stopping_strategy,
|
||||
revision=config.revision,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import copy
|
||||
|
||||
from vllm.tokenizers.deepseek_v4_encoding import encode_messages
|
||||
|
||||
from prime_rl.inference.patches import monkey_patch_deepseek_v4_request_tools_placement
|
||||
|
||||
|
||||
class _StubTokenizer:
|
||||
def get_added_vocab(self):
|
||||
return {}
|
||||
|
||||
def encode(self, text, **_kwargs):
|
||||
return text
|
||||
|
||||
|
||||
def _request_tools():
|
||||
return [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string"}},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def _tokenizer():
|
||||
from vllm.tokenizers import deepseek_v4
|
||||
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
return deepseek_v4.get_deepseek_v4_tokenizer(_StubTokenizer())
|
||||
|
||||
|
||||
def _render(messages, tools):
|
||||
return _tokenizer().apply_chat_template(
|
||||
messages,
|
||||
tools=tools,
|
||||
tokenize=False,
|
||||
thinking=True,
|
||||
reasoning_effort="low",
|
||||
)
|
||||
|
||||
|
||||
def _reference(messages):
|
||||
return encode_messages(messages, thinking_mode="thinking", reasoning_effort="low")
|
||||
|
||||
|
||||
def test_request_tools_attach_to_first_existing_system_without_mutation():
|
||||
messages = [
|
||||
{"role": "user", "content": "This may precede the system message."},
|
||||
{"role": "system", "content": "You are helpful.", "tools": []},
|
||||
{"role": "system", "content": "A later system message."},
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
]
|
||||
snapshot = copy.deepcopy(messages)
|
||||
tools = _request_tools()
|
||||
|
||||
prompt = _render(messages, tools)
|
||||
|
||||
expected_messages = messages.copy()
|
||||
expected_messages[1] = {**messages[1], "tools": tools}
|
||||
assert prompt == _reference(expected_messages)
|
||||
assert prompt.count("## Tools") == 1
|
||||
assert messages == snapshot
|
||||
|
||||
|
||||
def test_request_tools_synthesize_system_only_when_none_exists():
|
||||
messages = [{"role": "user", "content": "Weather in Paris?"}]
|
||||
tools = _request_tools()
|
||||
|
||||
prompt = _render(messages, tools)
|
||||
|
||||
assert prompt == _reference([{"role": "system", "tools": tools}, *messages])
|
||||
@@ -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
|
||||
|
||||
@@ -164,7 +164,7 @@ def prime_attention(layer_idx: int, dtype: torch.dtype = torch.bfloat16) -> nn.M
|
||||
bit-identical to one from a config carrying only the attention keys.
|
||||
"""
|
||||
with torch.device("cuda"), default_dtype(dtype):
|
||||
module = DeepseekV4Attention(MODEL_CONFIG, layer_idx=layer_idx)
|
||||
module = DeepseekV4Attention(MODEL_CONFIG, layer_idx, DeepseekV4RotaryEmbedding(MODEL_CONFIG))
|
||||
_randomize(module)
|
||||
eager_reference.use_eager_attention(module)
|
||||
return module
|
||||
@@ -189,15 +189,14 @@ def _packed_context(doc_lens: tuple[int, ...], dtype: torch.dtype) -> PackedCont
|
||||
"""The context `DeepseekV4Model` would hand its attention layers for a row of `doc_lens`.
|
||||
|
||||
A single-element `doc_lens` gives back the single-document context, which is what the unpacked
|
||||
half of a packing comparison runs at. `dtype` types the mask and the rotary tables, and has to
|
||||
be the one the caller runs at.
|
||||
half of a packing comparison runs at. `dtype` is the default dtype the rotary embedding is built
|
||||
under; the RoPE tables themselves are always fp32.
|
||||
"""
|
||||
with torch.device("cuda"), default_dtype(dtype):
|
||||
rotary = DeepseekV4RotaryEmbedding(MODEL_CONFIG)
|
||||
return PackedContext.build(
|
||||
rotary_emb=rotary,
|
||||
seq_lens=torch.tensor(doc_lens, device="cuda"),
|
||||
dtype=dtype,
|
||||
device=torch.device("cuda"),
|
||||
)
|
||||
|
||||
|
||||
@@ -11,10 +11,15 @@ from torch.utils._python_dispatch import TorchDispatchMode
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, eager_reference
|
||||
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
|
||||
from prime_rl.trainer.models.deepseek_v4.eager_reference import dense_mask_from_indices, eager_attention_with_sinks
|
||||
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
|
||||
from prime_rl.trainer.models.deepseek_v4.eager_reference import (
|
||||
apply_rotary_pos_emb_interleaved,
|
||||
dense_mask_from_indices,
|
||||
eager_attention_with_sinks,
|
||||
)
|
||||
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection, DeepseekV4UnweightedRMSNorm
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT, dsv4_mhc
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_rope import dsv4_q_norm_rope, dsv4_rope
|
||||
from prime_rl.utils.cp import CPContext
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
@@ -87,8 +92,8 @@ def _packed_context(
|
||||
"""The context `DeepseekV4Model` would hand its attention layers for a row of `doc_lens`.
|
||||
|
||||
A single-element `doc_lens` gives back the single-document context, which is what the unpacked
|
||||
half of a packing comparison runs at. `dtype` types the mask and the rotary tables, and has to
|
||||
be the one the caller runs at.
|
||||
half of a packing comparison runs at. `dtype` is the default dtype the rotary embedding is built
|
||||
under; the RoPE tables themselves are always fp32.
|
||||
|
||||
`doc_lens` always describes the whole row, `cp_world_size` shards included: the context
|
||||
parallel tests below hand it the same layout every rank sees and vary only `cp_rank`.
|
||||
@@ -98,7 +103,6 @@ def _packed_context(
|
||||
return PackedContext.build(
|
||||
rotary_emb=rotary,
|
||||
seq_lens=torch.tensor(doc_lens, device="cuda"),
|
||||
dtype=dtype,
|
||||
device=torch.device("cuda"),
|
||||
cp_rank=cp_rank,
|
||||
cp_world_size=cp_world_size,
|
||||
@@ -537,7 +541,7 @@ V4FLASH_DOC_IDS = ["two-docs", "no-entries", "one-short-doc", "three-docs", "sat
|
||||
def v4flash_attention(layer_idx: int, dtype: torch.dtype = torch.float32, eager: bool = False) -> nn.Module:
|
||||
"""One attention layer at the real DeepSeek V4 Flash shapes, 126M parameters of it."""
|
||||
with torch.device("cuda"), default_dtype(dtype):
|
||||
module = DeepseekV4Attention(V4FLASH_CONFIG, layer_idx=layer_idx)
|
||||
module = DeepseekV4Attention(V4FLASH_CONFIG, layer_idx, DeepseekV4RotaryEmbedding(V4FLASH_CONFIG))
|
||||
_randomize(module)
|
||||
if eager:
|
||||
eager_reference.use_eager_attention(module)
|
||||
@@ -642,7 +646,7 @@ def test_deepseek_v4_refuses_a_shape_the_kernel_cannot_tile():
|
||||
"""The constructor refuses a head count the kernels cannot tile, rather than the first forward."""
|
||||
config = DeepseekV4Config(**{**V4FLASH_MODEL, "num_attention_heads": 16})
|
||||
with pytest.raises(ValueError, match="cannot run the fused sparse-attention kernel"):
|
||||
DeepseekV4Attention(config, layer_idx=V4FLASH_CSA_LAYER)
|
||||
DeepseekV4Attention(config, V4FLASH_CSA_LAYER, DeepseekV4RotaryEmbedding(config))
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
@@ -1167,9 +1171,11 @@ def _cp_gathered_projections(
|
||||
"""
|
||||
# One context per rank, not one per gather: a rank's gathers all read the same tables.
|
||||
rope_tables = [
|
||||
_packed_context(doc_lens, dtype, config, cp_rank=cp_rank, cp_world_size=cp_world_size).position_embeddings[
|
||||
module.rope_layer_type
|
||||
]
|
||||
module.rotary_emb(
|
||||
_packed_context(doc_lens, dtype, config, cp_rank=cp_rank, cp_world_size=cp_world_size).position_ids,
|
||||
module.rope_layer_type,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
for cp_rank in range(cp_world_size)
|
||||
]
|
||||
|
||||
@@ -1246,6 +1252,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)
|
||||
@@ -1319,3 +1331,98 @@ def test_fused_post_bda_matches_the_eager_reference():
|
||||
for label, fused_leaf, reference_leaf in grads:
|
||||
assert reference_leaf.grad is not None, f"{label}: the reference backward left the leaf without a gradient"
|
||||
_assert_relative(fused_leaf.grad, reference_leaf.grad, POST_BDA_GRAD_RTOL, label)
|
||||
|
||||
|
||||
ROPE_DIM = V4FLASH_MODEL["qk_rope_head_dim"]
|
||||
|
||||
|
||||
def _rope_positions() -> torch.Tensor:
|
||||
"""Three packed documents, the last starting deep into a long rollout: positions reset and reach ~128k."""
|
||||
return torch.cat([torch.arange(700), torch.arange(1500), torch.arange(129000, 130896)]).cuda()
|
||||
|
||||
|
||||
def _rope_table(n_rows: int) -> torch.Tensor:
|
||||
"""A plain fp32 `[cos | sin]` table in vLLM's layout, one entry per interleaved pair."""
|
||||
inv_freq = 1.0 / (V4FLASH_MODEL["rope_theta"] ** (torch.arange(0, ROPE_DIM, 2, dtype=torch.float32) / ROPE_DIM))
|
||||
freqs = torch.outer(torch.arange(n_rows, dtype=torch.float32), inv_freq)
|
||||
return torch.cat([freqs.cos(), freqs.sin()], dim=-1).cuda()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("inverse", [False, True], ids=["forward", "inverse"])
|
||||
def test_dsv4_rope_matches_vllm_bit_for_bit(inverse):
|
||||
"""The kernel and vLLM's in-place `rotary_embedding` op agree on every bit, nope channels included.
|
||||
|
||||
Both read the same table, so this isolates the rotation: fp32 math on a bf16 input, one rounding
|
||||
on store, and the same multiply-add contraction.
|
||||
"""
|
||||
vllm_ops = pytest.importorskip("vllm._custom_ops")
|
||||
positions = _rope_positions()
|
||||
cos_sin = _rope_table(int(positions.max()) + 1)
|
||||
heads, head_dim = V4FLASH_MODEL["num_attention_heads"], V4FLASH_MODEL["head_dim"]
|
||||
x = torch.randn(positions.numel(), heads, head_dim, device="cuda", dtype=torch.bfloat16)
|
||||
|
||||
expected = x.clone()
|
||||
vllm_ops.rotary_embedding(
|
||||
positions, expected, None, head_dim, cos_sin, False, rope_dim_offset=head_dim - ROPE_DIM, inverse=inverse
|
||||
)
|
||||
actual = dsv4_rope(x.clone(), cos_sin, positions, inverse=inverse)
|
||||
|
||||
assert torch.equal(actual, expected)
|
||||
|
||||
|
||||
def test_q_norm_rope_matches_vllm_fused_prefill_kernel():
|
||||
"""q matches vLLM's fused prefill q norm + RoPE to the last ulp, and the kv rotation bit for bit.
|
||||
|
||||
vLLM rounds q to bf16 once after an fp32 RMSNorm and rotation, as `dsv4_q_norm_rope` does. The norm's
|
||||
reduction order differs, so a few elements per million land one ulp apart.
|
||||
"""
|
||||
pytest.importorskip("vllm._custom_ops")
|
||||
positions = _rope_positions()
|
||||
cos_sin = _rope_table(int(positions.max()) + 1)
|
||||
n_tokens, heads, head_dim = positions.numel(), V4FLASH_MODEL["num_attention_heads"], V4FLASH_MODEL["head_dim"]
|
||||
eps, block_size = V4FLASH_MODEL["rms_norm_eps"], 64
|
||||
q = torch.randn(n_tokens, heads, head_dim, device="cuda", dtype=torch.bfloat16)
|
||||
kv = torch.randn(n_tokens, head_dim, device="cuda", dtype=torch.bfloat16)
|
||||
kv_cache = torch.zeros(n_tokens // block_size, block_size, head_dim, device="cuda", dtype=torch.bfloat16)
|
||||
|
||||
expected_q = q.clone()
|
||||
torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_bf16_insert(
|
||||
expected_q, kv, kv_cache, torch.arange(n_tokens, device="cuda"), positions, cos_sin, eps, block_size
|
||||
)
|
||||
rotated_q = dsv4_q_norm_rope(q, cos_sin, positions, eps)
|
||||
|
||||
assert (rotated_q != expected_q).float().mean() < 1e-5
|
||||
_assert_relative(rotated_q, expected_q, torch.finfo(torch.bfloat16).eps, "q")
|
||||
rotated_kv = dsv4_rope(kv.clone().unsqueeze(1), cos_sin, positions)
|
||||
assert torch.equal(rotated_kv, kv_cache.view(n_tokens, 1, head_dim))
|
||||
|
||||
|
||||
def test_q_norm_rope_matches_the_composed_norm_and_rotation():
|
||||
"""Bit for bit with an fp32 RMSNorm, the rotation and one bf16 cast, eager and compiled.
|
||||
|
||||
Gradients agree with the composed ops to bf16 precision rather than bit for bit: the composed
|
||||
backward carries an fp32 gradient through the rotation, where `dsv4_q_norm_rope` keeps it in bf16.
|
||||
"""
|
||||
positions = _rope_positions()
|
||||
cos_sin = _rope_table(int(positions.max()) + 1)
|
||||
heads, head_dim = V4FLASH_MODEL["num_attention_heads"], V4FLASH_MODEL["head_dim"]
|
||||
eps = V4FLASH_MODEL["rms_norm_eps"]
|
||||
leaf = torch.randn(1, positions.numel(), heads, head_dim, device="cuda", dtype=torch.bfloat16)
|
||||
fused_leaf, compiled_leaf, composed_leaf = _leaves(leaf, leaf, leaf)
|
||||
weight = torch.randn_like(leaf, dtype=torch.float32)
|
||||
|
||||
def composed(q: torch.Tensor) -> torch.Tensor:
|
||||
normed = DeepseekV4UnweightedRMSNorm(eps=eps, out_dtype=torch.float32)(q)
|
||||
return dsv4_rope(normed, cos_sin, positions).to(q.dtype)
|
||||
|
||||
fused = dsv4_q_norm_rope(fused_leaf * 1, cos_sin, positions, eps)
|
||||
compiled = torch.compile(lambda q: dsv4_q_norm_rope(q * 1, cos_sin, positions, eps), fullgraph=True)(compiled_leaf)
|
||||
expected = composed(composed_leaf * 1)
|
||||
for out in (fused, compiled, expected):
|
||||
(out.float() * weight).sum().backward()
|
||||
|
||||
assert fused.dtype == torch.bfloat16
|
||||
assert torch.equal(fused, expected)
|
||||
assert torch.equal(compiled, fused)
|
||||
assert torch.equal(compiled_leaf.grad, fused_leaf.grad)
|
||||
_assert_relative(fused_leaf.grad, composed_leaf.grad, torch.finfo(torch.bfloat16).eps, "q gradient")
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -125,6 +125,17 @@ def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
|
||||
assert mamba_layer.mamba.cp_context.cp_world_size == 2
|
||||
|
||||
|
||||
def test_nemotron_h_mamba_parameters_follow_default_dtype():
|
||||
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
with torch.device("meta"), default_dtype(torch.bfloat16):
|
||||
model = NemotronHForCausalLM(config)
|
||||
|
||||
mamba = model.model.layers[0].mamba
|
||||
assert isinstance(mamba, NemotronHMamba2)
|
||||
assert mamba.A_log.dtype == torch.bfloat16
|
||||
assert mamba.D.dtype == torch.bfloat16
|
||||
|
||||
|
||||
def test_nemotron_h_no_latent_projection():
|
||||
"""Verify model works without latent projections (moe_latent_size=None)."""
|
||||
prime_config = NemotronHConfig(
|
||||
|
||||
@@ -49,19 +49,21 @@ members = [
|
||||
"bfcl-v3",
|
||||
"browsecomp",
|
||||
"browsecomp-plus",
|
||||
"cambench",
|
||||
"charxiv",
|
||||
"clbench",
|
||||
"color-codeword",
|
||||
"combibench",
|
||||
"deep-swe",
|
||||
"deepdive",
|
||||
"deepseek-prover",
|
||||
"deshuffle-papers",
|
||||
"discover-and-prove",
|
||||
"drug-discovery-bench",
|
||||
"enterprise-ops-gym",
|
||||
"formalmath",
|
||||
"forth-lang",
|
||||
"frontierscience",
|
||||
"general-agent",
|
||||
"goedel-pset",
|
||||
"gpqa",
|
||||
"graphwalks",
|
||||
"gsm8k",
|
||||
@@ -83,6 +85,7 @@ members = [
|
||||
"longpdfs",
|
||||
"math-env",
|
||||
"math500",
|
||||
"matholympiadbench",
|
||||
"mcp-atlas",
|
||||
"minif2f",
|
||||
"mmk12",
|
||||
@@ -102,12 +105,17 @@ members = [
|
||||
"openthoughts-tblite",
|
||||
"papersearchqa",
|
||||
"patterned-needle-in-haystack",
|
||||
"pi-deepswe",
|
||||
"pi-officeqa-pro-v2",
|
||||
"pi-terminal-bench-2",
|
||||
"pinchbench",
|
||||
"prime-rl",
|
||||
"programbench-env",
|
||||
"prolog",
|
||||
"proofnet",
|
||||
"proposer-solver",
|
||||
"proverbench",
|
||||
"putnambench",
|
||||
"r2e-gym",
|
||||
"redsearcher",
|
||||
"reverse-text",
|
||||
@@ -117,6 +125,9 @@ members = [
|
||||
"senior-swe-bench",
|
||||
"simpleqa",
|
||||
"simpleqa-verified",
|
||||
"swe-atlas-qna",
|
||||
"swe-atlas-rf",
|
||||
"swe-atlas-tw",
|
||||
"swebench-multilingual",
|
||||
"swebench-pro",
|
||||
"swebench-verified",
|
||||
@@ -774,6 +785,21 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/8c/7b/1fc1c09cc0756cf25861a3be10565915953876da48bb228fb9a672b20a42/cachetools-7.1.4-py3-none-any.whl", hash = "sha256:323dc4127934744db5b54eb4924482d7edafbf9554e820d1531c2e08c0e4ef54", size = 16761, upload-time = "2026-05-21T22:40:41.845Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cambench"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/cambench" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "catalogue"
|
||||
version = "2.0.10"
|
||||
@@ -1006,6 +1032,21 @@ requires-dist = [
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "combibench"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/combibench" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "comm"
|
||||
version = "0.2.3"
|
||||
@@ -1370,14 +1411,14 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "deep-swe"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/prime-envs/environments/swe/deep_swe" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1" }]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.2.dev137" }]
|
||||
|
||||
[[package]]
|
||||
name = "deepdiff"
|
||||
@@ -1403,17 +1444,6 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "deepseek-prover"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/prime-envs/environments/lean/deepseek_prover" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "deprecation"
|
||||
version = "2.1.0"
|
||||
@@ -1476,7 +1506,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "dion"
|
||||
version = "0.1.0"
|
||||
source = { git = "https://github.com/samsja/dion.git?rev=99e5f7e#99e5f7e5f0a7dbe418ce6dfc84196dba052e67c8" }
|
||||
source = { git = "https://github.com/samsja/dion.git?rev=6f9242d#6f9242dc3da131cd105afa83ee0141ed5298339d" }
|
||||
dependencies = [
|
||||
{ name = "numpy" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
@@ -1495,6 +1525,21 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5e/1f/c8bf92552b7f0a13b9f12b85e3de8df6d9814240e0f8ce8f37433df028b3/dirhash-0.5.0-py3-none-any.whl", hash = "sha256:523dfd6b058c64f45b31604376926c6e2bd2ea301d0df23095d4055674e38b09", size = 13119, upload-time = "2024-08-03T22:14:11.688Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "discover-and-prove"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/discover_and_prove" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "distlib"
|
||||
version = "0.4.0"
|
||||
@@ -1948,6 +1993,21 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/2c/47/c99d5268f354002ce80f8d029cd9d7d872969da1de8b93d32de4dc56d6f4/fonttools-4.63.0-py3-none-any.whl", hash = "sha256:445af2eab030a16b9171ea8bdda7ebf7d96bda2df88ee182a464252f6e05e20d", size = 1164562, upload-time = "2026-05-14T12:04:29.092Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "formalmath"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/formalmath" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "forth-lang"
|
||||
version = "0.2.1"
|
||||
@@ -2082,17 +2142,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/20/7a/1c6e3562dfd8950adbb11ffbc65d21e7c89d01a6e4f137fa981056de25c5/gitpython-3.1.50-py3-none-any.whl", hash = "sha256:d352abe2908d07355014abdd21ddf798c2a961469239afec4962e9da884858f9", size = 212507, upload-time = "2026-05-06T04:01:23.799Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "goedel-pset"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/prime-envs/environments/lean/goedel_pset" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "google-auth"
|
||||
version = "2.55.0"
|
||||
@@ -3003,14 +3052,20 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "kimina"
|
||||
version = "0.1.1"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/kimina" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "pyarrow" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "pyarrow", specifier = ">=15" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kiwisolver"
|
||||
@@ -3150,6 +3205,17 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/61/f75cd1fa54d8434276126034aed54dd120747de9a8fa013cdd79545ccbeb/latex2sympy2_extended-1.11.0-py3-none-any.whl", hash = "sha256:aebb77d52ce269e25028e4bea89ddb14d242ba36bcf7b636496fb5fd9728d234", size = 209050, upload-time = "2026-01-10T01:43:19.458Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lean-common"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/packages/lean_common" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.3.2.dev137" }]
|
||||
|
||||
[[package]]
|
||||
name = "litellm"
|
||||
version = "1.95.0"
|
||||
@@ -3404,6 +3470,21 @@ dependencies = [
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "matholympiadbench"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/matholympiadbench" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matplotlib"
|
||||
version = "3.10.9"
|
||||
@@ -3504,14 +3585,18 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "minif2f"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/minif2f" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mistral-common"
|
||||
@@ -4006,14 +4091,20 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "numina"
|
||||
version = "0.1.1"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/numina" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "pyarrow" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "pyarrow", specifier = ">=15" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "numpy"
|
||||
@@ -4331,7 +4422,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "officeqa-pro-v2"
|
||||
version = "0.1.0"
|
||||
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'" },
|
||||
@@ -4748,6 +4839,44 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pi-deepswe"
|
||||
version = "0.2.9"
|
||||
source = { editable = "deps/prime-envs/environments/swe/pi_deepswe" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.2.dev137" }]
|
||||
|
||||
[[package]]
|
||||
name = "pi-officeqa-pro-v2"
|
||||
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 = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "huggingface-hub", specifier = ">=0.34.0" },
|
||||
{ name = "verifiers", specifier = ">=0.3.1" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pi-terminal-bench-2"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/terminal/pi_terminal_bench_2" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "pillow"
|
||||
version = "12.2.0"
|
||||
@@ -5097,7 +5226,7 @@ requires-dist = [
|
||||
{ name = "deep-gemm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl" },
|
||||
{ name = "deep-gemm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'disagg'" },
|
||||
{ name = "deep-gemm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "dion", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/samsja/dion.git?rev=99e5f7e" },
|
||||
{ name = "dion", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/samsja/dion.git?rev=6f9242d" },
|
||||
{ name = "fastapi", marker = "extra == 'dashboard'", specifier = ">=0.115" },
|
||||
{ name = "flash-attn", marker = "platform_machine == 'aarch64' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.48/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_aarch64.whl" },
|
||||
{ name = "flash-attn", marker = "platform_machine == 'x86_64' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_x86_64.whl" },
|
||||
@@ -5350,6 +5479,21 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/84/03/0d3ce49e2505ae70cf43bc5bb3033955d2fc9f932163e84dc0779cc47f48/prompt_toolkit-3.0.52-py3-none-any.whl", hash = "sha256:9aac639a3bbd33284347de5ad8d68ecc044b91a762dc39b7c21095fcd6a19955", size = 391431, upload-time = "2025-08-27T15:23:59.498Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proofnet"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/proofnet" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "propcache"
|
||||
version = "0.5.2"
|
||||
@@ -5420,14 +5564,18 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "proverbench"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/proverbench" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "psutil"
|
||||
@@ -5460,6 +5608,21 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/8e/37/efad0257dc6e593a18957422533ff0f87ede7c9c6ea010a2177d738fb82f/pure_eval-0.2.3-py3-none-any.whl", hash = "sha256:1db8e35b67b3d218d818ae653e27f06c3aa420901fa7b081ca98cbedc874e0d0", size = 11842, upload-time = "2024-07-21T12:58:20.04Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "putnambench"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/lean/putnambench" }
|
||||
dependencies = [
|
||||
{ name = "lean-common" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "lean-common", editable = "deps/prime-envs/packages/lean_common" },
|
||||
{ name = "verifiers", specifier = ">=0.3.2.dev137" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "py-cpuinfo"
|
||||
version = "9.0.0"
|
||||
@@ -6701,6 +6864,39 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0e/65/5e726c372da8a5e35022a94388b12252710aad0c2351699c3d76ae8dba78/supervisor-4.3.0-py2.py3-none-any.whl", hash = "sha256:0bcb763fddafba410f35cbde226aa7f8514b9fb82eb05a0c85f6588d1c13f8db", size = 320736, upload-time = "2025-08-23T18:25:00.767Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "swe-atlas-qna"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/swe/swe_atlas_qna" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "swe-atlas-rf"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/swe/swe_atlas_rf" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "swe-atlas-tw"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/prime-envs/environments/swe/swe_atlas_tw" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "swe-rex"
|
||||
version = "1.4.0"
|
||||
@@ -6758,14 +6954,14 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1
|
||||
|
||||
[[package]]
|
||||
name = "swebench-pro"
|
||||
version = "0.1.0"
|
||||
version = "0.2.1"
|
||||
source = { editable = "deps/prime-envs/environments/swe/swebench_pro" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1" }]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.2.dev137" }]
|
||||
|
||||
[[package]]
|
||||
name = "swebench-verified"
|
||||
@@ -7740,7 +7936,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 +7964,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 = [
|
||||
|
||||
Reference in New Issue
Block a user