Compare commits

..
137 changed files with 3646 additions and 3639 deletions
+9 -4
View File
@@ -1,6 +1,8 @@
name: Build Image (ghcr)
on:
release:
types: [published]
workflow_dispatch:
inputs:
ref:
@@ -25,12 +27,12 @@ on:
env:
REGISTRY: ghcr.io
IMAGE_NAME: primeintellect-ai/prime-rl
BUILD_REF: ${{ inputs.ref || github.ref_name }}
BUILD_TAG: ${{ inputs.tag || '' }}
BUILD_REF: ${{ github.event.release.tag_name || inputs.ref || github.ref_name }}
BUILD_TAG: ${{ github.event.release.tag_name || inputs.tag || '' }}
BUILD_PLATFORMS: ${{ inputs.platforms || 'both' }}
concurrency:
group: build-image-${{ inputs.tag || inputs.ref || github.ref_name }}
group: build-image-${{ github.event.release.tag_name || inputs.tag || inputs.ref || github.ref_name }}
cancel-in-progress: false
jobs:
@@ -155,7 +157,10 @@ jobs:
uses: docker/build-push-action@v7
with:
context: .
file: ./Dockerfile.cuda
# This experiment tag derives from the immutable current-main arm64
# image and only bakes the pinned NVFP4 runtime. Main still uses
# Dockerfile.cuda; this workflow change exists solely on the tag.
file: ./Dockerfile.nvfp4-e2e-overlay
push: true
platforms: ${{ matrix.platform }}
tags: |
-8
View File
@@ -121,11 +121,3 @@ jobs:
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest -vvs ${{ matrix.pytest_args }}
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.test }}-logs
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
-197
View File
@@ -1,197 +0,0 @@
name: Nightly FFT
on:
# Allow to manually trigger the workflow
workflow_dispatch:
inputs:
config_file:
description: "Full-FT config to dispatch (e.g. configs/ci/nightly-fft/wordle.toml). Leave empty to run all."
required: false
default: ""
image_tag:
description: "prime-rl image tag to pin (e.g. v0.7.1.dev58). Leave empty to auto-resolve the newest v*.dev* with a published manifest."
required: false
default: ""
# Scheduled run at 3AM PST (11AM UTC)
schedule:
- cron: "0 11 * * *"
permissions:
contents: read
packages: read
jobs:
discover-configs:
name: Discover configs
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.build-matrix.outputs.matrix }}
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
submodules: false
- name: Build matrix from nightly FFT configs
id: build-matrix
run: |
# Find all nightly full-finetune configs
files=$(ls configs/ci/nightly-fft/*.toml)
# Filter to specific config if provided in workflow_dispatch
if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ github.event.inputs.config_file }}" ]; then
filtered=$(echo "$files" | grep -F "${{ github.event.inputs.config_file }}" || true)
if [ -z "$filtered" ]; then
echo "Error: Config file '${{ github.event.inputs.config_file }}' not found"
exit 1
fi
files="$filtered"
fi
echo "Discovered nightly FFT configs:"
echo "$files"
# Build JSON of the form: { "config_file": ["configs/ci/nightly-fft/foo.toml", ...] }
json=$(printf '%s\n' "$files" | jq -R . | jq -sc '{config_file: .}')
echo "matrix=$json" >> "$GITHUB_OUTPUT"
dispatch-run:
name: Dispatch hosted FFT run
needs: discover-configs
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.discover-configs.outputs.matrix) }}
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
submodules: false
- name: Resolve prime-rl image tag
id: image
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Pass the dispatch input through env so a malicious value
# cannot break out of shell context via $(...) or embedded
# quotes — the GitHub expression is substituted before Bash
# parses the script.
REQUESTED_IMAGE_TAG: ${{ github.event.inputs.image_tag }}
run: |
# If workflow_dispatch passed an explicit image_tag, validate
# it as a Docker/OCI tag, verify its manifest is pullable,
# and use it as-is (skip resolution).
requested="$REQUESTED_IMAGE_TAG"
if [ -n "$requested" ]; then
# OCI/Docker tag charset: [A-Za-z0-9._-], max 128, no
# leading '.' or '-'. Reject anything else before it
# reaches curl or GITHUB_OUTPUT.
if ! printf '%s' "$requested" | grep -Eq '^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$'; then
echo "Invalid image_tag: only [A-Za-z0-9._-] allowed, max 128 chars, no leading '.' or '-'." >&2
exit 1
fi
registry_token=$(curl -fsSL \
"https://ghcr.io/token?scope=repository:primeintellect-ai/prime-rl:pull" \
| jq -r .token)
code=$(curl -sS -o /dev/null -w '%{http_code}' \
-H "Authorization: Bearer $registry_token" \
-H 'Accept: application/vnd.oci.image.index.v1+json' \
-H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' \
"https://ghcr.io/v2/primeintellect-ai/prime-rl/manifests/$requested")
if [ "$code" != "200" ]; then
echo "Requested image_tag '$requested' has no published manifest (HTTP $code)." >&2
exit 1
fi
echo "Using pinned prime-rl image tag: $requested"
echo "tag=$requested" >> "$GITHUB_OUTPUT"
exit 0
fi
# No dispatch input: auto-resolve the newest v*.dev* tag on
# GHCR (the point of a nightly is to catch regressions on
# tip-of-main). The GHCR versions API can list a tag before
# its manifest is actually pullable (build in-flight, or
# manifest step didn't finish), so pull the top N candidates
# and verify each with a manifest HEAD via the anonymous
# registry token flow; take the newest one that resolves.
# Disable pipefail locally: `grep` may exit 1 on no matches
# (empty tag list) and `head` may SIGPIPE `sort` after
# reading its 10 lines. Both would abort the step before the
# explicit no-candidates guard below runs.
set +o pipefail
candidates=$(gh api --paginate \
"/orgs/primeintellect-ai/packages/container/prime-rl/versions" \
--jq '.[].metadata.container.tags[]' \
| grep -E '^v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+$' \
| sort -Vru | head -n 10)
set -o pipefail
if [ -z "$candidates" ]; then
echo "No v*.dev* tag listed on GHCR." >&2
exit 1
fi
registry_token=$(curl -fsSL \
"https://ghcr.io/token?scope=repository:primeintellect-ai/prime-rl:pull" \
| jq -r .token)
tag=""
for cand in $candidates; do
code=$(curl -sS -o /dev/null -w '%{http_code}' \
-H "Authorization: Bearer $registry_token" \
-H 'Accept: application/vnd.oci.image.index.v1+json' \
-H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' \
"https://ghcr.io/v2/primeintellect-ai/prime-rl/manifests/$cand")
if [ "$code" = "200" ]; then
tag="$cand"
break
fi
echo "Skip $cand — manifest HEAD returned $code"
done
if [ -z "$tag" ]; then
echo "None of the top v*.dev* tags have a published manifest." >&2
exit 1
fi
echo "Latest published prime-rl image tag on GHCR: $tag"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install prime CLI (latest)
run: uv tool install prime
- name: Dispatch run
env:
PRIME_API_KEY: ${{ secrets.PRIME_FFT_API_KEY }}
PRIME_TEAM_ID: ${{ secrets.PRIME_FFT_TEAM_ID }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
HF_TOKEN: ${{ secrets.HF_TOKEN }}
run: |
echo "Dispatching config: ${{ matrix.config_file }}"
echo "Image tag: ${{ steps.image.outputs.tag }}"
# Tag the RFTRun so it's identifiable on the platform as
# coming from this workflow. Injected here rather than in
# the checked-in toml because a top-level `name` field
# breaks tests/unit/test_configs.py::test_load_configs
# (RLConfig has no top-level name).
config_base=$(basename "${{ matrix.config_file }}" .toml)
run_name="nightly-${config_base}-$(date -u +%Y-%m-%d)-${{ github.run_id }}"
dispatch_cfg=$(mktemp --suffix=.toml)
printf 'name = "%s"\n\n' "$run_name" > "$dispatch_cfg"
cat "${{ matrix.config_file }}" >> "$dispatch_cfg"
echo "Dispatched run name: $run_name"
# Forward WANDB_API_KEY / HF_TOKEN into the hosted payload:
# the full-FT dispatch path (`prime train`) only picks up
# secrets that were explicitly collected via `-e` / `--env-file`,
# not ambient env, so the workflow env: block alone is not
# enough to reach the hosted trainer/orchestrator pods.
prime train "$dispatch_cfg" \
--image-tag "${{ steps.image.outputs.tag }}" \
-e WANDB_API_KEY \
-e HF_TOKEN \
--yes --output json
+5 -3
View File
@@ -1,9 +1,11 @@
name: Sync Docs to Public Docs
on:
release:
types:
- published
push:
branches:
- main
paths:
- 'docs/**'
workflow_dispatch:
jobs:
-25
View File
@@ -119,8 +119,6 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Publish draft release
env:
@@ -129,22 +127,11 @@ jobs:
run: |
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
# Publishing runs as GITHUB_TOKEN, whose events don't retrigger
# workflows, so dispatch the image build explicitly.
- name: Trigger image build for the release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.auto-tag-on-main.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
tag-and-release:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
@@ -208,7 +195,6 @@ jobs:
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Publish draft release
id: publish
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
@@ -221,17 +207,6 @@ jobs:
fi
if [ "$STATE" = "false" ]; then
echo "Release $TAG is already published; nothing to do."
echo "published=false" >> "$GITHUB_OUTPUT"
exit 0
fi
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
echo "published=true" >> "$GITHUB_OUTPUT"
# Skipped when the release was already published (no rebuild needed).
- name: Trigger image build for the release
if: steps.publish.outputs.published == 'true'
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
+4 -1
View File
@@ -88,6 +88,7 @@ COPY examples /app/examples
COPY k8s /app/k8s
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
COPY scripts/patch-vllm-nvfp4-writable-scales.py /app/scripts/patch-vllm-nvfp4-writable-scales.py
# Use submodule git metadata from the build context when present. Docker copies
# only the submodule .git pointer files into /app/deps, so we temporarily link
@@ -108,7 +109,9 @@ RUN --mount=type=cache,target=/app/.cache/uv \
&& \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]' \
&& \
/app/.venv/bin/python /app/scripts/patch-vllm-nvfp4-writable-scales.py
# 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
+21
View File
@@ -0,0 +1,21 @@
ARG BASE_IMAGE=ghcr.io/primeintellect-ai/prime-rl@sha256:a86004b9b44d43c8018633283ec0267c3339c0dac0e35a9957f48f0a6b56153c
FROM ${BASE_IMAGE}
USER root
COPY pyproject.toml /app/pyproject.toml
COPY uv.lock /app/uv.lock
COPY scripts/patch-vllm-nvfp4-writable-scales.py /app/scripts/patch-vllm-nvfp4-writable-scales.py
COPY k8s/experiments/run_nvfp4_inference.sh /app/k8s/experiments/run_nvfp4_inference.sh
RUN uv --no-config pip install \
--python /app/.venv/bin/python \
--upgrade \
--no-deps \
'https://wheels.vllm.ai/910cc8543a6907c9cc87c417f8f2420969278bf5/vllm-0.23.1rc1.dev1392%2Bg910cc8543-cp38-abi3-manylinux_2_28_aarch64.whl' \
'https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_python-0.6.15.post1-py3-none-any.whl' \
'https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_cubin-0.6.15.post1-py3-none-any.whl' \
&& /app/.venv/bin/python /app/scripts/patch-vllm-nvfp4-writable-scales.py \
&& /app/.venv/bin/python -c 'from importlib.metadata import version; expected={"vllm":"0.23.1rc1.dev1392+g910cc8543","flashinfer-python":"0.6.15.post1","flashinfer-cubin":"0.6.15.post1"}; actual={name:version(name) for name in expected}; assert actual == expected, (actual, expected)'
USER appuser
+13
View File
@@ -0,0 +1,13 @@
ARG BASE_IMAGE=ghcr.io/primeintellect-ai/prime-rl@sha256:4a2713ef9f6df8f002a8e63398f408127c05588e611e655d792252ecfd627ace
FROM ${BASE_IMAGE}
USER root
# Keep Prime main, the pinned NVFP4 runtime, and the cache/package-move fixes
# from the immutable dev3 image. This layer only tracks vLLM's OnlineRenderer
# member rename; it does not install or compile anything.
COPY --chown=appuser:appuser \
src/prime_rl/inference/vllm/serving_tokens.py \
/app/src/prime_rl/inference/vllm/serving_tokens.py
USER appuser
@@ -0,0 +1,7 @@
**
!Dockerfile.nvfp4-e2e-overlay
!src/
!src/prime_rl/
!src/prime_rl/inference/
!src/prime_rl/inference/vllm/
!src/prime_rl/inference/vllm/serving_tokens.py
@@ -0,0 +1,507 @@
#!/usr/bin/env python3
"""Exercise Prime's layerwise reload path with vLLM online NVFP4 weights."""
from __future__ import annotations
import argparse
import hashlib
import importlib.metadata
import json
import math
import os
import time
from functools import partial
from pathlib import Path
from typing import Any, Iterable
DEFAULT_MODEL = "Qwen/Qwen3-30B-A3B-Instruct-2507"
EXPERT_WEIGHT_SUFFIXES = (
".gate_proj.weight",
".up_proj.weight",
".down_proj.weight",
)
KERNEL_WEIGHT_NAMES = {"w13_weight", "w2_weight"}
KERNEL_DERIVED_NAMES = {
"g1_scale_c",
"gemm1_alpha",
"gemm1_beta",
"gemm1_clamp_limit",
}
def _package_version(name: str) -> str:
try:
return importlib.metadata.version(name)
except importlib.metadata.PackageNotFoundError:
return "not-installed"
def environment_probe() -> dict[str, Any]:
import torch
import vllm
from vllm._custom_ops import scaled_fp4_quant
from vllm.model_executor.layers.quantization.online.nvfp4 import (
Nvfp4OnlineMoEMethod,
)
from vllm.utils.flashinfer import has_flashinfer_trtllm_fused_moe
from prime_rl.inference.vllm.worker.weight_transfer import (
load_weights_checkpoint_layerwise,
)
if not torch.cuda.is_available():
raise RuntimeError("CUDA is unavailable")
capability = torch.cuda.get_device_capability()
if capability[0] != 10:
raise RuntimeError(f"online NVFP4 requires SM100, found SM{capability[0]}{capability[1]}")
if not has_flashinfer_trtllm_fused_moe():
raise RuntimeError("FlashInfer TRTLLM fused MoE is unavailable")
source = torch.arange(256, device="cuda", dtype=torch.bfloat16).reshape(16, 16)
scale = torch.ones((), device="cuda", dtype=torch.float32)
packed, block_scales = scaled_fp4_quant(
source,
scale,
is_sf_swizzled_layout=False,
)
torch.cuda.synchronize()
return {
"torch": _package_version("torch"),
"torch_cuda": torch.version.cuda,
"vllm": _package_version("vllm"),
"vllm_module": str(Path(vllm.__file__).resolve()),
"flashinfer_python": _package_version("flashinfer-python"),
"flashinfer_cubin": _package_version("flashinfer-cubin"),
"gpu": torch.cuda.get_device_name(),
"compute_capability": list(capability),
"nvfp4_method": f"{Nvfp4OnlineMoEMethod.__module__}.{Nvfp4OnlineMoEMethod.__name__}",
"prime_reload_helper": (
f"{load_weights_checkpoint_layerwise.__module__}.{load_weights_checkpoint_layerwise.__name__}"
),
"scaled_fp4_quant": {
"packed_shape": list(packed.shape),
"packed_dtype": str(packed.dtype),
"block_scale_shape": list(block_scales.shape),
"block_scale_dtype": str(block_scales.dtype),
},
"persistent_cache": {
"hit": os.environ.get("NVFP4_CACHE_HIT") == "1",
"key": os.environ.get("NVFP4_CACHE_KEY"),
"marker": os.environ.get("NVFP4_CACHE_READY_MARKER"),
},
}
def _mark_persistent_cache_ready() -> None:
"""Mark the versioned JIT cache reusable after engine warmup succeeds."""
marker_value = os.environ.get("NVFP4_CACHE_READY_MARKER")
cache_key = os.environ.get("NVFP4_CACHE_KEY")
if not marker_value or not cache_key:
return
marker = Path(marker_value)
marker.parent.mkdir(parents=True, exist_ok=True)
temporary = marker.with_name(f".{marker.name}.{os.getpid()}.tmp")
temporary.write_text(cache_key + "\n")
os.replace(temporary, marker)
def _get_worker_model(worker: Any):
model_runner = worker.model_runner
get_model = getattr(model_runner, "get_model", None)
model = get_model() if callable(get_model) else model_runner.model
return getattr(model, "runnable", model)
def _is_expert_weight(name: str, layer_index: int) -> bool:
marker = f"model.layers.{layer_index}.mlp.experts."
return name.startswith(marker) and name.endswith(EXPERT_WEIGHT_SUFFIXES)
def _reload_checkpoint(
worker: Any,
*,
model_path: str,
mutation_layer: int | None,
) -> dict[str, Any]:
"""Worker-side reload through Prime's production checkpoint-format helper."""
import torch
from torch.nn import Module
from vllm.model_executor.model_loader import DefaultModelLoader, get_model_loader
from prime_rl.inference.vllm.worker.weight_transfer import (
load_weights_checkpoint_layerwise,
)
model = _get_worker_model(worker)
if not isinstance(model, Module):
raise TypeError(f"expected torch Module, got {type(model)!r}")
model_loader = get_model_loader(worker.load_config)
if not isinstance(model_loader, DefaultModelLoader):
raise TypeError(f"expected DefaultModelLoader, got {type(model_loader)!r}")
source = DefaultModelLoader.Source(
model_path,
revision=None,
prefix="",
fall_back_to_pt=getattr(model, "fall_back_to_pt_during_load", True),
allow_patterns_overrides=getattr(model, "allow_patterns_overrides", None),
)
source_iterator = model_loader._get_weights_iterator(source)
stats: dict[str, Any] = {
"mutated_tensors": 0,
"mutated_numel": 0,
"mutated_names": [],
}
def transformed_weights() -> Iterable[tuple[str, torch.Tensor]]:
for name, tensor in source_iterator:
if mutation_layer is not None and _is_expert_weight(name, mutation_layer):
stats["mutated_tensors"] += 1
stats["mutated_numel"] += tensor.numel()
if len(stats["mutated_names"]) < 12:
stats["mutated_names"].append(name)
# Negation changes every non-zero packed FP4 value without
# creating the degenerate all-zero activation path. That
# keeps this test focused on reload/restore correctness.
yield name, tensor.neg()
else:
yield name, tensor
started = time.perf_counter()
load_weights_checkpoint_layerwise(
model,
transformed_weights(),
worker.model_runner.model_config,
worker.vllm_config,
)
torch.cuda.synchronize()
stats["elapsed_seconds"] = time.perf_counter() - started
if mutation_layer is not None:
num_experts = int(worker.model_runner.model_config.hf_text_config.num_experts)
expected_tensors = num_experts * len(EXPERT_WEIGHT_SUFFIXES)
if stats["mutated_tensors"] != expected_tensors:
raise RuntimeError(f"mutated {stats['mutated_tensors']} expert tensors, expected {expected_tensors}")
return stats
def _sample_tensor(tensor: Any, sample_size: int = 8192) -> dict[str, Any]:
import torch
value = tensor.detach()
if not value.is_contiguous():
value = value.contiguous()
raw = value.view(torch.uint8).reshape(-1)
count = min(sample_size, raw.numel())
if count:
indices = torch.linspace(
0,
raw.numel() - 1,
steps=count,
device=raw.device,
dtype=torch.float64,
).to(torch.long)
sample = raw[indices].to(device="cpu", dtype=torch.uint8)
payload = bytes(sample.tolist())
else:
payload = b""
return {
"shape": list(tensor.shape),
"dtype": str(tensor.dtype),
"device": str(tensor.device),
"nbytes": tensor.numel() * tensor.element_size(),
"data_ptr": tensor.data_ptr(),
"sample_bytes": len(payload),
"sample_nonzero": sum(byte != 0 for byte in payload),
"sample_sha256": hashlib.sha256(payload).hexdigest(),
"sample_prefix": list(payload[:16]),
}
def _probe_model(model: Any, *, layer_index: int) -> dict[str, Any]:
import torch
model = getattr(model, "runnable", model)
marker = f"model.layers.{layer_index}.mlp.experts"
tensors: dict[str, Any] = {}
for name, tensor in model.named_parameters():
leaf = name.rsplit(".", 1)[-1]
if marker in name and (
leaf.startswith(("w13_", "w2_")) or leaf in KERNEL_DERIVED_NAMES
):
tensors[name] = tensor
for name, tensor in model.named_buffers():
leaf = name.rsplit(".", 1)[-1]
if marker in name and (
leaf.startswith(("w13_", "w2_")) or leaf in KERNEL_DERIVED_NAMES
):
tensors.setdefault(name, tensor)
if not tensors:
nearby = [name for name, _ in model.named_parameters() if marker in name]
raise RuntimeError(f"found no NVFP4 kernel tensors under {marker}; nearby={nearby[:20]}")
quant_methods: dict[str, str] = {}
kernel_references: dict[str, Any] = {}
for name, module in model.named_modules():
if marker not in name:
continue
method = getattr(module, "_quant_method", None)
if method is None:
method = getattr(module, "quant_method", None)
if method is not None:
quant_methods[name] = f"{type(method).__module__}.{type(method).__name__}"
quant_config = getattr(method, "moe_quant_config", None)
for attr in (
"g1_alphas",
"g2_alphas",
"a1_gscale",
"a2_gscale",
"w1_scale",
"w2_scale",
):
value = getattr(quant_config, attr, None)
if isinstance(value, torch.Tensor):
kernel_references[f"{name}.moe_quant_config.{attr}"] = _sample_tensor(value)
moe_kernel = getattr(method, "moe_kernel", None)
fused_experts = getattr(moe_kernel, "fused_experts", None)
for attr in KERNEL_DERIVED_NAMES:
value = getattr(fused_experts, attr, None)
if isinstance(value, torch.Tensor):
kernel_references[f"{name}.moe_kernel.fused_experts.{attr}"] = _sample_tensor(value)
if not any(value.endswith(".Nvfp4OnlineMoEMethod") for value in quant_methods.values()):
raise RuntimeError(f"layer {layer_index} is not using Nvfp4OnlineMoEMethod: {quant_methods}")
return {
"quant_methods": quant_methods,
"tensors": {name: _sample_tensor(tensor) for name, tensor in sorted(tensors.items())},
"kernel_references": dict(sorted(kernel_references.items())),
"cuda_memory": {
"allocated": torch.cuda.memory_allocated(),
"reserved": torch.cuda.memory_reserved(),
"max_allocated": torch.cuda.max_memory_allocated(),
"max_reserved": torch.cuda.max_memory_reserved(),
},
}
def _generation_signature(llm: Any, prompt: str) -> dict[str, Any]:
from vllm import SamplingParams
params = SamplingParams(
temperature=0.0,
max_tokens=4,
logprobs=5,
seed=0,
)
request = llm.generate([prompt], params, use_tqdm=False)[0]
sequence = request.outputs[0]
chosen_logprobs: list[float | None] = []
for token_id, candidates in zip(sequence.token_ids, sequence.logprobs or []):
candidate = candidates.get(token_id)
chosen_logprobs.append(None if candidate is None else float(candidate.logprob))
return {
"token_ids": list(sequence.token_ids),
"text": sequence.text,
"cumulative_logprob": (None if sequence.cumulative_logprob is None else float(sequence.cumulative_logprob)),
"chosen_logprobs": chosen_logprobs,
}
def _kernel_leaf(name: str) -> str:
return name.rsplit(".", 1)[-1]
def _compare_phases(
baseline: dict[str, Any],
mutated: dict[str, Any],
restored: dict[str, Any],
baseline_generation: dict[str, Any],
mutated_generation: dict[str, Any],
restored_generation: dict[str, Any],
) -> dict[str, Any]:
baseline_tensors = baseline["tensors"]
mutated_tensors = mutated["tensors"]
restored_tensors = restored["tensors"]
if baseline_tensors.keys() != mutated_tensors.keys() or baseline_tensors.keys() != restored_tensors.keys():
raise RuntimeError("kernel tensor names changed across reload phases")
pointer_mismatches = [
name
for name in baseline_tensors
if not (
baseline_tensors[name]["data_ptr"]
== mutated_tensors[name]["data_ptr"]
== restored_tensors[name]["data_ptr"]
)
]
restore_hash_mismatches = [
name
for name in baseline_tensors
if baseline_tensors[name]["sample_sha256"] != restored_tensors[name]["sample_sha256"]
]
changed_kernel_weights = [
name
for name in baseline_tensors
if _kernel_leaf(name) in KERNEL_WEIGHT_NAMES
and baseline_tensors[name]["sample_sha256"] != mutated_tensors[name]["sample_sha256"]
]
kernel_weights = [name for name in baseline_tensors if _kernel_leaf(name) in KERNEL_WEIGHT_NAMES]
baseline_logprob = baseline_generation["cumulative_logprob"]
mutated_logprob = mutated_generation["cumulative_logprob"]
restored_logprob = restored_generation["cumulative_logprob"]
mutation_changed_output = baseline_generation["token_ids"] != mutated_generation["token_ids"] or (
baseline_logprob is not None
and mutated_logprob is not None
and not math.isclose(baseline_logprob, mutated_logprob, abs_tol=1e-5)
)
restored_output_matches = baseline_generation["token_ids"] == restored_generation["token_ids"]
if baseline_logprob is not None and restored_logprob is not None:
restored_output_matches = restored_output_matches and math.isclose(
baseline_logprob,
restored_logprob,
abs_tol=1e-5,
)
checks = {
"kernel_tensor_names_stable": True,
"kernel_storage_pointers_preserved": not pointer_mismatches,
"mutated_kernel_weights_changed": bool(kernel_weights) and len(changed_kernel_weights) == len(kernel_weights),
"restored_kernel_fingerprints_match": not restore_hash_mismatches,
"mutation_changed_generation": mutation_changed_output,
"restored_generation_matches": restored_output_matches,
}
return {
"passed": all(checks.values()),
"checks": checks,
"pointer_mismatches": pointer_mismatches,
"restore_hash_mismatches": restore_hash_mismatches,
"changed_kernel_weights": changed_kernel_weights,
}
def run_experiment(args: argparse.Namespace) -> dict[str, Any]:
from vllm import LLM
probe = environment_probe()
started = time.perf_counter()
llm = LLM(
model=args.model,
quantization="nvfp4_per_token",
dtype="bfloat16",
tensor_parallel_size=1,
enforce_eager=args.enforce_eager,
enable_prefix_caching=False,
max_model_len=args.max_model_len,
max_num_seqs=1,
gpu_memory_utilization=args.gpu_memory_utilization,
trust_remote_code=False,
disable_log_stats=True,
)
load_seconds = time.perf_counter() - started
_mark_persistent_cache_ready()
try:
baseline = llm.apply_model(partial(_probe_model, layer_index=args.layer))[0]
baseline_generation = _generation_signature(llm, args.prompt)
mutated_reload = llm.collective_rpc(
_reload_checkpoint,
timeout=args.reload_timeout,
kwargs={"model_path": args.model, "mutation_layer": args.layer},
)[0]
mutated = llm.apply_model(partial(_probe_model, layer_index=args.layer))[0]
mutated_generation = _generation_signature(llm, args.prompt)
restored_reload = llm.collective_rpc(
_reload_checkpoint,
timeout=args.reload_timeout,
kwargs={"model_path": args.model, "mutation_layer": None},
)[0]
restored = llm.apply_model(partial(_probe_model, layer_index=args.layer))[0]
restored_generation = _generation_signature(llm, args.prompt)
comparison = _compare_phases(
baseline,
mutated,
restored,
baseline_generation,
mutated_generation,
restored_generation,
)
return {
"status": "passed" if comparison["passed"] else "failed",
"environment": probe,
"configuration": {
"model": args.model,
"layer": args.layer,
"quantization": "nvfp4_per_token",
"enforce_eager": args.enforce_eager,
"max_model_len": args.max_model_len,
"gpu_memory_utilization": args.gpu_memory_utilization,
},
"initial_load_seconds": load_seconds,
"reloads": {
"mutated": mutated_reload,
"restored": restored_reload,
},
"generations": {
"baseline": baseline_generation,
"mutated": mutated_generation,
"restored": restored_generation,
},
"kernel_probes": {
"baseline": baseline,
"mutated": mutated,
"restored": restored,
},
"comparison": comparison,
}
finally:
shutdown = getattr(llm, "shutdown", None)
if callable(shutdown):
shutdown()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", default=DEFAULT_MODEL)
parser.add_argument("--layer", type=int, default=0)
parser.add_argument("--prompt", default="The capital of France is")
parser.add_argument("--max-model-len", type=int, default=256)
parser.add_argument("--gpu-memory-utilization", type=float, default=0.5)
parser.add_argument("--reload-timeout", type=float, default=1800)
parser.add_argument("--enforce-eager", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--environment-only", action="store_true")
parser.add_argument("--output", type=Path)
return parser.parse_args()
def main() -> None:
os.environ.setdefault("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
args = parse_args()
if args.environment_only:
result: dict[str, Any] = {"status": "passed", "environment": environment_probe()}
else:
result = run_experiment(args)
rendered = json.dumps(result, indent=2, sort_keys=True)
print(rendered, flush=True)
if args.output is not None:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(rendered + "\n")
if result["status"] != "passed":
raise RuntimeError("NVFP4 layerwise reload verification failed")
if __name__ == "__main__":
main()
+2 -3
View File
@@ -32,11 +32,10 @@ group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt] # Checkpoint at the end of training
+2 -3
View File
@@ -19,11 +19,10 @@ batch_size = 128
group_size = 8
seq_len = 8192
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.model]
seq_len = 16384
+2 -3
View File
@@ -22,11 +22,10 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+2 -3
View File
@@ -40,11 +40,10 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt] # Checkpoint at the end of training
+2 -3
View File
@@ -21,11 +21,10 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 128
group_size = 8
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 1024
+2 -3
View File
@@ -22,11 +22,10 @@ group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 384
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, task = { similarity_power = 4, power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
@@ -26,11 +26,10 @@ name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
enable_lora = true
@@ -25,11 +25,10 @@ name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
enable_lora = true
@@ -25,11 +25,10 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
gpu_memory_utilization = 0.7
@@ -14,11 +14,10 @@ lr = 3e-5
[train.sampling]
max_completion_tokens = 128
[[train.source]]
[[train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt]
interval = 10
@@ -37,11 +37,10 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -50,11 +49,10 @@ num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
@@ -43,11 +43,10 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -56,11 +55,10 @@ num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
@@ -23,11 +23,10 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
@@ -22,11 +22,10 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
-33
View File
@@ -1,33 +0,0 @@
max_steps = 200
seq_len = 2048
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "alphabet-sort"
name = "alphabet-sort"
[ckpt]
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 768
[trainer]
[inference.parallel]
dp = 4
@@ -1,51 +0,0 @@
max_steps = 5000
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
[ckpt]
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
group_size = 8
seq_len = 8192
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.source]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
group_size = 32
[trainer]
[trainer.model]
seq_len = 16384
attn = "flash_attention_2"
[inference.parallel]
dp = 4
[inference.model]
max_model_len = 8192
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-35
View File
@@ -1,35 +0,0 @@
max_steps = 20
seq_len = 2048
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[wandb]
project = "reverse-text"
name = "reverse-text"
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
group_size = 16
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 128
[trainer]
[inference]
[orchestrator.renderer]
name = "prime-qwen3"
-41
View File
@@ -1,41 +0,0 @@
max_steps = 200
seq_len = 4096
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "wiki-search"
name = "wiki-search"
[ckpt]
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
oversampling_factor = 2.0
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 512
[trainer]
[inference.parallel]
dp = 4
[inference.model]
tool_call_parser = "hermes"
-36
View File
@@ -1,36 +0,0 @@
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[wandb]
project = "wordle"
name = "wordle"
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 512
group_size = 16
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer]
[inference.parallel]
dp = 6
[orchestrator.renderer]
name = "prime-qwen3"
@@ -20,11 +20,10 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "color-codeword"
env.taskset = { id = "color-codeword-v1", images_per_turn = 1 }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer]
+2 -3
View File
@@ -24,11 +24,10 @@ type = "echo"
[orchestrator.algo.roles.user]
alpha = 0.1
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 512
+4 -6
View File
@@ -21,11 +21,10 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -34,11 +33,10 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+4 -6
View File
@@ -21,11 +21,10 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -34,11 +33,10 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+8 -11
View File
@@ -31,22 +31,20 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text-grpo"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text-opd"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.algo]
[orchestrator.train.env.algo]
type = "opd"
[orchestrator.train.source.algo.teacher]
[orchestrator.train.env.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
@@ -57,11 +55,10 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+4 -6
View File
@@ -33,11 +33,10 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -46,11 +45,10 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+4 -6
View File
@@ -33,11 +33,10 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -46,11 +45,10 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 1e-4
-53
View File
@@ -1,53 +0,0 @@
max_steps = 20
seq_len = 4096
[model]
name = "Qwen/Qwen3-0.6B"
[wandb]
project = "algorithms-debug"
name = "debug-rae"
[orchestrator]
batch_size = 32
group_size = 1
[orchestrator.algo]
type = "rae"
[orchestrator.renderer]
name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.source]]
name = "kuhn-poker"
env.taskset = { id = "kuhn-poker-v1" }
env.player0.harness = { id = "null" }
env.player0.runtime = { type = "subprocess" }
env.player1.harness = { id = "null" }
env.player1.runtime = { type = "subprocess" }
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 512
[[orchestrator.eval.source]]
name = "kuhn-poker"
env.taskset = { id = "kuhn-poker-v1" }
env.player0.harness = { id = "null" }
env.player0.runtime = { type = "subprocess" }
env.player1.harness = { id = "null" }
env.player1.runtime = { type = "subprocess" }
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+4 -6
View File
@@ -29,11 +29,10 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -42,11 +41,10 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+4 -6
View File
@@ -38,11 +38,10 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -51,11 +50,10 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+4 -6
View File
@@ -38,11 +38,10 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
@@ -51,11 +50,10 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 1e-4
+1 -1
+1 -1
+7 -34
View File
@@ -17,7 +17,6 @@ This page covers the math and the configurable algorithmic components: the algor
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
- [Self-Play Advantage (RAE)](#self-play-advantage-rae)
- [Authoring an Algorithm](#authoring-an-algorithm)
- [Reference Scoring](#reference-scoring)
- [Filters](#filters)
@@ -68,7 +67,6 @@ type = "grpo" # the default
|---|---|---|---|
| `grpo` | policy | `rl` on actions | Standard group-relative RL. |
| `max_rl` | policy | `rl` on actions | MaxRL ([arXiv:2602.02710](https://arxiv.org/abs/2602.02710)): GRPO's centered reward normalized by the group **mean** instead of the standard deviation — the gradient is unbiased for the order-`group_size` truncation of the maximum-likelihood objective, upweighting hard examples like `1/p`. |
| `rae` | policy | `rl` on actions | RAE (SPIRAL, [arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): reward minus a per-agent EMA baseline of that agent's own rewards — the estimator for multi-agent self-play envs, where the group mean would mix the agents' opposite reward scales. See [Self-Play Advantage](#self-play-advantage-rae). |
| `opd` | policy | `ref_kl` on actions | On-policy distillation ([Thinking Machines](https://thinkingmachines.ai/blog/on-policy-distillation/)): the policy samples, per-token reverse KL against a reference model as the gradient signal. Needs a `teacher`. |
| `sft` | *(the teacher)* | `ce` on actions | Hard distillation: a frozen model generates rollouts, the policy trains with CE on its tokens. Needs a frozen `sampling.source` (the teacher it samples from). |
| `opsd` | policy | `ref_kl` on actions | SDFT ([arXiv:2601.19897](https://arxiv.org/abs/2601.19897)): the model is its own reference, conditioned on an expert demonstration. The teacher *is* the live policy (the paper's setting, no extra deployment) — no model to configure. |
@@ -118,18 +116,16 @@ Both components resolve per environment. Each env inherits `[orchestrator.algo]`
[orchestrator.algo]
type = "grpo"
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "math"
env.taskset = { id = "math-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
taskset = { id = "math-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
# inherits the top-level grpo
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "terminal"
env.taskset = { id = "terminal-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "subprocess" }
taskset = { id = "terminal-v1" }
harness = { id = "bash", runtime = { type = "subprocess" } }
algo = { type = "echo" } # this env runs its own algorithm
```
@@ -142,7 +138,6 @@ At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_r
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
| `rae` | `RAEAlgorithm` | `score_group`: per-agent EMA-baseline credit |
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
@@ -179,7 +174,7 @@ $$
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
$$
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, and `echo`'s action tokens).
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the group-relative algorithms (`grpo`, `max_rl`, and `echo`'s action tokens).
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
@@ -281,7 +276,6 @@ The per-token training signal is set by `algo.type` and the [algorithm](#the-alg
|---|---|---|
| `grpo` | `rl` | Group-norm: reward minus per-group baseline, optional length penalty. |
| `max_rl` | `rl` | Mean-normalized group credit (maximum-likelihood RL). |
| `rae` | `rl` | Reward minus a per-agent EMA baseline (SPIRAL's role-conditioned advantage estimation) — for multi-agent self-play envs. |
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
@@ -303,27 +297,6 @@ type = "grpo"
type = "linear"
```
### Self-Play Advantage (RAE)
Group-relative baselines assume the group is exchangeable attempts by one agent. A multi-agent self-play env breaks that: one episode yields one trace per agent, all trainable, and in a zero-sum game the rewards sum to ~0 whatever the policy does — the group mean carries no information, and centering against it converts any structural asymmetry (a first-mover edge) into permanent credit for one agent.
`rae` implements SPIRAL's role-conditioned advantage estimation ([arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): each agent keeps an exponential-moving-average baseline of its own rewards, and every trace's advantage is its reward minus its agent's baseline — measured against the *pre-update* baseline (the unbiased order), then folded in at `decay` (SPIRAL's α, default 0.95). The algorithm instance is per-env, so baselines are keyed per (env, agent) — the paper's per (game, role). Advantages are not normalized, and `group_size` is free (RAE needs no sibling rollouts; `group_size = 1` is fine). Baselines live in orchestrator memory and re-warm from 0 over ~`1/(1 − decay)` traces per agent after a restart.
```toml
[orchestrator.algo]
type = "rae"
decay = 0.95
[[orchestrator.train.source]]
name = "kuhn-poker"
env.taskset = { id = "kuhn-poker-v1" }
env.player0.harness = { id = "null" }
env.player0.runtime = { type = "subprocess" }
env.player1.harness = { id = "null" }
env.player1.runtime = { type = "subprocess" }
```
Both of `kuhn-poker-v1`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
### Authoring an Algorithm
+12 -15
View File
@@ -17,7 +17,7 @@ Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeInt
- [Optional Sub-Configs](#optional-sub-configs)
- [None](#none)
- [Discriminated Unions](#discriminated-unions)
- [Environments](#environments)
- [Environments](#environments-orchestratortrainenv)
- [Environment Variables](#environment-variables)
- [Examples](#examples)
@@ -93,19 +93,19 @@ uv run rl @ rl.toml --trainer.model.lora.target-modules '["q_proj", "k_proj", "v
target_modules = ["q_proj", "k_proj", "v_proj"]
```
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables, see [Environments](#environments).
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables (e.g. environments), see [Environments](#environments-orchestratortrainenv).
### Dicts
CLI takes a JSON literal. TOML uses a table or inline-table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
```bash
uv run rl @ rl.toml --orchestrator.train.source.0.args \
uv run rl @ rl.toml --orchestrator.train.env.0.args \
'{"dataset_name": "openai/gsm8k", "dataset_subset": "main"}'
```
```toml
[[orchestrator.train.source]]
[[orchestrator.train.env]]
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
```
@@ -142,30 +142,27 @@ mu = 0.95
Omit `type` to keep the default variant.
### Environments
### Environments (`[[orchestrator.train.env]]`)
Training and evaluation sources are arrays of tables. Set one source per environment; training sources can optionally carry sampling weights:
Training environments are an array of tables — set one per env, optionally with sampling weights:
```toml
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "gsm8k"
env.taskset = { id = "gsm8k-v1", split = "train" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 3 # 75% of batches
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 1 # default — 25% of batches
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "gsm8k-eval"
env.taskset = { id = "gsm8k-v1", split = "test" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
-13
View File
@@ -14,7 +14,6 @@ This page covers workflows for developing on `prime-rl` itself — running the t
- [Implement the Modeling Code](#implement-the-modeling-code)
- [Register a Mini Preset](#register-a-mini-preset)
- [Run the Smoke Test](#run-the-smoke-test)
- [Adding a Custom VLM Implementation](#adding-a-custom-vlm-implementation)
## Test Suite
@@ -138,15 +137,3 @@ Before merging a new model, you need to ensure the following:
- The small smoke test passes.
In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on `math` environment with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.
## Adding a Custom VLM Implementation
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body — the Qwen3.5 dense (`models/qwen3_5/`) and MoE (`models/qwen3_5_moe/`) implementations are the reference. The pieces, in dependency order:
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
2. **Composite VLM body.** A `*VLMModel` that holds the HF vision encoder and the custom text model, with a `prepare_inputs_embeds_and_position_ids` step: embed tokens, run the vision encoder, scatter image embeddings over placeholder tokens, and build MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
+8 -12
View File
@@ -30,9 +30,7 @@ We support 3 distinct deployment shapes:
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
Every deployment shape has the same client-facing layout: a single global router listens on `inference.server.port` and fronts all vLLM engines, which listen on `inference.backend_port` (+ rank offset). Clients always talk to one URL, regardless of how many engines run behind it.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape and topology knobs such as `num_nodes` and `num_replicas`.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
```toml
[inference.deployment]
@@ -58,8 +56,6 @@ The single-node deployment is the default deployment shape. It runs the inferenc
type = "single_node"
```
The launcher starts a `vllm-router` on `inference.server.port` (default `8000`) fronting the vLLM engine on `inference.backend_port` (default `8100`). Clients connect to the router URL; admin operations (weight updates, health checks) bypass the router and hit the engine port directly — the RL entrypoint wires `orchestrator.model.client.admin_base_url` accordingly.
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
```toml
@@ -106,7 +102,7 @@ tp = 2
dp = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
@@ -164,15 +160,15 @@ num_train_nodes = 4
num_infer_replicas = 3
```
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes, fronted by the single global router.
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
## Router
Every deployment fronts its vLLM engines with a single global router — it listens on `inference.server.port` and is the one URL clients connect to. The backend is configured via a discriminated `[inference.router]` block (`type = "vllm-router" | "llm-d"`):
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
```toml
[inference.router] # or [router] for the standalone inference entrypoint
[inference.deployment.router] # or [deployment.router] for the standalone inference entrypoint
type = "llm-d" # "vllm-router" (default) or "llm-d"
# llm-d-only knobs (all optional):
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
@@ -181,8 +177,8 @@ decode_scorer_overrides = {} # merged onto the P/D decode profile
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. The only backend supported for single-node (local) deployments.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy (multi-node / disaggregated SLURM deployments only). Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
Both backends support the 2 most important things:
- Request routing - KV cache re-use and balanced routing
@@ -283,6 +279,6 @@ enable_router_replay = true # this will also auto-set the inference.enable_retur
enable_return_routed_experts = true
```
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env-server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend increasing `orchestrator.*.env.num_workers` to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
+1 -1
View File
@@ -12,7 +12,7 @@ A `prime-rl` RL run is three cooperating processes:
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses ZMQ, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
## Installation
+1 -1
View File
@@ -231,7 +231,7 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
### Custom Templates
+6 -7
View File
@@ -59,9 +59,9 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.env]]` | Training environments. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Environments](configuration.md#environments-orchestratortrainenv). |
| `[[orchestrator.eval.env]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
**Monitoring:**
@@ -89,7 +89,6 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
|---|---|---|
| `grpo` (default) | None | Standard group-relative RL |
| `max_rl` | None | [MaxRL](https://arxiv.org/abs/2602.02710): GRPO with mean-normalized advantages (maximum-likelihood RL) |
| `rae` | None | [SPIRAL](https://arxiv.org/abs/2506.24119)'s role-conditioned advantage estimation: reward minus a per-agent EMA baseline, for multi-agent self-play envs (e.g. `kuhn-poker-v1`) |
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
| `opsd` | None — the live policy is its own reference (no deployment) | [SDFT](https://arxiv.org/abs/2601.19897): the model is its own reference conditioned on expert demonstrations |
@@ -257,7 +256,7 @@ For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write t
### Log Files
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router_*.log` files):
```
<output_dir>/logs/
@@ -269,7 +268,7 @@ The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The f
│ └── torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log # per-rank
├── inference/
│ ├── node_*.log # per-node inference stdout (multi-node only)
│ └── router.log # the single global router (multi-node only)
│ └── router_*.log # vllm-router per replica (multi-node only)
└── envs/{train,eval}/<env_name>/
├── env_server.log
└── env_worker_<id>.log
@@ -282,7 +281,7 @@ Live tailing from a single point (works on the head node for multi-node runs ove
```bash
tail -F <output_dir>/logs/{trainer,orchestrator,inference}.log
tail -F <output_dir>/logs/trainer/node_*.log # multi-node only
tail -F <output_dir>/logs/inference/router.log # multi-node only
tail -F <output_dir>/logs/inference/router_*.log # multi-node only
```
### Console Output
+16 -19
View File
@@ -46,7 +46,7 @@ enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp = 8
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
@@ -71,7 +71,7 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_episodes = 512
max_inflight_rollouts = 512
[orchestrator.renderer]
name = "glm-4.5"
@@ -93,15 +93,14 @@ num_turns_weight = 0.0
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "openseeker"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
[orchestrator.train.source.env.taskset]
[orchestrator.train.env.env.taskset]
id = "openseeker-v1"
[[orchestrator.train.source.env.taskset.task.judges]]
[[orchestrator.train.env.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -109,22 +108,21 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.source.env.taskset.task.judges]]
# [[orchestrator.train.env.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "redsearcher"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
[orchestrator.train.source.env.taskset]
[orchestrator.train.env.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.source.env.taskset.task.judges]]
[[orchestrator.train.env.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -132,7 +130,7 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.source.env.taskset.task.judges]]
# [[orchestrator.train.env.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
@@ -144,19 +142,18 @@ choices = ["A", "B"]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.taskset]
[orchestrator.eval.env.env.taskset]
id = "browsecomp-v1"
task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.eval.source.env.taskset.task.judges]]
# [[orchestrator.eval.env.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
+7 -9
View File
@@ -7,7 +7,7 @@
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# 2 train + 4 infer nodes. Trainer uses cp=4 (ulysses) plus
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
# CPU offload, and skip-gather / skip-optimizer checkpointing.
@@ -57,7 +57,7 @@ enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp = 8
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
@@ -82,7 +82,7 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_episodes = 512
max_inflight_rollouts = 512
[orchestrator.algo]
type = "grpo"
@@ -97,11 +97,10 @@ num_turns_weight = 0.1
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
[orchestrator.prime_monitor]
@@ -110,11 +109,10 @@ env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels =
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
env.agent.timeout = { rollout = 3600 }
# --- Inference ---
+17 -20
View File
@@ -47,7 +47,7 @@ enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp = 8
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
@@ -72,7 +72,7 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_episodes = 512
max_inflight_rollouts = 512
[orchestrator.renderer]
name = "glm-4.5"
@@ -91,23 +91,22 @@ num_turns_weight = 0.1
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "tmax"
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
[orchestrator.train.source.env.taskset]
[orchestrator.train.env.env.taskset]
id = "tmax-v1"
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
# [[orchestrator.train.source.env.taskset.judges]]
# [[orchestrator.train.env.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.train.source.env.taskset.judges]]
# [[orchestrator.train.env.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
@@ -119,47 +118,45 @@ id = "tmax-v1"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "swebench-verified"
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.taskset]
[orchestrator.eval.env.env.taskset]
id = "swebench-verified-v1"
# [[orchestrator.eval.source.env.taskset.judges]]
# [[orchestrator.eval.env.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.source.env.taskset.judges]]
# [[orchestrator.eval.env.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "terminal-bench-2"
group_size = 4 # avg@4
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.taskset]
[orchestrator.eval.env.env.taskset]
id = "terminal-bench-2-v1"
# [[orchestrator.eval.source.env.taskset.judges]]
# [[orchestrator.eval.env.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.source.env.taskset.judges]]
# [[orchestrator.eval.env.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
+1 -1
View File
@@ -38,7 +38,7 @@ num_decode_replicas = 1
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
[router]
[deployment.router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 }
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 }
+4 -5
View File
@@ -37,7 +37,7 @@ decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="
prefill_vllm_overrides = {"enable_dbo"=true}
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
[inference.router]
[inference.deployment.router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
@@ -81,7 +81,7 @@ weight_decay = 0.0
[orchestrator]
batch_size = 256
group_size = 16
max_inflight_episodes = 2048
max_inflight_rollouts = 2048
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
[orchestrator.model]
@@ -96,11 +96,10 @@ temperature = 1.0
extra_body = {chat_template_kwargs = {clear_thinking = false}}
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "r2e"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "rlm" }
env.agent.runtime = { type = "prime", labels = ["glm5-llmd"] }
env.agent.harness = { id = "rlm", runtime = { type = "prime", labels = ["glm5-llmd"] } }
[inference]
enable_expert_parallel = true
+2 -3
View File
@@ -71,11 +71,10 @@ name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] } }
[[orchestrator.post_batch_filters]]
type = "gibberish"
+14 -21
View File
@@ -47,40 +47,35 @@ weight_decay = 0.01
batch_size = 2048
oversampling_factor = 2
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "swe"
ratio = 0.3
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe"] }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe"] } }
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "deepdive"
ratio = 0.2
env.taskset = { id = "deepdive-v1" }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"] }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] } }
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "math"
ratio = 0.3
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "logic"
ratio = 0.2
env.taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "code"
ratio = 0.2
env.taskset = { id = "i3_code_v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
@@ -89,17 +84,15 @@ enforce = true
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] } }
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference.parallel]
tp = 8
+4 -6
View File
@@ -49,20 +49,18 @@ oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe"] }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe"] } }
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] } }
[inference.parallel]
tp = 8
+5 -7
View File
@@ -66,7 +66,7 @@ type = "adamw"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_episodes = 1536
max_inflight_rollouts = 1536
[orchestrator.algo]
type = "grpo"
@@ -81,22 +81,20 @@ num_turns_weight = 0.1
name = "nemotron-3"
truncate_history_thinking = false
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
[orchestrator.prime_monitor]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
env.agent.timeout = { rollout = 3600 }
[inference]
+5 -7
View File
@@ -48,20 +48,18 @@ max_off_policy_steps = 8
[orchestrator.train.sampling]
max_completion_tokens = 32768
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "math"
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference.parallel]
tp = 8
tp = 8
+5 -7
View File
@@ -46,20 +46,18 @@ batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] } }
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] } }
[inference.parallel]
tp = 8
tp = 8
+2 -3
View File
@@ -35,10 +35,9 @@ batch_size = 512
group_size = 16
max_off_policy_steps = 32
[[orchestrator.train.source]]
[[orchestrator.train.env]]
env.taskset = { id = "general-agent-v1", task = { tools = { colocated = true } }, min_tier = 1 }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "modal" }
env.agent.harness = { id = "null", runtime = { type = "modal" } }
[inference]
gpu_memory_utilization = 0.85
+2 -3
View File
@@ -31,10 +31,9 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference] # Default inference config
+4 -6
View File
@@ -16,20 +16,18 @@ batch_size = 512
group_size = 8
seq_len = 8192
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
group_size = 32
[trainer.model]
+2 -3
View File
@@ -15,11 +15,10 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
+2 -3
View File
@@ -133,11 +133,10 @@ uv run eval wiki-search-v1 --harness.id null \
The V1 taskset fixes the question bank and searchable corpus. You can replace its reference judge in `rl.toml`:
```toml
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "wiki-search"
taskset = { id = "wiki-search-v1", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
harness = { id = "null" }
runtime = { type = "subprocess" }
harness = { id = "null", runtime = { type = "subprocess" } }
```
## Notes
+2 -3
View File
@@ -44,11 +44,10 @@ max_completion_tokens = 512
type = "zero_advantage"
enforce = true
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt] # Checkpoint at the end of training
+2 -3
View File
@@ -18,11 +18,10 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 512
group_size = 16
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 1024
+144
View File
@@ -0,0 +1,144 @@
apiVersion: batch/v1
kind: Job
metadata:
generateName: nvfp4-layerwise-
labels:
app.kubernetes.io/name: nvfp4-layerwise-reload
spec:
backoffLimit: 0
activeDeadlineSeconds: 10800
ttlSecondsAfterFinished: 86400
template:
metadata:
labels:
app.kubernetes.io/name: nvfp4-layerwise-reload
spec:
restartPolicy: Never
automountServiceAccountToken: false
imagePullSecrets:
- name: ghcr-secret
nodeSelector:
kubernetes.io/arch: arm64
nvidia.com/gpu.product: NVIDIA-GB200
containers:
- name: experiment
image: ghcr.io/primeintellect-ai/hosted-rl/prime-rl:v0.7.1.dev2-13-g91292f812-feat-convert-entrypoint
imagePullPolicy: IfNotPresent
securityContext:
runAsUser: 0
command: ["/bin/bash", "-lc"]
args:
- |
set -euo pipefail
vllm_wheel='https://wheels.vllm.ai/910cc8543a6907c9cc87c417f8f2420969278bf5/vllm-0.23.1rc1.dev1392%2Bg910cc8543-cp38-abi3-manylinux_2_28_aarch64.whl'
uv --no-config pip install \
--python /app/.venv/bin/python \
--upgrade \
--no-deps \
"$vllm_wheel" \
'https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_python-0.6.15.post1-py3-none-any.whl' \
'https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_cubin-0.6.15.post1-py3-none-any.whl'
if [[ -n "${PRIME_RL_VLLM_PYTHON_OVERLAY:-}" ]]; then
site_packages=$(/app/.venv/bin/python -c 'import site; print(site.getsitepackages()[0])')
cp -a "${PRIME_RL_VLLM_PYTHON_OVERLAY}/vllm/." "${site_packages}/vllm/"
fi
export NVFP4_CACHE_HIT=0
if [[ -f "${NVFP4_CACHE_READY_MARKER}" ]] && \
[[ "$(<"${NVFP4_CACHE_READY_MARKER}")" == "${NVFP4_CACHE_KEY}" ]]; then
# The image recreates /app/.venv for every pod. Its wheel sources
# are byte-identical for this exact cache key, but receive fresh
# mtimes, which otherwise makes Ninja rebuild cached objects.
find "${FLASHINFER_WORKSPACE_BASE}" \
-type f \( -name '*.so' -o -name '*.o' -o -name '*.a' \) \
-exec touch {} +
export NVFP4_CACHE_HIT=1
echo "Reusing persistent NVFP4 JIT cache: ${NVFP4_CACHE_KEY}"
fi
export PYTHONPATH="${PRIME_RL_SOURCE}/src${PYTHONPATH:+:${PYTHONPATH}}"
probe_args=()
if [[ "${NVFP4_ENVIRONMENT_ONLY}" == "1" ]]; then
probe_args+=(--environment-only)
fi
cd /app
VIRTUAL_ENV=/app/.venv uv run --active --no-sync python \
"${PRIME_RL_SOURCE}/benchmarks/scripts/nvfp4_layerwise_reload.py" \
"${probe_args[@]}" \
--output "/workspace/results/${POD_NAME}.json"
env:
- name: PRIME_RL_SOURCE
value: /workspace/live
- name: NVFP4_ENVIRONMENT_ONLY
value: "${NVFP4_ENVIRONMENT_ONLY}"
- name: PRIME_RL_VLLM_PYTHON_OVERLAY
value: /workspace/vllm-fixes/fix-nvfp4-reload-writable-scales
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: HF_HOME
value: /tmp/huggingface
- name: HF_HUB_CACHE
value: /model-cache
- name: HF_HUB_OFFLINE
value: "1"
- name: TRANSFORMERS_OFFLINE
value: "1"
- name: HF_HUB_DISABLE_XET
value: "1"
- name: HF_HUB_DOWNLOAD_TIMEOUT
value: "1800"
- name: HF_HUB_ETAG_TIMEOUT
value: "300"
- name: UV_CACHE_DIR
value: /workspace/.cache/uv/arm64
- name: UV_LINK_MODE
value: copy
# Keep generated kernels across Jobs. The versioned root prevents a
# vLLM/FlashInfer/Torch or compiler upgrade from reusing stale code.
- name: FLASHINFER_WORKSPACE_BASE
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13
- name: VLLM_CACHE_ROOT
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13/vllm
- name: TORCH_EXTENSIONS_DIR
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13/torch-extensions
- name: TRITON_CACHE_DIR
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13/triton
- name: CUDA_CACHE_PATH
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13/cuda
- name: NVFP4_CACHE_KEY
value: image-91292f812_sm100a_cuda12.8_torch2.11.0_vllm-910cc8543_flashinfer-0.6.15.post1
- name: NVFP4_CACHE_READY_MARKER
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13/.prime-rl-ready
- name: VLLM_ALLOW_INSECURE_SERIALIZATION
value: "1"
- name: TOKENIZERS_PARALLELISM
value: "false"
resources:
requests:
cpu: "16"
memory: 96Gi
nvidia.com/gpu: "1"
limits:
cpu: "64"
memory: 256Gi
nvidia.com/gpu: "1"
volumeMounts:
- name: source
mountPath: /workspace
- name: model-cache
mountPath: /model-cache
readOnly: true
- name: dshm
mountPath: /dev/shm
volumes:
- name: source
persistentVolumeClaim:
claimName: prime-rl-dev-source
- name: model-cache
hostPath:
path: /scratch/model-cache
type: Directory
- name: dshm
emptyDir:
medium: Memory
sizeLimit: 32Gi
@@ -0,0 +1,110 @@
output_dir = "/data/nvfp4-e2e/runs/qwen3-30b-a3b-instruct-4x4"
max_steps = 20
seq_len = 8192
clean_output_dir = true
[log]
level = "info"
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
[weight_broadcast]
type = "nccl"
timeout = 7200
quantize_in_weight_transfer = false
# The k8s launcher maps these two counts to separate, full-node pods. The
# aggregate gpus_per_node value only satisfies prime-rl's single-node schema;
# each GB200 node physically has four GPUs.
[deployment]
type = "single_node"
num_train_gpus = 4
num_infer_gpus = 4
gpus_per_node = 8
[trainer]
dist_timeout_seconds = 7200
[trainer.file_monitor]
filename = "trainer-metrics.jsonl"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 4
ep_comm_backend = "torch"
optim_cpu_offload = true
fsdp_cpu_offload = false
ac_offloading = "None"
conversion_dir = "/data/nvfp4-e2e/model-conversions/qwen3-30b-a3b-instruct-2507"
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
mode = "full"
freq = 1
[trainer.model.compile]
[trainer.optim]
type = "sign_sgd"
lr = 1e-6
weight_decay = 0.0
max_norm = 1.0
[trainer.loss]
type = "default"
kl_tau = 0.001
[orchestrator]
batch_size = 64
group_size = 8
oversampling_factor = 1.0
max_off_policy_steps = 0
post_batch_filters = []
collect_inference_metrics = true
[orchestrator.file_monitor]
filename = "orchestrator-metrics.jsonl"
[orchestrator.model.client]
wait_for_ready_timeout = 10800
[orchestrator.renderer]
name = "qwen3"
enable_thinking = false
[orchestrator.train.sampling]
temperature = 1.0
max_completion_tokens = 2048
[[orchestrator.train.env]]
name = "math"
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
quantization = "nvfp4_per_token"
gpu_memory_utilization = 0.85
enable_prefix_caching = true
[inference.model]
dtype = "bfloat16"
max_model_len = 8192
# Establish the RL/weight-transfer baseline before separately validating
# online-NVFP4 reloads under captured CUDA graphs.
enforce_eager = true
[inference.parallel]
tp = 4
[k8s]
release = "nvfp4-qwen3-e2e-4x4"
namespace = "dev-matej"
create_namespace = false
chart = "../fft/charts/prime-rl-fft"
example = "nvfp4-qwen3-e2e-4x4"
values_out = "k8s/experiments/nvfp4-qwen3-e2e-4x4.generated.values.yaml"
overlays = [
"k8s/experiments/nvfp4-qwen3-e2e-4x4.values.yaml",
]
@@ -0,0 +1,131 @@
weightBroadcast:
type: nccl
port: 29501
trainer:
replicas: 1
gpu:
enabled: true
count: 4
autoStart: true
inference:
enabled: true
islands: 1
podsPerIsland: 1
gpu:
enabled: true
count: 4
autoStart: true
tp: 4
router:
enabled: true
scope: global
policy: consistent_hash
backendPort: 8001
orchestrator:
enabled: true
autoStart: true
command: uv run --no-sync orchestrator @ /etc/prime-rl/orchestrator.toml
resumeCleanup:
enabled: true
outputDir: /data/nvfp4-e2e/runs/qwen3-30b-a3b-instruct-4x4
configs:
trainer: "output_dir = \"/data/nvfp4-e2e/runs/qwen3-30b-a3b-instruct-4x4\"\nmatmul_precision = \"high\"\nmax_steps = 20\nenable_router_replay = false\ndist_timeout_seconds = 7200\nmax_concurrent_runs = 1\nenable_token_export = false\n\n[model]\nname = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\ntrust_remote_code = false\nconversion_dir = \"/data/nvfp4-e2e/model-conversions/qwen3-30b-a3b-instruct-2507\"\nseq_len = 8192\nattn = \"flash_attention_3\"\nfsdp_cpu_offload = false\noptim_cpu_offload = true\nreshard_after_forward = true\ndp_replicate = 1\nep = 4\nep_comm_backend = \"torch\"\ndeepep_num_sms = 20\ncp = 1\ncp_style = \"ring\"\nimpl = \"custom\"\noptimization_dtype = \"float32\"\nreduce_dtype = \"float32\"\nmoe_router_dtype = \"float32\"\nmoe_use_grouped_mm = true\nfreeze_moe_router = false\nfused_lm_head_token_chunk_size = 1024\n\n[model.compile]\nfullgraph = false\n\n[model.ac]\nmode = \"full\"\nfreq = 1\ntargets = [\n \"norm\",\n]\n\n[model.debug]\nrandom_init = false\nforce_balanced_routing = false\n\n[tokenizer]\nname = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\ntrust_remote_code = false\n\n[data]\n\n[loss]\ntype = \"default\"\ndppo_mask_low = 0.2\ndppo_mask_high = 0.2\nadv_tau = 1.0\nkl_tau = 0.001\n\n[optim]\nlr = 1e-06\nweight_decay = 0.0\nmax_norm = 1.0\ntype = \"sign_sgd\"\n\n[scheduler]\ntype = \"constant\"\n\n[weight_broadcast]\nhost = \"localhost\"\nport = 29501\ntimeout = 7200\ninference_world_size = 4\ntype = \"nccl\"\nquantize_in_weight_transfer = false\n\n[rollout_transport]\ntype = \"filesystem\"\n\n[log]\nlevel = \"info\"\nvf_level = \"info\"\njson_logging = false\nlog_data = false\ninterval = 10.0\nranks_filter = [\n 0,\n]\n\n[file_monitor]\nfilename = \"trainer-metrics.jsonl\"\n\n[gc]\ninterval = 50\n\n[env_vars]\n"
orchestrator: "pre_batch_filters = [\n { type = \"gibberish\", enforce = false, token_id_threshold = 100000, logprob_offset = 2.0 },\n { type = \"repetition\", enforce = false, window = 3000, prob_threshold = 0.99 },\n { type = \"zero_advantage\", enforce = false },\n]\npost_batch_filters = []\ncollect_inference_metrics = true\noutput_dir = \"/data/nvfp4-e2e/runs/qwen3-30b-a3b-instruct-4x4/run_default\"\nbatch_size = 64\noversampling_factor = 1.0\nmax_inflight_rollouts = 64\ngroup_size = 8\nseq_len = 8192\nnum_train_workers = 4\nmax_steps = 20\nmax_off_policy_steps = 0\nbench = false\n\n[algo]\ntype = \"grpo\"\n\n[algo.sampling]\nsource = \"policy\"\n\n[model]\nname = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\ntrust_remote_code = false\n\n[model.client]\nwait_for_ready_timeout = 10800\nbase_url = [\n \"http://nvfp4-qwen3-e2e-4x4-inference-0.nvfp4-qwen3-e2e-4x4-inference.dev-matej.svc.cluster.local:8000/v1\",\n]\napi_key_var = \"VLLM_API_KEY\"\nskip_model_check = false\ndp_rank_count = 1\nadmin_base_url = [\n \"http://nvfp4-qwen3-e2e-4x4-inference-0.nvfp4-qwen3-e2e-4x4-inference.dev-matej.svc.cluster.local:8000/v1\",\n]\n\n[model.client.headers]\n\n[model.client.headers_from_env]\n\n[model.client.extra_headers_from_state]\nX-Session-ID = \"trajectory_id\"\n\n[[train.env]]\nname = \"math\"\n\n[train.env.env.taskset]\nid = \"i3_math_v1\"\n\n[train.env.env.agent.harness]\nid = \"null\"\n\n[train.env.env.agent.harness.runtime]\ntype = \"subprocess\"\n\n[train.sampling]\ntemperature = 1.0\nmax_completion_tokens = 2048\n\n[train.sampling.extra_body]\n\n[tokenizer]\nname = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\ntrust_remote_code = false\n\n[renderer]\nname = \"qwen3\"\nenable_thinking = false\n\n[optim]\nlr = 0.0001\n\n[log]\nlevel = \"info\"\nvf_level = \"info\"\njson_logging = false\nlog_data = false\ninterval = 10.0\n\n[env_vars]\n\n[file_monitor]\nfilename = \"orchestrator-metrics.jsonl\"\n\n[weight_broadcast]\nhost = \"localhost\"\nport = 29501\ntimeout = 7200\ninference_world_size = 4\ntype = \"nccl\"\nquantize_in_weight_transfer = false\n\n[rollout_transport]\ntype = \"filesystem\"\n"
inference: 'enable_lora = false
max_loras = 8
max_cpu_loras = 100
enable_prefix_caching = true
gpu_memory_utilization = 0.85
quantization = "nvfp4_per_token"
api_server_count = 1
data_parallel_rpc_port = 13345
seed = 0
enable_expert_parallel = false
all2all_backend = "allgather_reducescatter"
enable_eplb = false
enable_dbo = false
use_deep_gemm = false
use_pd_kv_transfer = false
enable_return_routed_experts = false
enable_fp32_lm_head = true
enable_fp32_router_logits = true
[server]
port = 8000
liveness_timeout_seconds = 30.0
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
trust_remote_code = false
dtype = "bfloat16"
max_model_len = 8192
enforce_eager = true
tool_call_parser = "hermes"
[parallel]
tp = 4
dp = 1
[log]
level = "info"
vf_level = "info"
json_logging = false
log_data = false
interval = 10.0
[env_vars]
[weight_broadcast]
type = "nccl"
[vllm_extra]
'
config:
example: nvfp4-qwen3-e2e-4x4
secrets:
enabled: true
name: prime-rl-secrets
image:
repository: docker.io/primeintellect/prime-rl
tag: commit-e96bbae
@@ -0,0 +1,121 @@
runId: nvfp4-qwen3-e2e-4x4
imagePullSecrets:
- name: ghcr-secret
image:
repository: ghcr.io/primeintellect-ai/prime-rl
tag: nvfp4-e2e.dev3-arm64
digest: sha256:4a2713ef9f6df8f002a8e63398f408127c05588e611e655d792252ecfd627ace
pullPolicy: IfNotPresent
devSource:
enabled: false
# Reuse the large RWX PVC for run output and the one-time trainer-native model
# conversion. The root was provisioned world-writable by the dev workspace.
storage:
enabled: true
existingClaim: model-cache
mountPath: /data
fixPermissions: false
# The HF snapshot is already present on every GB200 node.
modelCache:
enabled: true
type: hostPath
hostPath: /scratch/model-cache
subPath: ""
mountPath: /model-cache
readOnly: true
offline: true
# Mount the exact cache populated by the successful SM100 layerwise test.
inferenceCache:
enabled: true
existingClaim: prime-rl-dev-source
subPath: .cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13
mountPath: /inference-cache
weightBroadcast:
type: nccl
port: 29501
inferenceWorldSize: 4
orchestrator:
runAsRoot: true
resources:
requests:
cpu: "4"
memory: 16Gi
nodeSelector:
kubernetes.io/arch: arm64
nvidia.com/gpu.product: NVIDIA-GB200
trainer:
hostNetwork: true
resources:
requests:
cpu: "64"
memory: 640Gi
rdma:
enabled: true
deviceName: rdma/rdma_shared_device_a
count: 1
nodeSelector:
kubernetes.io/arch: arm64
nvidia.com/gpu.product: NVIDIA-GB200
env: &nccl-env
- name: NCCL_IB_HCA
value: mlx5_2
- name: NCCL_CROSS_NIC
value: "0"
- name: VLLM_RPC_TIMEOUT
value: "7200000"
- name: TRANSFORMERS_OFFLINE
value: "1"
inference:
# Avoid the auxiliary vllm-router for this one TP=4 server.
router:
enabled: false
hostNetwork: true
command: bash /app/k8s/experiments/run_nvfp4_inference.sh
resources:
requests:
cpu: "64"
memory: 384Gi
rdma:
enabled: true
deviceName: rdma/rdma_shared_device_a
count: 1
nodeSelector:
kubernetes.io/arch: arm64
nvidia.com/gpu.product: NVIDIA-GB200
env:
- name: NCCL_IB_HCA
value: mlx5_2
- name: NCCL_CROSS_NIC
value: "0"
- name: VLLM_RPC_TIMEOUT
value: "7200000"
- name: TRANSFORMERS_OFFLINE
value: "1"
- name: VLLM_ALLOW_INSECURE_SERIALIZATION
value: "1"
- name: TOKENIZERS_PARALLELISM
value: "false"
- name: UV_CACHE_DIR
value: /inference-cache/uv
- name: UV_LINK_MODE
value: copy
- name: VLLM_CACHE_ROOT
value: /inference-cache/vllm
- name: TORCH_EXTENSIONS_DIR
value: /inference-cache/torch-extensions
- name: CUDA_CACHE_PATH
value: /inference-cache/cuda
- name: NVFP4_CACHE_KEY
value: image-91292f812_sm100a_cuda12.8_torch2.11.0_vllm-910cc8543_flashinfer-0.6.15.post1
- name: NVFP4_CACHE_READY_MARKER
value: /inference-cache/.prime-rl-ready
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env bash
set -euo pipefail
# Pin the process environment explicitly. The Helm chart also supplies generic
# cache defaults; these versioned paths are the authoritative values for this
# exact runtime and avoid relying on duplicate-env ordering.
export UV_CACHE_DIR=/inference-cache/uv
export UV_LINK_MODE=copy
export FLASHINFER_WORKSPACE_BASE=/inference-cache
export VLLM_CACHE_ROOT=/inference-cache/vllm
export TORCH_EXTENSIONS_DIR=/inference-cache/torch-extensions
export TRITON_CACHE_DIR=/inference-cache/triton
export CUDA_CACHE_PATH=/inference-cache/cuda
# Verify that this is the immutable experiment image, including the approved
# writable-scale fix. Nothing is installed or modified in the pod.
/app/.venv/bin/python - <<'PY'
from importlib.metadata import version
from pathlib import Path
import vllm
expected = {
"vllm": "0.23.1rc1.dev1392+g910cc8543",
"flashinfer-python": "0.6.15.post1",
"flashinfer-cubin": "0.6.15.post1",
}
actual = {package: version(package) for package in expected}
if actual != expected:
raise RuntimeError(f"Unexpected NVFP4 runtime: {actual!r} != {expected!r}")
path = (
Path(vllm.__file__).parent
/ "model_executor/layers/quantization/utils/flashinfer_fp4_moe.py"
)
source = path.read_text()
for scale in ("a13_scale", "a2_scale"):
old = f"{scale}.max().to(torch.float32).expand(num_experts)"
new = f"{scale}.max().to(torch.float32).repeat(num_experts)"
if source.count(old) != 0 or source.count(new) != 2:
raise RuntimeError(f"Writable NVFP4 scale fix is absent or unexpected in {path}")
print(f"Verified pinned NVFP4 runtime and writable-scale fix in {path}")
PY
export NVFP4_CACHE_HIT=0
if [[ -f "$NVFP4_CACHE_READY_MARKER" ]] && \
[[ "$(<"$NVFP4_CACHE_READY_MARKER")" == "$NVFP4_CACHE_KEY" ]]; then
# The runtime is baked into an immutable image, so its CUDA source mtimes
# are stable across pods. Preserve Ninja's recorded output mtimes: touching
# cached objects here invalidates .ninja_log and forces the expensive
# fused-MoE translation units to rebuild.
export NVFP4_CACHE_HIT=1
echo "Reusing persistent NVFP4 JIT cache: $NVFP4_CACHE_KEY"
else
# Mark the versioned cache ready only after the API health endpoint proves
# that model load, online quantization, and lazy kernel setup all succeeded.
(
for _ in $(seq 1 2400); do
if curl -fsS http://127.0.0.1:8000/health >/dev/null 2>&1; then
marker_tmp="${NVFP4_CACHE_READY_MARKER}.$$"
printf '%s\n' "$NVFP4_CACHE_KEY" >"$marker_tmp"
mv "$marker_tmp" "$NVFP4_CACHE_READY_MARKER"
echo "Marked persistent NVFP4 JIT cache ready: $NVFP4_CACHE_KEY"
exit 0
fi
sleep 5
done
echo "Inference did not become healthy; leaving cache unmarked" >&2
) &
fi
cd /app
exec uv run --active --no-sync inference @ /etc/prime-rl/inference.toml "$@"
+3 -4
View File
@@ -13,11 +13,10 @@ name = "reverse-text"
[train.sampling]
max_completion_tokens = 128
[[train.source]]
[[train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[renderer]
name = "prime-qwen3"
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies = [
"renderers>=0.1.8",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.2.2.dev43",
"verifiers>=0.2.1",
]
[build-system]
@@ -232,27 +232,6 @@ class MaxRLAlgoConfig(BaseAlgoConfig):
action_loss_type: ClassVar[ActionLossType] = "rl"
class RAEAlgoConfig(BaseAlgoConfig):
type: Literal["rae"] = "rae"
"""RAE — role-conditioned advantage estimation (SPIRAL,
https://arxiv.org/abs/2506.24119): scalar advantage = reward minus a
per-agent EMA baseline of that agent's own rewards, consumed by the ``rl``
loss component. The advantage estimator for multi-agent self-play envs
(``kuhn-poker-v1`` and friends): in a zero-sum game the group mean is ~0
whatever the policy does, so a group-relative baseline mixes the agents'
opposite reward scales — a structural first-mover edge would read as
permanent credit. Per-agent baselines measure each agent against its own
expected reward instead. Works with any ``group_size`` (including 1)."""
action_loss_type: ClassVar[ActionLossType] = "rl"
decay: float = Field(0.95, ge=0.0, lt=1.0)
"""EMA decay of the per-agent baselines (SPIRAL's α): after a trace is
scored, its agent's baseline moves as ``baseline ← decay · baseline +
(1 − decay) · reward``. Baselines start at 0 and live in orchestrator
memory — a restart re-warms them over ~1/(1 − decay) traces per agent."""
class OPDAlgoConfig(BaseAlgoConfig):
type: Literal["opd"] = "opd"
"""On-policy distillation: the per-token signal is the reverse KL to
@@ -326,7 +305,7 @@ class SFTAlgoConfig(BaseAlgoConfig):
AlgoConfig: TypeAlias = Annotated[
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | RAEAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
Field(discriminator="type"),
]
"""The training algorithm: sampling plus the per-token training signal (credit
@@ -335,7 +314,6 @@ its class defaults are the vetted setting.
- ``grpo`` — policy group sampling, group-relative advantage, RL loss (the default).
- ``max_rl`` — GRPO with mean-normalized advantages (maximum-likelihood RL).
- ``rae`` — reward minus a per-agent EMA baseline (SPIRAL), for multi-agent self-play envs.
- ``opd`` — on-policy distillation: policy samples, per-token reverse KL against a reference model. Needs ``teacher``.
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
@@ -190,6 +190,9 @@ class VllmRouterConfig(BaseConfig):
type: Literal["vllm-router"] = "vllm-router"
port: int = 8000
"""Port the router listens on — becomes the client-facing router URL."""
policy: str = "consistent_hash"
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
@@ -199,6 +202,9 @@ class LlmdRouterConfig(BaseConfig):
type: Literal["llm-d"] = "llm-d"
port: int = 8000
"""Port the Envoy gateway listens on — becomes the client-facing router URL."""
scorers: dict[str, float] = {
"prefix-cache-scorer": 3.0,
"active-request-scorer": 2.0,
@@ -248,6 +254,12 @@ class BaseInferenceDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
backend_port: int = 8100
"""Port for the per-rank vLLM backend instances."""
router: RouterConfig = VllmRouterConfig()
"""Router fronting the per-rank endpoints."""
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["single_node"] = "single_node"
@@ -319,12 +331,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
class InferenceConfig(BaseConfig):
server: ServerConfig = ServerConfig()
router: RouterConfig | None = Field(default_factory=VllmRouterConfig)
"""Router fronting the engine(s). Every deployment runs a single global router as the client-facing endpoint on ``server.port``, with the engines listening on ``backend_port``. Set to ``None`` to run a bare engine on ``server.port`` without a router (the SLURM launchers do this for per-rank engine processes; the sbatch script starts the router)."""
backend_port: int = 8100
"""Port for the vLLM engine(s) behind the router. Defaults to ``server.port + 100``. Multi-node deployments start one engine per local DP rank at ``backend_port + rank``."""
model: ModelConfig = Field(default_factory=ModelConfig)
parallel: ParallelConfig = ParallelConfig()
@@ -432,7 +438,8 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
if self.router is not None and self.router.type == "llm-d" and self.enable_return_routed_experts:
router = getattr(self.deployment, "router", None)
if router is not None and router.type == "llm-d" and self.enable_return_routed_experts:
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
@@ -440,21 +447,6 @@ class InferenceConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_router_deployment(self):
"""The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines."""
if self.router is not None and self.router.type == "llm-d" and self.deployment.type == "single_node":
raise ValueError("The llm-d router backend requires a multi-node or disaggregated SLURM deployment.")
if self.router is None and self.deployment.type in ("multi_node", "disaggregated"):
raise ValueError("Multi-node / disaggregated deployments require a router fronting the per-rank engines.")
return self
@model_validator(mode="after")
def auto_setup_backend_port(self):
if self.router is not None and "backend_port" not in self.model_fields_set:
self.backend_port = self.server.port + 100
return self
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
@@ -3,7 +3,7 @@ from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
import verifiers.v1 as vf
from pydantic import AliasChoices, Field, SerializeAsAny, model_validator
from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.algorithm import (
@@ -15,12 +15,12 @@ from prime_rl.configs.shared import (
ClientConfig,
EnvVars,
FileMonitorConfig,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
TransportConfig,
WandbWithExtrasConfig,
ZMQTransportConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig
@@ -151,52 +151,27 @@ class EvalSamplingConfig(BaseConfig):
return data
class ServingConfig(vf.ServingConfig):
"""Verifiers' serving block with ``address`` back to optional. Verifiers defaults it
to the address its own ``serve`` CLI binds; here the question is whether to spawn a
server or connect to one already running, and that answer has to survive the
resolved config being written to a file and read back — so it must be a *value*
(``None``), not field-set metadata, which a round-trip drops."""
address: str | None = None
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to that server instead of spawning one; when None, it spawns a subprocess env server on a free port. ``pool`` sizes the spawned server."""
class EnvConfig(BaseConfig):
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
runs, ``serve`` — how it's hosted, ``legacy`` — a classic v0 env instead) plus this
orchestrator's own per-env knobs."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
serve: ServingConfig = ServingConfig()
"""How the env server is run: ``serve.pool`` sizes the spawned server, ``serve.address`` points at an external one instead, and ``serve.max_concurrent`` bounds one worker's episodes in flight (unset = unbounded; the dispatcher's ``max_inflight_episodes`` is the run's bound)."""
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
"""A classic (v0) environment to run through the bridge instead of ``env``."""
class EnvConfig(vf.EnvServerConfig):
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
address: str | None = None
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
ratio: float = Field(1.0, gt=0)
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
@model_validator(mode="before")
@classmethod
def _resolve_env(cls, data):
"""Narrow ``env`` to the selected env's config class."""
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
@property
def is_legacy(self) -> bool:
"""A classic (v0) env run through the bridge: a legacy id and no v1 taskset."""
return self.legacy.id is not None and not self.env.taskset.id
@property
def env_id(self) -> str:
"""The env's identifier: the v1 env's, else the v0 env id."""
return self.env.env_id or self.legacy.id or ""
def _migrate_num_workers(cls, data):
"""Back-compat: the removed ``num_workers`` maps onto ``pool`` — an int becomes a
fixed ``static`` pool, ``"auto"`` falls through to the default ``elastic`` pool. An
explicit ``pool`` always wins."""
if isinstance(data, dict) and "num_workers" in data:
num_workers = data.pop("num_workers")
if "pool" not in data and num_workers != "auto":
data["pool"] = {"type": "static", "num_workers": num_workers}
return data
@property
def resolved_name(self) -> str:
@@ -204,24 +179,9 @@ class EnvConfig(BaseConfig):
@model_validator(mode="after")
def validate_env(self):
# A v0 id next to any v1 env identity leaves one of the two going nowhere, and
# which one depends on `is_legacy`: a taskset makes it False, so the v0 env never
# loads; a bare `env.id` leaves it True, so the v0 env runs under the v1 name.
if self.legacy.id is not None and self.env.env_id:
if self.env.taskset.id:
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with "
f"the v1 taskset {self.env.taskset.id!r}. Pairing a reusable env with a taskset "
f"is env.id = {self.legacy.id!r}; to run the v0 env instead, drop the taskset."
)
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with the "
f"v1 env.id {self.env.id!r}: the v0 env is what would run, stamped with the v1 "
"env's name. Keep whichever one you meant to run."
)
if not self.env_id:
raise ValueError(
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or legacy = { id = "<id>" } (v0)'
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or id = "<id>" (v0/legacy)'
)
if self.resolved_name == "agg":
raise ValueError(
@@ -232,21 +192,21 @@ class EnvConfig(BaseConfig):
@model_validator(mode="after")
def resolve_legacy_env_kwargs(self):
"""For a v0/legacy env, surface the v1 knobs the legacy bridge applies via
``legacy.extra_env_kwargs`` (``env.set_kwargs(...)``): the per-rollout wall-clock
timeout and the multi-turn completion-token budget, read off ``env.agent``.
(``max_seq_len`` is added per train run in ``OrchestratorConfig.resolve_env_config``,
which knows ``seq_len``.)"""
``extra_env_kwargs`` (``env.set_kwargs(...)``): the per-rollout wall-clock timeout and
the multi-turn completion-token budget, read off ``env.agent``. (``max_seq_len`` is
added per train run in ``OrchestratorConfig.resolve_env_config``, which knows
``seq_len``.)"""
if self.is_legacy:
agent = getattr(self.env, "agent", None)
if agent is not None:
if agent.timeout.rollout is not None:
self.legacy.extra_env_kwargs["timeout_seconds"] = agent.timeout.rollout
self.extra_env_kwargs["timeout_seconds"] = agent.timeout.rollout
if agent.max_output_tokens is not None:
self.legacy.extra_env_kwargs["max_total_completion_tokens"] = agent.max_output_tokens
self.extra_env_kwargs["max_total_completion_tokens"] = agent.max_output_tokens
return self
class TrainSourceConfig(EnvConfig):
class TrainEnvConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
@@ -260,7 +220,7 @@ class TrainSourceConfig(EnvConfig):
this env its own algorithm."""
class EvalSourceConfig(EnvConfig):
class EvalEnvConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
@@ -275,8 +235,8 @@ class EvalSourceConfig(EnvConfig):
class TrainConfig(BaseConfig):
source: list[TrainSourceConfig] = Field(default_factory=list)
"""Training sources."""
env: list[TrainEnvConfig] = Field(default_factory=list)
"""Training environments."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
@@ -286,7 +246,7 @@ class TrainConfig(BaseConfig):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
is configured per env, defaulting to elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.source:
for env in self.env:
if "sampling" not in env.model_fields_set:
env.sampling = TrainSamplingConfig(**group_sampling)
else:
@@ -296,7 +256,7 @@ class TrainConfig(BaseConfig):
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.source]
env_names = [env.resolved_name for env in self.env]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
@@ -306,8 +266,8 @@ class TrainConfig(BaseConfig):
class EvalConfig(BaseConfig):
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
env: list[EvalEnvConfig] = Field(default_factory=list)
"""Evaluation environments."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
"""Shared eval sampling configuration; can differ from training sampling."""
@@ -330,33 +290,33 @@ class EvalConfig(BaseConfig):
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for source in self.source:
if "sampling" not in source.model_fields_set:
source.sampling = EvalSamplingConfig(**group_sampling)
for env in self.env:
if "sampling" not in env.model_fields_set:
env.sampling = EvalSamplingConfig(**group_sampling)
else:
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
source.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in source.model_fields_set:
source.num_examples = self.num_examples
if "group_size" not in source.model_fields_set:
source.group_size = self.group_size
if "interval" not in source.model_fields_set:
source.interval = self.interval
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in env.model_fields_set:
env.num_examples = self.num_examples
if "group_size" not in env.model_fields_set:
env.group_size = self.group_size
if "interval" not in env.model_fields_set:
env.interval = self.interval
return self
@model_validator(mode="after")
def validate_non_empty_sources(self):
if not self.source:
def validate_non_empty_envs(self):
if not self.env:
raise ValueError(
"EvalConfig must define at least one source. Either drop the "
"EvalConfig must define at least one env. Either drop the "
"[orchestrator.eval] block entirely (to disable eval) or "
"add a [[orchestrator.eval.source]] block."
"add a [[orchestrator.eval.env]] block."
)
return self
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [source.resolved_name for source in self.source]
env_names = [env.resolved_name for env in self.env]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
@@ -477,7 +437,7 @@ class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
assignment and loss routing, fused — its ``type`` names the algorithm).
Defaults to ``grpo``. Override per source via ``[[orchestrator.train.source]]``'s
Defaults to ``grpo``. Override per env via ``[[orchestrator.train.env]]``'s
``algo``."""
model: ModelConfig = ModelConfig()
@@ -549,7 +509,7 @@ class OrchestratorConfig(BaseConfig):
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to receive updated weights from the trainer."""
rollout_transport: TransportConfig = ZMQTransportConfig()
rollout_transport: TransportConfig = FileSystemTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
output_dir: Path = Path("outputs/run_default")
@@ -565,12 +525,10 @@ class OrchestratorConfig(BaseConfig):
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
oversampling_factor: float | None = Field(None, gt=0)
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_episodes`` from ``batch_size`` when ``max_inflight_episodes`` is unset. Values below 1.0 intentionally cap in-flight episode capacity below ``batch_size``."""
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_rollouts`` from ``batch_size`` when ``max_inflight_rollouts`` is unset. Values below 1.0 intentionally cap in-flight rollout capacity below ``batch_size``."""
max_inflight_episodes: int | None = Field(
None, ge=1, validation_alias=AliasChoices("max_inflight_episodes", "max_inflight_rollouts")
)
"""Maximum number of episodes kept in-flight — one episode is one agent run at a time, whatever the env's agents are. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
max_inflight_rollouts: int | None = Field(None, ge=1)
"""Maximum number of rollouts kept in-flight. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
"""Output sequences returned per example during training."""
@@ -596,20 +554,29 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="before")
@classmethod
def _sampling_to_train(cls, data: Any) -> Any:
"""Allow [sampling] as shorthand for [train.sampling]."""
def _env_to_train(cls, data: Any) -> Any:
"""Allow [[env]] and [sampling] as shorthand for [train] with [[train.env]] and [train.sampling]."""
if not isinstance(data, dict):
return data
if "sampling" in data:
if "env" in data or "sampling" in data:
train = data.setdefault("train", {})
if isinstance(train, dict):
warnings.warn(
"'[orchestrator.sampling]' is deprecated, use '[orchestrator.train.sampling]' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("sampling", data.pop("sampling"))
if "env" in data:
warnings.warn(
"'[[orchestrator.env]]' is deprecated, use '[[orchestrator.train.env]]' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("env", data.pop("env"))
if "sampling" in data:
warnings.warn(
"'[orchestrator.sampling]' is deprecated, use '[orchestrator.train.sampling]' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("sampling", data.pop("sampling"))
return data
@model_validator(mode="after")
@@ -650,7 +617,7 @@ class OrchestratorConfig(BaseConfig):
def inherit_env_algorithms(self):
"""Envs without their own algorithm inherit the top-level one.
Declared before any validator that reads ``algo``."""
for env_cfg in self.train.source:
for env_cfg in self.train.env:
if env_cfg.algo is None:
env_cfg.algo = self.algo.model_copy(deep=True)
return self
@@ -658,7 +625,7 @@ class OrchestratorConfig(BaseConfig):
@property
def any_policy_sourced(self) -> bool:
"""True when at least one train env samples rollouts from the live policy."""
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.source)
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.env)
@model_validator(mode="after")
def validate_pool_size(self):
@@ -724,29 +691,29 @@ class OrchestratorConfig(BaseConfig):
if has_token_batch:
if self.oversampling_factor is not None:
raise ValueError("oversampling_factor can only be set when batch_size is set")
if self.max_inflight_episodes is None:
raise ValueError("max_inflight_episodes must be set when token_batch_size is set")
if self.max_inflight_rollouts is None:
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
else:
assert self.batch_size is not None
if self.batch_size % self.group_size != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
resolved_max_inflight_episodes = max(
resolved_max_inflight_rollouts = max(
self.group_size,
int(self.batch_size * oversampling_factor),
)
if self.max_inflight_episodes is not None and self.oversampling_factor is not None:
expected_max_inflight_episodes = resolved_max_inflight_episodes
if self.max_inflight_episodes != expected_max_inflight_episodes:
raise ValueError("max_inflight_episodes conflicts with oversampling_factor * batch_size")
if self.max_inflight_episodes is None:
self.max_inflight_episodes = resolved_max_inflight_episodes
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
expected_max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
if self.max_inflight_rollouts is None:
self.max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_episodes is not None and self.max_inflight_episodes < self.group_size:
raise ValueError("max_inflight_episodes must be at least the number of rollouts per example")
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.group_size:
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
for env_cfg in self.train.source:
for env_cfg in self.train.env:
if "group_size" not in env_cfg.model_fields_set:
env_cfg.group_size = self.group_size
@@ -769,7 +736,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_config(self):
"""Set vLLM sampling defaults + legacy env kwargs on each train env from top-level fields."""
for env in self.train.source:
for env in self.train.env:
# Policy-sourced rollouts hit our vLLM server; frozen-sourced
# rollouts may hit external OAI endpoints that reject these knobs.
assert env.algo is not None
@@ -779,6 +746,6 @@ class OrchestratorConfig(BaseConfig):
env.sampling.extra_body.setdefault("return_token_ids", True)
if env.is_legacy:
# v0 env: cap per-turn response tokens to the training budget (the legacy
# bridge applies legacy.extra_env_kwargs via env.set_kwargs).
env.legacy.extra_env_kwargs["max_seq_len"] = self.seq_len
# bridge applies extra_env_kwargs via env.set_kwargs).
env.extra_env_kwargs["max_seq_len"] = self.seq_len
return self
@@ -22,7 +22,6 @@ from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
SlurmConfig,
TransportConfig,
VLMConfig,
)
from prime_rl.configs.trainer import (
@@ -261,8 +260,6 @@ class RLConfig(BaseConfig):
weight_broadcast: SharedWeightBroadcastConfig | None = None
rollout_transport: TransportConfig | None = None
bench: bool = False
"""Benchmark mode. Sets trainer and orchestrator to benchmark mode and, when set, suffixes the W&B project with ``-bench``."""
@@ -422,28 +419,6 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def auto_setup_rollout_transport(self):
"""Resolve the shared ``rollout_transport`` from the sub-configs so the launcher can
gate multi-node ZMQ host injection on it (mirrors ``auto_setup_weight_broadcast``).
``rollout_transport`` may be set either as the shared block (propagated down to both
sub-configs by ``propagate_shared_fields``) or directly on
``trainer.rollout_transport`` / ``orchestrator.rollout_transport`` (the documented
fallback). Either way the shared field must reflect the resolved per-component
transport, otherwise the launcher would leave ZMQ trainers connecting to localhost.
"""
if self.trainer.rollout_transport.type != self.orchestrator.rollout_transport.type:
raise ValueError(
"trainer.rollout_transport.type "
f"({self.trainer.rollout_transport.type!r}) != orchestrator.rollout_transport.type "
f"({self.orchestrator.rollout_transport.type!r}); set the shared [rollout_transport] "
"block or make both sub-configs the same type."
)
if self.rollout_transport is None:
self.rollout_transport = self.trainer.rollout_transport
return self
@model_validator(mode="after")
def validate_eplb_requires_quantized_weight_transfer(self):
if self.inference is None or not self.inference.enable_eplb:
@@ -554,7 +529,7 @@ class RLConfig(BaseConfig):
(after InferenceConfig's own validators, which therefore miss it).
"""
if self.inference is not None and self.inference.enable_return_routed_experts:
router = self.inference.router
router = getattr(self.inference.deployment, "router", None)
if router is not None and router.type == "llm-d":
raise ValueError(
"The llm-d router backend does not support routed-expert return "
@@ -564,12 +539,6 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_multi_node_requires_router(self):
if self.deployment.type == "multi_node" and self.inference is not None and self.inference.router is None:
raise ValueError("Multi-node deployments require inference.router to front the per-rank engines.")
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
@@ -738,27 +707,27 @@ class RLConfig(BaseConfig):
def auto_setup_inference_client(self):
"""Auto-configure the orchestrator policy client from the inference server config.
When no train env samples from the policy (e.g. sft_distill), set
base_url. Policy-sourced algorithms rely on the ClientConfig default
(``["http://localhost:8000/v1"]``), which already matches the
auto-launched policy router at inference.server.port = 8000.
Direct single-node runs expose all local DP ranks behind one base URL,
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
runs expose a vllm-router URL instead; the router balances across
per-rank backend URLs and forwards request headers, so the orchestrator
must not inject a DP-rank header there. When no train env samples from
the policy (e.g. sft_distill), also set base_url — policy-sourced
algorithms rely on the ClientConfig default (``["http://localhost:8000/v1"]``)
which already matches the auto-launched policy vLLM at inference.server.port = 8000.
"""
if self.inference is None:
return self
client = self.orchestrator.model.client
if "dp_rank_count" not in client.model_fields_set:
if self.deployment.type == "multi_node":
client.dp_rank_count = 1
else:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if not self.orchestrator.any_policy_sourced and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
client.base_url = [f"http://{host}:{port}/v1"]
if (
self.deployment.type == "single_node"
and self.inference.router is not None
and "admin_base_url" not in client.model_fields_set
):
# Admin ops (pause/update_weights/resume) must bypass the router and hit
# the engine directly; multi-node runs get ADMIN_URLS from the sbatch.
host = self.inference.server.host or "localhost"
client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"]
return self
@model_validator(mode="after")
@@ -322,6 +322,8 @@ class SFTConfig(BaseConfig):
raise ValueError(
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
)
if self.model.cp > 1 and self.model.cp_style != "ulysses":
raise ValueError("VLM models require cp_style='ulysses' for context parallelism")
if self.data.micro_batch_size != 1:
raise ValueError("VLM SFT requires data.micro_batch_size = 1.")
if self.val is not None and self.val.data.micro_batch_size != 1:
@@ -141,6 +141,9 @@ class ClientConfig(BaseConfig):
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
dp_rank_count: int = Field(1, ge=1)
"""Number of data-parallel ranks behind each base URL. When > 1, each URL is expanded into ``dp_rank_count`` logical clients pinned via the ``X-data-parallel-rank`` header, so every request within a rollout hits the same DP engine and reuses KV cache. Auto-set from the inference config when using the RL entrypoint."""
admin_base_url: list[str] | None = None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in disaggregated P/D deployments where the router must not handle admin traffic."""
@@ -8,12 +8,12 @@ from prime_rl.configs.shared import (
BaseModelConfig,
EnvVars,
FileMonitorConfig,
FileSystemTransportConfig,
HeartbeatConfig,
MetricsServerConfig,
TrainerLogConfig,
TransportConfig,
WandbConfig,
ZMQTransportConfig,
)
from prime_rl.utils.config import BaseConfig
@@ -242,12 +242,6 @@ class ModelConfig(BaseModelConfig):
raise ValueError("VLM training requires model.impl='custom'")
return self
@model_validator(mode="after")
def vlm_cp_requires_ulysses(self):
if self.vlm is not None and self.cp > 1 and self.cp_style != "ulysses":
raise ValueError("VLM models require cp_style='ulysses' for context parallelism")
return self
@model_validator(mode="after")
def validate_cp(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
@@ -582,7 +576,7 @@ class TrainerConfig(BaseConfig):
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to broadcast updated weights from trainer to inference."""
rollout_transport: TransportConfig = ZMQTransportConfig()
rollout_transport: TransportConfig = FileSystemTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
log: TrainerLogConfig = TrainerLogConfig()
@@ -126,9 +126,6 @@ def propagate_shared_fields(data: Any) -> Any:
"inference.model.chat_template",
)
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport")
# Top-level scalars.
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
+10 -4
View File
@@ -18,7 +18,9 @@ dependencies = [
"torchaudio",
"torchdata>=0.11.0",
"transformers==5.6.2",
"vllm>=0.24.0",
"vllm==0.23.1rc1.dev1392+g910cc8543",
"flashinfer-python==0.6.15.post1",
"flashinfer-cubin==0.6.15.post1",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
@@ -33,7 +35,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.2.2.dev43",
"verifiers[harbor]>=0.2.1",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -157,6 +159,8 @@ requires-dist = [
[tool.uv.exclude-newer-package]
# we want latest vllm, remove next patch
vllm = false
flashinfer-python = false
flashinfer-cubin = false
tokenspeed-mla = false
fastokens = false
flash_attn_3 = false
@@ -200,9 +204,11 @@ vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://wheels.vllm.ai/910cc8543a6907c9cc87c417f8f2420969278bf5/vllm-0.23.1rc1.dev1392%2Bg910cc8543-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://wheels.vllm.ai/910cc8543a6907c9cc87c417f8f2420969278bf5/vllm-0.23.1rc1.dev1392%2Bg910cc8543-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
flashinfer-python = { url = "https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_python-0.6.15.post1-py3-none-any.whl" }
flashinfer-cubin = { url = "https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_cubin-0.6.15.post1-py3-none-any.whl" }
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
@@ -0,0 +1,28 @@
"""Apply the approved writable-scale fix to the pinned vLLM wheel in an image.
The experiment intentionally builds from the exact upstream nightly wheel. The
fix is tiny but not yet present in that immutable wheel, so fail closed unless
the source matches the reviewed change exactly.
"""
from pathlib import Path
import vllm
path = Path(vllm.__file__).parent / "model_executor/layers/quantization/utils/flashinfer_fp4_moe.py"
source = path.read_text()
replacements = {
"a13_scale.max().to(torch.float32).expand(num_experts)": "a13_scale.max().to(torch.float32).repeat(num_experts)",
"a2_scale.max().to(torch.float32).expand(num_experts)": "a2_scale.max().to(torch.float32).repeat(num_experts)",
}
for old, new in replacements.items():
old_count = source.count(old)
new_count = source.count(new)
if (old_count, new_count) == (2, 0):
source = source.replace(old, new)
elif (old_count, new_count) != (0, 2):
raise RuntimeError(f"Unexpected vLLM source in {path}: {old_count=} {new_count=}")
path.write_text(source)
print(f"Applied writable NVFP4 MoE scale fix to {path}")
+4 -11
View File
@@ -41,26 +41,19 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
**Lists** — TOML uses array of tables; later config files replace lists wholesale, so overlays must include the full desired list:
```toml
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[[orchestrator.eval.source]]
name = "reverse-text-eval"
env.taskset = { id = "reverse-text-v1", split = "test" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
```
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text-v1` or `--orchestrator.eval.source.0.env.taskset.id reverse-text-v1`.
CLI: `--orchestrator.train.env.0.env.taskset.id reverse-text-v1`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-env override: `[orchestrator.train.env.algo] type = "opd"` (the env assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
+1 -1
View File
@@ -57,7 +57,7 @@ Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
### llm-d router backend
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[inference.router] type = "llm-d"`). It needs three native binaries — install once:
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[...deployment.router] type = "llm-d"`). It needs three native binaries — install once:
```bash
bash scripts/install_llmd.sh # builds epp + pd-sidecar from a pinned llm-d-router commit (vendored Go), fetches envoy
+9 -9
View File
@@ -72,7 +72,7 @@ After a restart, verify all processes are back up and progress resumed before th
│ └── torchrun/ # per-rank stdout/stderr
├── inference/
│ ├── node_*.log # per-node (multi-node only)
│ └── router.log # the single global router (multi-node only; single-node logs it in inference.log)
│ └── router_0.log # vllm-router per replica (multi-node only)
└── envs/{train,eval}/{env_name}.log # one log file per env
```
@@ -93,13 +93,13 @@ All metrics print to the console log (and W&B when configured).
| Metric | Description |
|--------|-------------|
| `train/agg/effective/reward/mean` | mean training reward (per env: `train/<env>/effective/reward/mean`) |
| `train/agg/effective/num_total_tokens/mean` | avg tokens per rollout (also `num_input_tokens`, `num_output_tokens`) |
| `train/agg/effective/num_turns/mean` | avg turns per rollout (multi-turn only) |
| `train/agg/effective/is_truncated/mean` | fraction truncated |
| `train/agg/all/reward/mean` | mean training reward (per env: `train/<env>/all/reward/mean`) |
| `train/agg/all/num_total_tokens/mean` | avg tokens per rollout (also `num_input_tokens`, `num_output_tokens`) |
| `train/agg/all/num_turns/mean` | avg turns per rollout (multi-turn only) |
| `train/agg/all/is_truncated/mean` | fraction truncated |
| `train/agg/all/has_error/mean` | fraction errored (per-type under `train/agg/all/error/<type>`; also `dispatcher/errored/{train,eval}`) |
| `train/<env>/effective/metrics/<name>/mean` | env-specific metrics (e.g. pass rate) |
| `eval/<env>/effective/{avg@k,pass@k}` | eval scores when configured |
| `train/<env>/all/metrics/<name>/mean` | env-specific metrics (e.g. pass rate) |
| `eval/<env>/all/{avg@k,pass@k}` | eval scores when configured |
**Stability** — trainer log:
@@ -126,7 +126,7 @@ All metrics print to the console log (and W&B when configured).
For live vLLM stats, query Prometheus directly:
```bash
curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage" # engine port (8000 is the router)
curl -s http://localhost:8000/metrics | grep -E "num_requests|gpu_cache_usage"
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
```
@@ -154,7 +154,7 @@ jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
```
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
The binary batches consumed by the trainer still live at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
### Common failure modes
+1 -1
View File
@@ -57,7 +57,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
## `inference` — vLLM server
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly.
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly.
```bash
uv run inference --model.name Qwen/Qwen3-0.6B
+16 -78
View File
@@ -1,10 +1,8 @@
import json
import os
import signal
import subprocess
import sys
from pathlib import Path
from threading import Event, Thread
from typing import Any
import tomli_w
@@ -13,12 +11,7 @@ from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli, to_toml_dict
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
cleanup_processes,
set_proc_title,
)
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, DEFAULT_INFERENCE_ENV_VARS, set_proc_title
INFERENCE_TOML = "inference.toml"
INFERENCE_SBATCH = "inference.sbatch"
@@ -35,21 +28,12 @@ def vllm_overrides_fragment(overrides: dict[str, Any]) -> str:
return ", " + json.dumps(overrides)[1:-1].replace('"', '\\"')
def write_config(
config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None, engine_only: bool = False
) -> Path:
"""Write resolved config to disk.
With ``engine_only``, the router is nulled so per-rank processes run bare
engines — the sbatch script starts the single global router.
"""
def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None) -> Path:
"""Write resolved config to disk."""
output_dir.mkdir(parents=True, exist_ok=True)
config_path = output_dir / INFERENCE_TOML
toml_dict = to_toml_dict(config, exclude=exclude)
if engine_only:
toml_dict["router"] = "None"
with open(config_path, "wb") as f:
tomli_w.dump(toml_dict, f)
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
return config_path
@@ -77,8 +61,6 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
dp_per_node=dp_per_node,
num_nodes=getattr(config.deployment, "num_nodes", 1),
port=config.server.port,
router=config.router,
router_port=config.server.port,
is_disaggregated=is_disaggregated,
kv_offload=offload is not None,
kv_offload_mooncake=is_mooncake,
@@ -100,6 +82,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
num_decode_replicas=config.deployment.num_decode_replicas,
prefill_port=config.deployment.prefill_port,
decode_port=config.deployment.decode_port,
router=config.deployment.router,
data_parallel_rpc_port=config.data_parallel_rpc_port,
use_deep_gemm=config.use_deep_gemm,
prefill_env_vars=config.deployment.prefill_env_vars,
@@ -109,7 +92,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
)
elif is_multi_node:
template_vars.update(
backend_port=config.backend_port,
router=config.deployment.router,
backend_port=config.deployment.backend_port,
data_parallel_rpc_port=config.data_parallel_rpc_port,
enable_expert_parallel=config.enable_expert_parallel,
infer_nodes_per_replica=config.deployment.num_nodes,
@@ -128,9 +112,12 @@ def inference_slurm(config: InferenceConfig):
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
is_multi_node = config.deployment.type in ("multi_node", "disaggregated")
exclude = {"deployment", "slurm", "dry_run"} if is_multi_node else {"slurm", "dry_run"}
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
exclude = (
{"deployment", "slurm", "dry_run"}
if config.deployment.type in ("multi_node", "disaggregated")
else {"slurm", "dry_run"}
)
config_path = write_config(config, config_dir, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
script_path = config.output_dir / INFERENCE_SBATCH
@@ -154,35 +141,8 @@ def inference_slurm(config: InferenceConfig):
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def start_router(config: InferenceConfig) -> subprocess.Popen:
"""Start the vllm-router on ``server.port``, fronting the local engine at ``backend_port``."""
assert config.router is not None and config.router.type == "vllm-router"
host = config.server.host
worker_host = "localhost" if host in (None, "0.0.0.0") else host
cmd = [
"vllm-router",
"--policy",
config.router.policy,
"--host",
host or "0.0.0.0",
"--port",
str(config.server.port),
"--worker-urls",
f"http://{worker_host}:{config.backend_port}",
"--intra-node-data-parallel-size",
str(config.data_parallel_size_local or config.parallel.dp),
"--request-id-headers",
"x-session-id",
"--worker-startup-timeout-secs",
"4200",
"--prometheus-port",
str(config.server.port + 21000),
]
return subprocess.Popen(cmd)
def inference_local(config: InferenceConfig):
"""Run inference locally: a router on ``server.port`` fronting the engine on ``backend_port``."""
"""Run inference locally."""
from prime_rl.inference.server import setup_vllm_env
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
@@ -193,6 +153,7 @@ def inference_local(config: InferenceConfig):
host = config.server.host or "0.0.0.0"
port = config.server.port
logger.info(f"Starting inference on http://{host}:{port}/v1\n")
# Apply the inference env (defaults + [inference.env_vars]) in-process so a standalone
# `uv run inference` gets the same environment the rl/SLURM launchers inject into the
@@ -201,32 +162,9 @@ def inference_local(config: InferenceConfig):
setup_vllm_env(config)
router_process: subprocess.Popen | None = None
router_stopping = Event()
if config.router is not None:
logger.info(f"Starting router on http://{host}:{port}/v1 (engine on port {config.backend_port})\n")
router_process = start_router(config)
# The router owns the client-facing port; the engine moves behind it.
config.server.port = config.backend_port
def watch_router():
router_process.wait()
if not router_stopping.is_set():
logger.error(f"Router exited with code {router_process.returncode} - shutting down")
os.kill(os.getpid(), signal.SIGTERM)
Thread(target=watch_router, daemon=True).start()
else:
logger.info(f"Starting inference on http://{host}:{port}/v1\n")
from prime_rl.inference.vllm.server import server # pyright: ignore
try:
server(config, vllm_extra=config.vllm_extra)
finally:
if router_process is not None:
router_stopping.set()
cleanup_processes([router_process])
server(config, vllm_extra=config.vllm_extra)
def inference(config: InferenceConfig):
+10 -22
View File
@@ -73,12 +73,8 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
if config.inference is not None:
# Exclude launcher-only fields that are not needed by the vLLM server
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
inference_dict = to_toml_dict(config.inference, exclude=exclude_inference)
if config.deployment.type == "multi_node":
# Per-rank processes run bare engines; the sbatch starts the single global router.
inference_dict["router"] = "None"
with open(output_dir / INFERENCE_TOML, "wb") as f:
tomli_w.dump(inference_dict, f)
tomli_w.dump(to_toml_dict(config.inference, exclude=exclude_inference), f)
def rl_local(config: RLConfig):
@@ -205,9 +201,9 @@ def rl_local(config: RLConfig):
)
frozen_endpoints: list[str] = []
for env in config.orchestrator.train.source:
for env in config.orchestrator.train.env:
algo = env.algo
assert algo is not None, "TrainSourceConfig.algo must be resolved before launch (inherit_env_algorithms)"
assert algo is not None, "TrainEnvConfig.algo must be resolved before launch (inherit_env_algorithms)"
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
if isinstance(ref, FrozenModelConfig):
frozen_endpoints.append(f"{ref.name} ({', '.join(ref.base_url)})")
@@ -418,8 +414,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
num_prefill_replicas=infer_deploy.num_prefill_replicas,
num_decode_replicas=infer_deploy.num_decode_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router=config.inference.router,
router_port=config.inference.server.port,
router=infer_deploy.router,
prefill_port=infer_deploy.prefill_port,
decode_port=infer_deploy.decode_port,
inference_tp=config.inference.parallel.tp,
@@ -435,7 +430,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
)
@@ -451,17 +445,15 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
num_infer_replicas=config.deployment.num_infer_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router=config.inference.router if config.inference else VllmRouterConfig(),
router_port=config.inference.server.port if config.inference else 8000,
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
backend_port=config.inference.backend_port if config.inference else 8100,
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
inference_tp=config.inference.parallel.tp if config.inference else 1,
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
trainer_env_vars=trainer_env_vars,
@@ -487,10 +479,8 @@ def rl_slurm(config: RLConfig):
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean_output_dir"})
logger.info(f"Wrote config to {config_dir / RL_TOML}")
train_env_names = [env.resolved_name for env in config.orchestrator.train.source]
eval_env_names = (
[source.resolved_name for source in config.orchestrator.eval.source] if config.orchestrator.eval else []
)
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
log_message = format_log_message(
log_dir=log_dir,
@@ -504,10 +494,8 @@ def rl_slurm(config: RLConfig):
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
train_env_names = [env.resolved_name for env in config.orchestrator.train.source]
eval_env_names = (
[source.resolved_name for source in config.orchestrator.eval.source] if config.orchestrator.eval else []
)
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
has_infer = config.deployment.infer_nodes_per_replica > 0
log_message = format_log_message(
@@ -1,7 +1,7 @@
"""Prime-RL extensions to vLLM's `/inference/v1/generate` handler.
vLLM 0.22 ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.serve.disagg.serving.ServingTokens`` that already covers
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that already covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
defaulting. We subclass it for the bits still missing from the upstream handler:
@@ -37,12 +37,12 @@ from vllm.entrypoints.openai.engine.protocol import (
RequestResponseMetadata,
UsageInfo,
)
from vllm.entrypoints.serve.disagg.protocol import (
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
GenerateResponse,
GenerateResponseChoice,
)
from vllm.entrypoints.serve.disagg.serving import ServingTokens
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
from vllm.outputs import RequestOutput
from vllm.sampling_params import RequestOutputKind, SamplingParams
@@ -200,7 +200,7 @@ class PrimeRlServingTokens(ServingTokens):
# Build the engine input — features-aware (MM) or text-only fallback.
# Identical to upstream so we keep tracking it.
if features := request.features:
from vllm.entrypoints.serve.disagg.mm_serde import decode_mm_kwargs_item
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
from vllm.inputs import mm_input
from vllm.multimodal.inputs import (
MultiModalKwargsItem,
@@ -226,7 +226,7 @@ class PrimeRlServingTokens(ServingTokens):
cache_salt=request.cache_salt,
)
else:
(engine_input,) = await self.openai_serving_render.preprocess_completion(
(engine_input,) = await self.online_renderer.preprocess_completion(
request,
prompt_input=request.token_ids,
prompt_embeds=None,
+1 -4
View File
@@ -5,7 +5,7 @@ is — a bundle of sampling and the per-token training signal. This package
turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.sampler.Sampler`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``, ``opd``,
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``opd``,
``opsd``, ``sft``) — each named class owns its scoring hooks
(``score_rollout`` / ``score_group``) and declares what it needs (loss
component, a "teacher", ...). One instance per env, built by
@@ -34,7 +34,6 @@ from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.orchestrator.algo.max_rl import MaxRLAlgorithm
from prime_rl.orchestrator.algo.opd import OPDAlgorithm
from prime_rl.orchestrator.algo.opsd import OPSDAlgorithm
from prime_rl.orchestrator.algo.rae import RAEAlgorithm
from prime_rl.orchestrator.algo.routing import stamp_advantages, stamp_loss_routing
from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm
from prime_rl.orchestrator.types import Rollout
@@ -49,7 +48,6 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
"grpo": GRPOAlgorithm,
"echo": EchoAlgorithm,
"max_rl": MaxRLAlgorithm,
"rae": RAEAlgorithm,
"opd": OPDAlgorithm,
"opsd": OPSDAlgorithm,
"sft": SFTDistillAlgorithm,
@@ -74,7 +72,6 @@ __all__ = [
"MaxRLAlgorithm",
"OPDAlgorithm",
"OPSDAlgorithm",
"RAEAlgorithm",
"Rollout",
"SFTDistillAlgorithm",
"build_algorithm",
-41
View File
@@ -1,41 +0,0 @@
from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import RAEAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
class RAEAlgorithm(Algorithm):
"""Role-conditioned advantage estimation (SPIRAL, arXiv:2506.24119):
credit = reward minus a per-agent EMA baseline of that agent's rewards.
The advantage estimator for multi-agent self-play envs (kuhn-poker-v1 and
friends): in a zero-sum game the group mean is ~0 whatever the policy does,
and centering all agents against it mixes their opposite reward scales — a
structural first-mover edge would read as permanent credit for one agent.
A per-agent baseline tracks each agent's own expected reward instead, so
credit measures improvement over that agent's usual result. The instance is
per-env, so baselines are keyed per (env, agent) — the paper's per
(game, role). A single-agent env degrades to REINFORCE with an EMA baseline.
Each trace is scored against the baseline *before* its reward updates it
(the reference implementation's unbiased order). Baselines start at 0 and
live in orchestrator memory: a restart re-warms them over ~1/(1 − decay)
traces per agent."""
def __init__(self, config: RAEAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
self.decay = config.decay
self.baselines: dict[str | None, float] = defaultdict(float)
async def score_group(self, group: list[Rollout]) -> None:
for rollout in group:
baseline = self.baselines[rollout.agent_name]
rollout.assign_advantages(rollout.reward - baseline)
self.baselines[rollout.agent_name] = self.decay * baseline + (1.0 - self.decay) * rollout.reward
+4 -6
View File
@@ -1,9 +1,7 @@
"""RolloutDispatcher: schedules rollouts under a shared permit counter.
- Capacity (``max_inflight_episodes``) is shared across train + eval. One permit is
one episode: for a v1 env one ``run`` request, and a group-scoring task that runs
N rollouts in one call reserves N permits (each bridged v0 rollout is its own
single-agent episode).
- Capacity (``max_inflight_rollouts``) is shared across train + eval.
A group-scoring task that runs N rollouts in one call reserves N permits.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Emit-everything invariant: every dispatched env-rollout eventually reaches
``out_q`` exactly once, as one episode (a ``list[Rollout]``). Failures
@@ -131,7 +129,7 @@ class RolloutDispatcher:
eval_source: EvalSource | None,
policy_pool: InferencePool,
policy: Policy,
max_inflight_episodes: int,
max_inflight_rollouts: int,
tasks_per_minute: float | None,
max_off_policy_steps: int,
) -> None:
@@ -145,7 +143,7 @@ class RolloutDispatcher:
self.eval_source = eval_source
self.max_off_policy_steps = max_off_policy_steps
self.max_inflight = max_inflight_episodes
self.max_inflight = max_inflight_rollouts
self.inflight_permits = 0
self.rate_limiter: AsyncLimiter | None = (
AsyncLimiter(tasks_per_minute, time_period=60) if tasks_per_minute else None
@@ -13,18 +13,18 @@ from prime_rl.utils.utils import clean_exit
@clean_exit
def run_server(config: EnvServerConfig):
env = config.env
address = env.serve.address or "tcp://127.0.0.1:5000"
# The env's ``serve.pool`` (static or elastic) sizes the server; a v0/legacy env runs through
address = env.address or "tcp://127.0.0.1:5000"
# The env's ``pool`` (static or elastic) sizes the server; a v0/legacy env runs through
# the bridge, a v1 env is a native env block — both speak the same serve protocol,
# so the orchestrator is agnostic. serve_env applies the logging setup in this process
# and in every spawned worker.
server_kwargs = (
{"env_id": env.env_id, "env_args": env.legacy.args, "extra_env_kwargs": env.legacy.extra_env_kwargs}
{"env_id": env.env_id, "env_args": env.args, "extra_env_kwargs": env.extra_env_kwargs}
if env.is_legacy
else {"config_data": env_config_data(env.env), "max_concurrent": env.serve.max_concurrent}
else {"config_data": env_config_data(env.env)}
)
serve_env(
**pool_serve_kwargs(env.serve.pool),
**pool_serve_kwargs(env.pool),
legacy=env.is_legacy,
address=address,
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
+15 -21
View File
@@ -1,7 +1,7 @@
"""Env wrappers over a v1 env server.
Each ``Env`` owns a v1 ``EnvServer`` (spawned as a child process, or an
external one pinned by ``config.serve.address``) and an ``EnvClient`` to drive it. The
external one given by ``config.address``) and an ``EnvClient`` to drive it. The
orchestrator never *runs* an environment — the agents and their runtimes live only
in the server — but it does own the *taskset*: a v1 env's tasks are loaded here,
once, and each dispatched env-rollout ships its task's data on the request
@@ -34,7 +34,7 @@ from typing import Generic, TypeVar
import verifiers.v1 as vf
from verifiers.v1.serve import EnvClient, env_config_data
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig, TrainEnvConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.sampler import Sampler
from prime_rl.orchestrator.types import Rollout
@@ -112,8 +112,8 @@ class Env:
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
"""Spawn the env server (if needed), connect, and load the taskset client-side
(legacy instead asks the server for ``info`` — its dataset is server-side)."""
external = self.config.serve.address is not None
address = self.config.serve.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
external = self.config.address is not None
address = self.config.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
get_logger().debug(f"Connecting {self.name} to env server {address}")
self._env_client = EnvClient(address=address)
# A spawned server already reported its address *after* binding, so it's up. An
@@ -152,18 +152,12 @@ class Env:
dict(
legacy=True,
env_id=self.config.env_id,
env_args=self.config.legacy.args,
extra_env_kwargs=self.config.legacy.extra_env_kwargs,
env_args=self.config.args,
extra_env_kwargs=self.config.extra_env_kwargs,
)
if self.config.is_legacy
# Picklable dict — the narrowed config class doesn't survive the spawn.
# ``max_concurrent`` bounds this worker's episodes in flight — usually unset,
# since the dispatcher's ``max_inflight_episodes`` is the run's bound.
else dict(
legacy=False,
config_data=env_config_data(self.config.env),
max_concurrent=self.config.serve.max_concurrent,
)
else dict(legacy=False, config_data=env_config_data(self.config.env))
)
process = ctx.Process(
target=_run_env_server,
@@ -171,7 +165,7 @@ class Env:
log_file=str(log_file),
log_level=log_level,
json_logging=json_logging,
**vf.pool_serve_kwargs(self.config.serve.pool),
**vf.pool_serve_kwargs(self.config.pool),
address="tcp://127.0.0.1:0",
address_queue=address_queue,
**server_kwargs,
@@ -252,9 +246,9 @@ class Env:
class TrainEnv(Env):
config: TrainSourceConfig
config: TrainEnvConfig
def __init__(self, config: TrainSourceConfig, sampler: Sampler, algorithm: Algorithm):
def __init__(self, config: TrainEnvConfig, sampler: Sampler, algorithm: Algorithm):
super().__init__(config)
self.sampler = sampler
self.algorithm = algorithm
@@ -262,9 +256,9 @@ class TrainEnv(Env):
class EvalEnv(Env):
config: EvalSourceConfig
config: EvalEnvConfig
def __init__(self, config: EvalSourceConfig):
def __init__(self, config: EvalEnvConfig):
super().__init__(config)
self.sampling_args = config.sampling.to_sampling_args()
self.examples: list[dict] = []
@@ -339,10 +333,10 @@ class TrainEnvs(Envs[TrainEnv]):
:class:`Sampler` and runtime :class:`Algorithm`, built from the env's
resolved algorithm config."""
def __init__(self, configs: Sequence[TrainSourceConfig], *, policy_pool, renderer_config=None):
def __init__(self, configs: Sequence[TrainEnvConfig], *, policy_pool, renderer_config=None):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
assert config.algo is not None, "TrainEnvConfig.algo must be resolved before env construction"
env = TrainEnv(
config,
Sampler(config.algo.sampling, policy_pool, renderer_config),
@@ -354,7 +348,7 @@ class TrainEnvs(Envs[TrainEnv]):
class EvalEnvs(Envs[EvalEnv]):
"""Collection of evaluation environments."""
def __init__(self, configs: Sequence[EvalSourceConfig]):
def __init__(self, configs: Sequence[EvalEnvConfig]):
self._envs: dict[str, EvalEnv] = {}
for config in configs:
env = EvalEnv(config)
+6 -11
View File
@@ -12,7 +12,7 @@ is flat over the rollout list except the solve rates, which group by ``group_id`
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Iterator, Literal
from typing import TYPE_CHECKING, Iterator, Literal
from prime_rl.orchestrator.utils import compute_pass_metrics
@@ -134,20 +134,16 @@ class TimingMetrics(StatGroup):
class CustomMetrics(StatGroup):
"""Per-key ``Stat``s over a dynamic per-rollout dict attribute (env ``@metric``s or reward
components), each averaged over the rollouts that report the key. ``value`` extracts the
float from each entry (rewards are ``vf.Reward`` records; metrics are plain floats)."""
components), each averaged over the rollouts that report the key."""
def __init__(self, rollouts: list[Rollout], attr: str, value: Callable[[Any], float] = float) -> None:
def __init__(self, rollouts: list[Rollout], attr: str) -> None:
super().__init__(rollouts)
self.attr = attr
self.value = value
def stats(self) -> dict[str, Stat]:
names = sorted({name for r in self.rollouts for name in getattr(r, self.attr)})
return {
name: Stat(
[self.value(getattr(r, self.attr)[name]) for r in self.rollouts if name in getattr(r, self.attr)]
)
name: Stat([getattr(r, self.attr)[name] for r in self.rollouts if name in getattr(r, self.attr)])
for name in names
}
@@ -192,9 +188,8 @@ class RolloutMetrics:
@property
def rewards(self) -> CustomMetrics:
"""Per-component reward breakdown, keyed by name (each entry's weighted ``value``,
summed into the scalar ``reward``)."""
return CustomMetrics(self.rollouts, "rewards", value=lambda reward: reward.value)
"""Per-component reward breakdown, keyed by name (summed into the scalar ``reward``)."""
return CustomMetrics(self.rollouts, "rewards")
# Boolean rate metrics (0/1 distributions — ``.mean()`` is the rate)
@property
+21 -55
View File
@@ -156,7 +156,7 @@ class Orchestrator:
# Route the in-process v1 library logging through our handler. The
# env server runs in a child process, so its logging is separate.
intercept_vf_logging(logger="verifiers.v1", level="WARN")
algorithms = sorted({env.algo.type for env in config.train.source if env.algo is not None})
algorithms = sorted({env.algo.type for env in config.train.env if env.algo is not None})
get_logger().info(f"Starting orchestrator (algorithm: {', '.join(algorithms)})")
if config.bench:
@@ -176,8 +176,6 @@ class Orchestrator:
self.eval_triggered_at = {}
self.consecutive_empty_batches = 0
self.gate_closed_at = None
# Pulsed by the version hooks so a held ship can re-check ``policy.version``
self.version_advanced = asyncio.Event()
self.wait_for_policy_time = 0.0
self.component_tasks = []
@@ -238,8 +236,8 @@ class Orchestrator:
tokenizer=self.tokenizer,
run_config=config,
keep_full_history=config.bench,
train_env_names=[env.resolved_name for env in config.train.source],
eval_env_names=[source.resolved_name for source in config.eval.source] if config.eval is not None else [],
train_env_names=[env.resolved_name for env in config.train.env],
eval_env_names=[env.resolved_name for env in config.eval.env] if config.eval is not None else [],
)
if config.heartbeat is not None:
@@ -256,7 +254,7 @@ class Orchestrator:
get_logger().info("Loading training environments")
self.train_envs = TrainEnvs(
config.train.source, policy_pool=self.policy_inference, renderer_config=config.renderer
config.train.env, policy_pool=self.policy_inference, renderer_config=config.renderer
)
get_logger().debug(
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
@@ -270,7 +268,7 @@ class Orchestrator:
if config.eval is not None:
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source)
self.eval_envs = EvalEnvs(config.eval.env)
get_logger().debug(f"Loaded {len(self.eval_envs)} eval environment(s) ({', '.join(self.eval_envs.names)})")
await self.eval_envs.start(
log_dir=get_log_dir(config.output_dir.parent) / "envs" / "eval",
@@ -391,7 +389,7 @@ class Orchestrator:
else None
)
assert config.max_inflight_episodes is not None, "max_inflight_episodes must be resolved before dispatcher init"
assert config.max_inflight_rollouts is not None, "max_inflight_rollouts must be resolved before dispatcher init"
log_interval = config.log.interval
wandb_enabled = config.wandb is not None
self.dispatcher = RolloutDispatcher(
@@ -401,7 +399,7 @@ class Orchestrator:
eval_source=self.eval_source,
policy_pool=self.policy_inference,
policy=self.policy,
max_inflight_episodes=config.max_inflight_episodes,
max_inflight_rollouts=config.max_inflight_rollouts,
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=config.max_off_policy_steps,
)
@@ -597,47 +595,18 @@ class Orchestrator:
)
return
self.consecutive_empty_batches = 0
effective = batch.rollouts.effective
n_trainable = sum(1 for r in effective if r.is_trainable)
if effective and n_trainable / len(effective) <= 0.1:
n_trainable = sum(1 for r in batch.rollouts if r.is_trainable)
if n_trainable / len(batch.rollouts) <= 0.1:
get_logger().warning(
f"Only {n_trainable}/{len(effective)} effective rollouts are trainable "
f"({n_trainable / len(effective):.1%}) — consider reviewing task difficulty / filter config"
f"Only {n_trainable}/{len(batch.rollouts)} generated rollouts are trainable "
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
)
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
# Without this, fast envs fill batches from buffered rollouts, the
# orchestrator finishes early, and its teardown strands the trainer inside
# an in-memory broadcast handshake that needs the live weight watcher.
# Always satisfiable: the trainer skips only the final TARGET_LAG+1
# in-memory broadcasts. Bench runs have no trainer, so they ship freely.
required_version = step - 1 - TARGET_LAG
if not config.bench and self.policy.version < required_version:
get_logger().info(
f"Holding batch {step} until the trainer publishes policy v{required_version} "
f"(currently v{self.policy.version})"
)
hold_start = time.perf_counter()
while True:
self.version_advanced.clear()
if self.policy.version >= required_version:
break
await self.version_advanced.wait()
self.wait_for_policy_time += time.perf_counter() - hold_start
# Stamp each rollout's true staleness: batch ``step`` trains on policy
# v{step-1}, so a rollout generated from v{k} is (step-1)-k versions
# off-policy — queue time included, unlike the dispatcher's in-flight
# counter, which only sees weight updates during generation. Frozen-
# sourced rollouts stay 0 (their sampler doesn't follow the policy).
for r in batch.rollouts:
if self.train_envs.get(r.env_name).sampler.samples_from_live_policy:
r.off_policy_steps = (step - 1) - r.policy_version
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
# at ship time; the full arrival window already streamed into ``all`` on arrival.
# to_record drops the per-node training tensors — they're for training, not the rollout
# record, and can't round-trip json (raw numpy bytes).
effective = batch.rollouts.effective
records = [r.to_record() for r in effective]
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
@@ -805,19 +774,19 @@ class Orchestrator:
def log_train_batch(self, batch: TrainBatch, *, step: int, step_time: float) -> None:
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
``Error`` is the sink-level rate (errored arrivals / total arrivals, over the full window);
the quality metrics are over the effective (clean, trained-on) subset, as is ``Trainable``."""
the quality metrics are over the effective (clean, trained-on) subset; ``Trainable`` is
relative to all generated rollouts."""
rollouts = batch.rollouts
effective = rollouts.effective
eff = effective.metrics
n_generated = len(rollouts)
n_effective = len(effective)
n_trainable = sum(1 for r in effective if r.is_trainable)
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
n_trainable = sum(1 for r in rollouts if r.is_trainable)
trainable_rate = (n_trainable / n_generated) if n_generated else 0.0
max_off_policy = max((r.off_policy_steps for r in effective), default=0)
head = (
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
f"Trainable {n_trainable}/{n_generated} ({trainable_rate:.1%}) | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max_off_policy} | "
f"Error {rollouts.metrics.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
@@ -875,15 +844,15 @@ class Orchestrator:
metrics["step"] = float(batch.step)
self.monitor.log(metrics, step=batch.step)
# Success line — quality metrics over the effective set, error rate over the full returned
# cohort. ``Stat.mean()`` is 0.0 for an empty set.
# Success line — reward / turns / truncation over the effective set, error rate + branches
# over the full returned cohort. ``Stat.mean()`` is 0.0 for an empty set.
eff, full = effective.metrics, rollouts.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {full.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
)
@@ -936,14 +905,11 @@ class Orchestrator:
gate.set()
async def on_version_pending(self, step: int) -> None:
"""``VersionObserver`` hook, fired at publish confirmation (pre-apply):
``policy.version`` already carries the new version, so wake a held ship."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
self.version_advanced.set()
async def on_new_version(self, step: int) -> None:
"""``VersionObserver`` hook: the weight update completed;
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
+1 -1
View File
@@ -146,7 +146,7 @@ class TrainBatch:
finalized in that span (errored + filtered included; rollouts of still-incomplete groups wait
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
trainer-bound payload (the shipped cohort's post-filter survivors) — an empty list means nothing
ships, which would stall the trainer. Trainable counts derive from ``rollouts.effective``
ships, which would stall the trainer. Trainable counts derive from ``rollouts``
(``r.is_trainable``) and token totals from ``samples``, so neither is carried as a field."""
rollouts: TrainRollouts

Some files were not shown because too many files have changed in this diff Show More