Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
adfbc6003d | ||
|
|
94a93203cf | ||
|
|
f0d27513a4 | ||
|
|
684f0d0afe | ||
|
|
559b44772e | ||
|
|
1e756307ae | ||
|
|
2441fd5142 | ||
|
|
967fbf25ef | ||
|
|
e6d2b3f252 | ||
|
|
13553dd88a | ||
|
|
d37b57ba6e | ||
|
|
802a364e6a | ||
|
|
9b9de2f1bc | ||
|
|
fe38722e8b | ||
|
|
c69f5b0389 | ||
|
|
29e4222767 | ||
|
|
e3e3a87dea | ||
|
|
65e4b915ba | ||
|
|
a686a90405 | ||
|
|
991b925e6e |
Symlink
+1
@@ -0,0 +1 @@
|
||||
../skills
|
||||
@@ -0,0 +1,155 @@
|
||||
name: Build Kernels
|
||||
|
||||
# Builds the `prime-kernels` wheel for x86_64 and aarch64 from the deps/prime-kernels submodule.
|
||||
# Runs on every bump of that submodule to catch build breakage, and with `release_tag` to
|
||||
# attach the wheels to a GitHub release — which is how they are consumed (see the `kernels`
|
||||
# skill).
|
||||
#
|
||||
# `tag-and-release.yaml` calls this for every release, before it promotes the draft, so a
|
||||
# published release always carries the wheels its `[tool.uv.sources]` pin can point at.
|
||||
# `workflow_dispatch` does the same by hand, for backfilling an already published release.
|
||||
#
|
||||
# No GPU is needed: nvcc cross compiles for the architectures kernels.toml declares.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "deps/prime-kernels"
|
||||
- ".gitmodules"
|
||||
- ".github/workflows/build_kernels.yaml"
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "deps/prime-kernels"
|
||||
- ".gitmodules"
|
||||
- ".github/workflows/build_kernels.yaml"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: "Existing release tag to attach the wheels to (e.g. v0.7.0). Empty = artifacts only."
|
||||
required: false
|
||||
type: string
|
||||
ref:
|
||||
description: "Ref to build the kernels from. Empty = the ref the workflow was started on."
|
||||
required: false
|
||||
type: string
|
||||
workflow_call:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: "Release tag to attach the wheels to. The release may still be a draft."
|
||||
required: false
|
||||
type: string
|
||||
ref:
|
||||
description: "Ref to build the kernels from. Empty = the caller's ref."
|
||||
required: false
|
||||
type: string
|
||||
|
||||
env:
|
||||
# Keep in sync with the CUDA the prime-rl image is built against (Dockerfile.cuda);
|
||||
# the job container image below must be edited alongside it (no env context there).
|
||||
CUDA_TAG: cu128
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build wheel (${{ matrix.arch }})
|
||||
# Uploading the wheels to a release needs write; on workflow_call the caller
|
||||
# must grant it too (tag-and-release.yaml does).
|
||||
permissions:
|
||||
contents: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: image-builder
|
||||
arch: x86_64
|
||||
- runner: image-builder-arm-2204
|
||||
arch: aarch64
|
||||
runs-on: ${{ matrix.runner }}
|
||||
container: nvidia/cuda:12.8.1-devel-ubuntu24.04
|
||||
steps:
|
||||
- name: Install build tooling
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends git curl ca-certificates build-essential gh
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: false
|
||||
ref: ${{ inputs.ref }}
|
||||
|
||||
# deps/prime-kernels is the prime-kernels submodule and carries every kernel's sources.
|
||||
- name: Init the kernels submodule
|
||||
run: |
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
git submodule update --init -- deps/prime-kernels
|
||||
|
||||
- name: Install uv
|
||||
run: |
|
||||
curl -LsSf https://astral.sh/uv/install.sh | env INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR=/usr/local/bin sh
|
||||
uv --version
|
||||
|
||||
# The wheel only imports under the exact torch it was compiled against, so build
|
||||
# against the torch prime-rl resolves rather than whatever is newest today.
|
||||
- name: Create build environment
|
||||
env:
|
||||
UV_TORCH_BACKEND: ${{ env.CUDA_TAG }}
|
||||
run: |
|
||||
TORCH_PIN=$(grep -A1 '^name = "torch"$' uv.lock | sed -n 's/^version = "\([^"+]*\).*"$/\1/p' | head -n1)
|
||||
if [ -z "$TORCH_PIN" ]; then
|
||||
echo "Could not read torch's version from uv.lock" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Building against torch==$TORCH_PIN"
|
||||
uv venv --python 3.12 /tmp/build-env
|
||||
VIRTUAL_ENV=/tmp/build-env uv pip install "torch==$TORCH_PIN" setuptools wheel ninja
|
||||
|
||||
# torch C++ extensions are bound to the torch and CUDA they were compiled against, so
|
||||
# the wheel carries both in its local version.
|
||||
- name: Stamp ABI into the version
|
||||
run: |
|
||||
TORCH_VERSION=$(/tmp/build-env/bin/python -c 'import torch; print(torch.__version__.split("+")[0])')
|
||||
LOCAL="${CUDA_TAG}torch${TORCH_VERSION}"
|
||||
sed -i -E "s/^version = \"([^\"]+)\"$/version = \"\1+${LOCAL}\"/" deps/prime-kernels/pyproject.toml
|
||||
grep '^version' deps/prime-kernels/pyproject.toml
|
||||
|
||||
- name: Build wheel
|
||||
env:
|
||||
VIRTUAL_ENV: /tmp/build-env
|
||||
CUDA_HOME: /usr/local/cuda
|
||||
PRIME_KERNELS_REQUIRE: "1"
|
||||
MAX_JOBS: "8"
|
||||
run: uv build --wheel --no-build-isolation --out-dir dist deps/prime-kernels
|
||||
|
||||
- name: Inspect wheel
|
||||
run: |
|
||||
ls -lh dist/
|
||||
/tmp/build-env/bin/python - <<'PY'
|
||||
import pathlib, zipfile
|
||||
wheel = next(pathlib.Path("dist").glob("*.whl"))
|
||||
extensions = [n for n in zipfile.ZipFile(wheel).namelist() if n.endswith(".so")]
|
||||
assert extensions, f"{wheel.name} contains no compiled kernels"
|
||||
print(wheel.name, *extensions, sep="\n ")
|
||||
PY
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: prime-kernels-${{ matrix.arch }}
|
||||
path: dist/*.whl
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Attach to release
|
||||
if: inputs.release_tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
# gh must not resolve the repo from the checkout: inside the container the
|
||||
# workspace is owned by another uid, which git rejects as dubious ownership.
|
||||
GH_REPO: ${{ github.repository }}
|
||||
TAG: ${{ inputs.release_tag }}
|
||||
run: |
|
||||
gh release upload "$TAG" dist/*.whl --clobber
|
||||
# The `[tool.uv.sources]` pin has to name the wheel exactly, ABI suffix and all.
|
||||
WHEEL=$(basename dist/*.whl)
|
||||
URL="https://github.com/${GITHUB_REPOSITORY}/releases/download/${TAG}/${WHEEL}"
|
||||
echo "\`{ url = \"$URL\", marker = \"platform_machine == '${{ matrix.arch }}'\" },\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -113,9 +113,22 @@ jobs:
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
release-from-auto-tag:
|
||||
# Wheels are attached while the release is still a draft, so it is never published without
|
||||
# them — `[tool.uv.sources]` pins prime-kernels at a release asset, and an install that
|
||||
# resolves to a wheel-less release would fall back to compiling CUDA from source.
|
||||
kernels-from-auto-tag:
|
||||
needs: auto-tag-on-main
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/build_kernels.yaml
|
||||
with:
|
||||
release_tag: ${{ needs.auto-tag-on-main.outputs.tag }}
|
||||
ref: ${{ needs.auto-tag-on-main.outputs.tag }}
|
||||
|
||||
release-from-auto-tag:
|
||||
needs: [auto-tag-on-main, kernels-from-auto-tag]
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -138,13 +151,12 @@ jobs:
|
||||
run: |
|
||||
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
|
||||
|
||||
tag-and-release:
|
||||
resolve-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
|
||||
outputs:
|
||||
tag: ${{ steps.release.outputs.tag }}
|
||||
version: ${{ steps.release.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout tagged release (dispatch)
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
@@ -207,11 +219,28 @@ jobs:
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
kernels-from-tag:
|
||||
needs: resolve-release
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/build_kernels.yaml
|
||||
with:
|
||||
release_tag: ${{ needs.resolve-release.outputs.tag }}
|
||||
ref: ${{ needs.resolve-release.outputs.tag }}
|
||||
|
||||
publish-release:
|
||||
needs: [resolve-release, kernels-from-tag]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
# Needed to dispatch build_image.yaml below (POST .../dispatches).
|
||||
actions: write
|
||||
steps:
|
||||
- name: Publish draft release
|
||||
id: publish
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ steps.release.outputs.tag }}
|
||||
TAG: ${{ needs.resolve-release.outputs.tag }}
|
||||
run: |
|
||||
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
|
||||
if [ "$STATE" = "missing" ]; then
|
||||
@@ -232,6 +261,6 @@ jobs:
|
||||
if: steps.publish.outputs.published == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ steps.release.outputs.tag }}
|
||||
TAG: ${{ needs.resolve-release.outputs.tag }}
|
||||
run: |
|
||||
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
|
||||
|
||||
@@ -10,3 +10,6 @@
|
||||
[submodule "pydantic-config"]
|
||||
path = deps/pydantic-config
|
||||
url = https://github.com/PrimeIntellect-ai/pydantic-config
|
||||
[submodule "prime-kernels"]
|
||||
path = deps/prime-kernels
|
||||
url = https://github.com/PrimeIntellect-ai/prime-kernels
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Time the routed-expert compute three ways: the fused MoE kernel (bf16 and mxfp8) against
|
||||
the grouped-mm path a `model.moe_fused_kernel=false` run takes.
|
||||
|
||||
Forward and backward are timed separately, because only the forward is a kernel — the
|
||||
backward is prime-rl's own closed-form bf16 gradients or, for mxfp8, autograd through the
|
||||
grouped-mm reference. A speedup on the forward can be spent again on the backward.
|
||||
|
||||
uv run benchmarks/scripts/bench_fused_moe.py
|
||||
uv run benchmarks/scripts/bench_fused_moe.py --tokens 16384 --num-experts 128
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.layers.moe import _FusedMoE, _load_fused_moe_kernel, _run_experts_fused_reference
|
||||
|
||||
MODES = ("grouped_mm", "fused_bf16", "fused_mxfp8")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--tokens", type=int, default=8192, help="routed tokens (batch * seq)")
|
||||
parser.add_argument("--dim", type=int, default=2048, help="model dim; must be a multiple of 256")
|
||||
parser.add_argument("--hidden-dim", type=int, default=768, help="expert intermediate size; multiple of 128")
|
||||
parser.add_argument("--num-experts", type=int, default=64)
|
||||
parser.add_argument("--top-k", type=int, default=8)
|
||||
parser.add_argument("--iters", type=int, default=20)
|
||||
parser.add_argument("--warmup", type=int, default=5)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def make_inputs(args: argparse.Namespace) -> tuple[torch.Tensor, ...]:
|
||||
torch.manual_seed(0)
|
||||
randn = lambda *shape: torch.randn(*shape, device="cuda", dtype=torch.bfloat16)
|
||||
x = (randn(args.tokens, args.dim) * 0.2).requires_grad_(True)
|
||||
w1 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
|
||||
w3 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
|
||||
w2 = (randn(args.num_experts, args.dim, args.hidden_dim) * 0.05).requires_grad_(True)
|
||||
logits = torch.randn(args.tokens, args.num_experts, device="cuda", dtype=torch.float32)
|
||||
top_scores, selected = torch.softmax(logits, dim=-1).topk(args.top_k, dim=-1)
|
||||
return x, w1, w2, w3, selected, top_scores.requires_grad_(True)
|
||||
|
||||
|
||||
def run_forward(mode: str, inputs: tuple[torch.Tensor, ...], num_experts: int) -> torch.Tensor:
|
||||
x, w1, w2, w3, selected, top_scores = inputs
|
||||
if mode == "grouped_mm":
|
||||
return _run_experts_fused_reference(x, w1, w2, w3, selected, top_scores, num_experts)
|
||||
return _FusedMoE.apply(x, w1, w2, w3, selected, top_scores, num_experts, mode == "fused_mxfp8")
|
||||
|
||||
|
||||
def time_mode(mode: str, inputs: tuple[torch.Tensor, ...], args: argparse.Namespace) -> tuple[float, float, float]:
|
||||
"""Median forward ms, median backward ms, peak MiB."""
|
||||
forward_ms, backward_ms = [], []
|
||||
grad_out = torch.randn(args.tokens, args.dim, device="cuda", dtype=torch.bfloat16)
|
||||
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
|
||||
for i in range(args.warmup + args.iters):
|
||||
for tensor in inputs[:4] + (inputs[5],):
|
||||
tensor.grad = None
|
||||
torch.cuda.synchronize()
|
||||
|
||||
start.record()
|
||||
out = run_forward(mode, inputs, args.num_experts)
|
||||
end.record()
|
||||
torch.cuda.synchronize()
|
||||
if i >= args.warmup:
|
||||
forward_ms.append(start.elapsed_time(end))
|
||||
|
||||
start.record()
|
||||
out.backward(grad_out)
|
||||
end.record()
|
||||
torch.cuda.synchronize()
|
||||
if i >= args.warmup:
|
||||
backward_ms.append(start.elapsed_time(end))
|
||||
|
||||
median = lambda values: sorted(values)[len(values) // 2]
|
||||
return median(forward_ms), median(backward_ms), torch.cuda.max_memory_allocated() / 2**20
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
if not torch.cuda.is_available():
|
||||
raise SystemExit("no CUDA device")
|
||||
kernel = _load_fused_moe_kernel()
|
||||
for mxfp8 in (False, True):
|
||||
reason = kernel.unsupported_shape_reason(args.dim, args.hidden_dim, mxfp8=mxfp8)
|
||||
if reason is not None:
|
||||
raise SystemExit(f"shape unsupported by the fused kernel: {reason}")
|
||||
|
||||
inputs = make_inputs(args)
|
||||
print(
|
||||
f"tokens={args.tokens} dim={args.dim} hidden_dim={args.hidden_dim} "
|
||||
f"experts={args.num_experts} top_k={args.top_k} "
|
||||
f"({args.iters} iters, {args.warmup} warmup, median)\n"
|
||||
)
|
||||
print(f"{'mode':<12} {'fwd ms':>9} {'bwd ms':>9} {'total ms':>9} {'speedup':>9} {'peak MiB':>10}")
|
||||
|
||||
baseline = None
|
||||
for mode in MODES:
|
||||
forward, backward, peak = time_mode(mode, inputs, args)
|
||||
total = forward + backward
|
||||
baseline = baseline or total
|
||||
print(f"{mode:<12} {forward:>9.3f} {backward:>9.3f} {total:>9.3f} {baseline / total:>8.2f}x {peak:>10.0f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -34,20 +34,12 @@ max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -21,17 +21,11 @@ seq_len = 8192
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math-env"
|
||||
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
dataset_subset = "default"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "math-env"
|
||||
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
env.taskset.dataset_subset = "default"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
@@ -24,15 +24,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -29,14 +29,8 @@ max_completion_tokens = 1024
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -42,15 +42,9 @@ max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wiki-search"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -23,15 +23,9 @@ group_size = 8
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.player.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wordle"
|
||||
env.player.harness.id = "null"
|
||||
env.player.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -27,23 +27,15 @@ max_completion_tokens = 384
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort"
|
||||
min_turns = 2
|
||||
max_turns = 2
|
||||
min_names_per_turn = 1
|
||||
max_names_per_turn = 3
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
similarity_power = 4
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 2
|
||||
env.taskset.max_turns = 2
|
||||
env.taskset.min_names_per_turn = 1
|
||||
env.taskset.max_names_per_turn = 3
|
||||
env.taskset.task.similarity_power = 4
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -15,9 +15,6 @@ lr = 5e-5
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
@@ -33,15 +30,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -12,9 +12,6 @@ lr = 5e-5
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
@@ -30,15 +27,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -30,15 +30,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -42,15 +42,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -61,15 +55,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -48,15 +48,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -67,15 +61,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -5,9 +5,6 @@ max_steps = 10
|
||||
[resume]
|
||||
step = 5
|
||||
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
|
||||
@@ -2,9 +2,6 @@ max_steps = 5
|
||||
|
||||
[ckpt]
|
||||
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
|
||||
@@ -30,15 +30,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -27,15 +27,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -23,20 +23,12 @@ max_inflight = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
@@ -23,17 +23,11 @@ max_inflight = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math-env"
|
||||
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
dataset_subset = "default"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "math-env"
|
||||
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
env.taskset.dataset_subset = "default"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
@@ -41,15 +35,9 @@ interval = 50
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2024"
|
||||
group_size = 32
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime24"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "aime24"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -23,15 +23,9 @@ max_inflight = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -24,15 +24,9 @@ max_inflight = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wiki-search"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
@@ -23,15 +23,9 @@ max_inflight = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.player.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wordle"
|
||||
env.player.harness.id = "null"
|
||||
env.player.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -25,16 +25,10 @@ max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "color-codeword"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "color-codeword"
|
||||
images_per_turn = 1
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "color-codeword"
|
||||
env.taskset.images_per_turn = 1
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -26,20 +26,12 @@ alpha = 0.1
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
@@ -23,15 +23,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -42,15 +36,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -23,15 +23,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -42,15 +36,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -33,34 +33,18 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-grpo"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-opd"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.algo]
|
||||
type = "opd"
|
||||
|
||||
[orchestrator.train.source.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = "http://localhost:8001/v1"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
algo.type = "opd"
|
||||
algo.teacher.name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
algo.teacher.base_url = "http://localhost:8001/v1"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
@@ -71,15 +55,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -35,15 +35,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -54,15 +48,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -35,15 +35,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -54,15 +48,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
@@ -70,9 +58,6 @@ lr = 1e-4
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
+10
-30
@@ -23,21 +23,11 @@ max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "kuhn-poker"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "kuhn-poker"
|
||||
|
||||
[orchestrator.train.source.env.player0.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player0.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.env.player1.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player1.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "kuhn-poker"
|
||||
env.player0.harness.id = "null"
|
||||
env.player0.runtime.type = "subprocess"
|
||||
env.player1.harness.id = "null"
|
||||
env.player1.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -48,21 +38,11 @@ max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "kuhn-poker"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "kuhn-poker"
|
||||
|
||||
[orchestrator.eval.source.env.player0.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.player0.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval.source.env.player1.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.player1.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "kuhn-poker"
|
||||
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
|
||||
|
||||
@@ -31,15 +31,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -50,15 +44,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -40,15 +40,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -59,15 +53,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -40,15 +40,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -59,15 +53,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
@@ -75,9 +63,6 @@ lr = 1e-4
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -41,6 +41,8 @@ num_infer_replicas = 1
|
||||
project = "swe-ablations"
|
||||
name = "debug-concurrency"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -77,7 +79,6 @@ max_inflight_activations = 1
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
@@ -105,17 +106,9 @@ thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["debug-concurrency"]
|
||||
|
||||
[monitors.prime]
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["debug-concurrency"]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
|
||||
@@ -125,24 +118,15 @@ interval = 20
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
num_examples = 100
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["debug-concurrency"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["debug-concurrency"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
|
||||
@@ -19,27 +19,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-a"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-b"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
@@ -50,15 +38,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
+1
Submodule deps/prime-kernels added at 2ceaf9eccb
Vendored
+1
-1
Submodule deps/verifiers updated: 4bcb48e55a...a60a606ecc
+1
-6
@@ -115,12 +115,7 @@ dropout = 0.0
|
||||
|
||||
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
|
||||
|
||||
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
|
||||
|
||||
```toml
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
```
|
||||
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
|
||||
|
||||
## Disaggregated Prefill/Decode Inference
|
||||
|
||||
|
||||
+18
-52
@@ -124,36 +124,22 @@ type = "grpo"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "math" # inherits the top-level grpo
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "math"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "terminal"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "terminal"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
env.taskset.id = "terminal"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
# this env runs its own algorithm
|
||||
[orchestrator.train.source.algo]
|
||||
type = "echo"
|
||||
algo.type = "echo"
|
||||
```
|
||||
|
||||
### The Algorithm Classes
|
||||
|
||||
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
|
||||
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
|
||||
|
||||
| `algo.type` | Class | hook(s) — stage |
|
||||
|---|---|---|
|
||||
@@ -365,21 +351,11 @@ episode_agents = ["solver"]
|
||||
name = "proposer-solver"
|
||||
group_size = 4 # proposed problems per source task
|
||||
env.n = 4 # solver attempts per proposed problem
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "proposer-solver"
|
||||
|
||||
[orchestrator.train.source.env.proposer.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.proposer.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.env.solver.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.solver.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "proposer-solver"
|
||||
env.proposer.harness.id = "null"
|
||||
env.proposer.runtime.type = "subprocess"
|
||||
env.solver.harness.id = "null"
|
||||
env.solver.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero.
|
||||
@@ -399,21 +375,11 @@ decay = 0.95
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "kuhn-poker"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "kuhn-poker"
|
||||
|
||||
[orchestrator.train.source.env.player0.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player0.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.env.player1.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player1.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "kuhn-poker"
|
||||
env.player0.harness.id = "null"
|
||||
env.player0.runtime.type = "subprocess"
|
||||
env.player1.harness.id = "null"
|
||||
env.player1.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
Both of `kuhn-poker`'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.
|
||||
|
||||
+13
-33
@@ -106,10 +106,8 @@ uv run rl @ rl.toml --orchestrator.train.source.0.args \
|
||||
|
||||
```toml
|
||||
[[orchestrator.train.source]]
|
||||
|
||||
[orchestrator.train.source.args]
|
||||
dataset_name = "openai/gsm8k"
|
||||
dataset_subset = "main"
|
||||
args.dataset_name = "openai/gsm8k"
|
||||
args.dataset_subset = "main"
|
||||
```
|
||||
|
||||
### Optional Sub-Configs
|
||||
@@ -153,42 +151,24 @@ Training and evaluation sources are arrays of tables. Set one source per environ
|
||||
[[orchestrator.train.source]]
|
||||
name = "gsm8k"
|
||||
ratio = 3 # 75% of batches
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "gsm8k"
|
||||
split = "train"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "gsm8k"
|
||||
env.taskset.split = "train"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
ratio = 1 # default — 25% of batches
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "gsm8k-eval"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "gsm8k"
|
||||
split = "test"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "gsm8k"
|
||||
env.taskset.split = "test"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
|
||||
|
||||
+1
-1
@@ -109,7 +109,7 @@ uv run sft \
|
||||
--data.name PrimeIntellect/Reverse-Text-SFT \
|
||||
--max_steps 200 \
|
||||
--optim.lr 1e-4 \
|
||||
--ckpt.weights
|
||||
--ckpt
|
||||
```
|
||||
|
||||
Then run the full RL stack on reverse-text:
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundl
|
||||
uv run rl @ examples/basic/reverse-text/rl.toml
|
||||
```
|
||||
|
||||
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/<run_name>/weights/step_20`.
|
||||
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes with a final DCP checkpoint at `outputs/<run_name>/checkpoints/step_20`.
|
||||
|
||||
## Documentation
|
||||
|
||||
|
||||
+7
-24
@@ -59,7 +59,7 @@ 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.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
|
||||
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `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). |
|
||||
@@ -187,15 +187,9 @@ num_examples = 32
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -204,11 +198,11 @@ num_train_gpus = 1 # trainer
|
||||
num_infer_gpus = 1 # inference
|
||||
```
|
||||
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. The handoff is the filesystem, not NCCL: the trainer writes an HF weight checkpoint at every step an eval env is due (in addition to `ckpt.interval`), and the evals process watches `weights/step_{n}`, points the inference server at each stable checkpoint (`/update_weights` reload from disk), and runs the due envs against it — sequentially per checkpoint, so every epoch measures exactly one policy version. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final checkpoint always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at every step an eval env is due, and the evals process watches `broadcasts/step_{n}` for synchronization markers before it drives the NCCL receive. It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
|
||||
#### Multi-Node (Decoupled Trainer and Inference Pool)
|
||||
|
||||
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two independent SLURM jobs**. `deployment.num_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
|
||||
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
@@ -223,7 +217,7 @@ tensor_parallel_size = 8
|
||||
job_name = "my-run"
|
||||
```
|
||||
|
||||
The only coupling is weight checkpoints on the shared filesystem, so the jobs' lifetimes are independent: when training finishes, the trainer job exits and releases its nodes even while evals are still running; the eval job keeps draining pending checkpoints and exits after evaluating the final one (`max_steps` — without it the eval job never sees a final checkpoint and holds its allocation until walltime). Trainer and evals log to a single shared W&B run across both jobs — the trainer creates it, the evals process finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
|
||||
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
@@ -272,7 +266,6 @@ Checkpointing is split across processes because the orchestrator and trainer can
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
|
||||
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
|
||||
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
|
||||
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<run_dir>/weights/step_N/` |
|
||||
|
||||
### Enabling Checkpoints
|
||||
|
||||
@@ -304,16 +297,6 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
|
||||
--resume.dir outputs/my-run/checkpoints/step_10
|
||||
```
|
||||
|
||||
### Serving Checkpoints
|
||||
|
||||
HF-compatible weight snapshots are written under `<run_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via `--ckpt.weights-only` for cheaper snapshots). Upload directly:
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/<model>-RL outputs/<run_name>/weights/step_100
|
||||
```
|
||||
|
||||
For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write the raw adapter alongside the merged weights — useful when serving the adapter through a separate `/load_lora_adapter` call.
|
||||
|
||||
## Observability
|
||||
|
||||
### Log Files
|
||||
|
||||
@@ -25,6 +25,8 @@ num_infer_replicas = 4
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -59,7 +61,6 @@ max_inflight_activations = 1
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
@@ -89,8 +90,6 @@ num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.0
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
|
||||
|
||||
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
|
||||
@@ -98,18 +97,12 @@ num_turns_weight = 0.0
|
||||
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
|
||||
[[orchestrator.train.source]]
|
||||
name = "openseeker"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "openseeker"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.taskset.id = "openseeker"
|
||||
|
||||
[[orchestrator.train.source.env.taskset.task.judges]]
|
||||
id = "reference"
|
||||
@@ -128,18 +121,12 @@ choices = ["A", "B"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "redsearcher"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
|
||||
|
||||
[[orchestrator.train.source.env.taskset.task.judges]]
|
||||
id = "reference"
|
||||
@@ -164,24 +151,14 @@ interval = 20
|
||||
[[orchestrator.eval.source]]
|
||||
name = "browsecomp"
|
||||
num_examples = 500 # full set is 1266; cap eval at 500
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "browsecomp"
|
||||
|
||||
[orchestrator.eval.source.env.taskset.task.judge]
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "browsecomp"
|
||||
env.taskset.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]]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, rlm harness on a prime sandbox
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
@@ -7,9 +7,8 @@
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
#
|
||||
# 1 train + 3 infer nodes. Inference serves FP8 via online per-tensor quantization of the bf16
|
||||
# checkpoint; weight broadcasts re-quantize through the same path on every update. The trainer fits on one
|
||||
# node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
|
||||
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
|
||||
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, 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), and
|
||||
# skip-gather / skip-optimizer checkpointing.
|
||||
@@ -40,6 +39,8 @@ num_infer_replicas = 3
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -76,7 +77,6 @@ max_inflight_activations = 1
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
@@ -104,45 +104,26 @@ thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["glm45air-swe"]
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm45air-swe"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
@@ -151,5 +132,4 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
quantization = "fp8"
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -26,6 +26,8 @@ num_infer_replicas = 4
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -60,7 +62,6 @@ max_inflight_activations = 1
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
@@ -90,22 +91,14 @@ num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "tmax"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "tmax"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.taskset.id = "tmax"
|
||||
|
||||
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
|
||||
# [[orchestrator.train.source.env.taskset.judges]]
|
||||
@@ -129,27 +122,17 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/prime-envs/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
@@ -160,19 +143,11 @@ id = "swebench-verified"
|
||||
[[orchestrator.eval.source]]
|
||||
name = "terminal-bench-2"
|
||||
group_size = 4 # avg@4
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "terminal-bench-2"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
|
||||
@@ -134,15 +134,9 @@ clear_thinking = false
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "r2e"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["glm5-llmd"]
|
||||
env.taskset.id = "r2e-gym"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.runtime.labels = ["glm5-llmd"]
|
||||
|
||||
[inference]
|
||||
# <0.80 because glm5 layers are too large for 0.85
|
||||
|
||||
@@ -55,7 +55,6 @@ max_inflight_activations = 1
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
skip_gather_master_weights = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "adamw"
|
||||
@@ -79,15 +78,9 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm5-pd-disag", "swe-bench-verified"]
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
|
||||
|
||||
[inference]
|
||||
# we need <0.85 bc glm5 layers are too large for 0.85
|
||||
|
||||
@@ -54,103 +54,59 @@ max_inflight = 4096
|
||||
name = "swe"
|
||||
ratio = 0.3
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["intellect-3.1", "swe"]
|
||||
env.taskset.id = "r2e-gym"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["intellect-3.1", "swe"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "deepdive"
|
||||
ratio = 0.2
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "deepdive"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["intellect-3.1", "deepdive"]
|
||||
env.taskset.id = "deepdive"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.runtime.labels = ["intellect-3.1", "deepdive"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
ratio = 0.3
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_math"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "i3_math"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "logic"
|
||||
ratio = 0.2
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_logic"
|
||||
|
||||
[orchestrator.train.source.env.taskset.filter]
|
||||
max = 0.874
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "i3_logic"
|
||||
env.taskset.filter.max = 0.874
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "code"
|
||||
ratio = 0.2
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_code"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "i3_code"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["intellect-3.1", "swe-bench-verified"]
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["intellect-3.1", "swe-bench-verified"]
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2025"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime25"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -53,30 +53,18 @@ max_inflight = 4096
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["minimax-swe", "swe"]
|
||||
env.taskset.id = "r2e-gym"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["minimax-swe", "swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["minimax-swe", "swe-bench-verified"]
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["minimax-swe", "swe-bench-verified"]
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -22,6 +22,8 @@ num_infer_replicas = 4
|
||||
project = "nemotron-3-super"
|
||||
name = "nemotron-3-super-swe"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -56,7 +58,6 @@ max_inflight_activations = 1
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
@@ -86,37 +87,21 @@ truncate_history_thinking = false
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[monitors.prime]
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.runtime.labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["nemotron-3-super-swe"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
[inference]
|
||||
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
|
||||
|
||||
@@ -52,30 +52,18 @@ max_completion_tokens = 32768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_math"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "i3_math"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2025"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime25"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -50,30 +50,18 @@ initial_inflight = 1024
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["qwen30b-swe", "swe"]
|
||||
env.taskset.id = "r2e-gym"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["qwen30b-swe", "swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["qwen30b-swe", "swe-bench-verified"]
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["qwen30b-swe", "swe-bench-verified"]
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -36,19 +36,11 @@ group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "general-agent"
|
||||
min_tier = 1
|
||||
|
||||
[orchestrator.train.source.env.taskset.task.tools]
|
||||
colocated = true
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "modal"
|
||||
env.taskset.id = "general-agent"
|
||||
env.taskset.min_tier = 1
|
||||
env.taskset.task.tools.colocated = true
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "modal"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -98,11 +98,7 @@ uv run rl @ examples/basic/alphabet-sort/rl.toml \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
This will write a weight checkpoint in `outputs/rl/weights/step_100`. Upload it to HF to be able to use it as the final model for evaluation.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-4B-Instruct-AlphabetSort-RL outputs/rl/weights/step_100
|
||||
```
|
||||
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL`](https://huggingface.co/PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL).
|
||||
|
||||
|
||||
@@ -33,19 +33,11 @@ max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference] # Default inference config
|
||||
|
||||
@@ -18,17 +18,11 @@ seq_len = 8192
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math-env"
|
||||
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
dataset_subset = "default"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "math-env"
|
||||
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
env.taskset.dataset_subset = "default"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
@@ -36,15 +30,9 @@ interval = 50
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2024"
|
||||
group_size = 32
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime24"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "aime24"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
@@ -60,11 +60,7 @@ uv run torchrun \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
This should write a weight checkpoint in `outputs/sft/weights/step_100`. Upload it to HF to be able to use it as the base model for RL.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT outputs/sft/weights/step_100
|
||||
```
|
||||
This should write a DCP checkpoint in `outputs/sft/checkpoints/step_100`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT).
|
||||
|
||||
@@ -83,11 +79,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
This will write a weight checkpoint in `outputs/rl/weights/step_20`. As before, let's upload it to HF.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-RL outputs/rl/weights/step_20
|
||||
```
|
||||
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_20`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL).
|
||||
|
||||
@@ -134,17 +126,7 @@ Exec into the trainer pod and run SFT:
|
||||
```bash
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
|
||||
# This will save checkpoints to /data/outputs/sft/weights/step_100
|
||||
```
|
||||
|
||||
Upload the checkpoint to HuggingFace or use it directly from shared storage:
|
||||
|
||||
```bash
|
||||
# Option 1: Upload to HuggingFace (from within the pod)
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT /data/outputs/sft/weights/step_100
|
||||
|
||||
# Option 2: Use local checkpoint path in RL config
|
||||
# Update the model.name in the RL configs to point to /data/outputs/sft/weights/step_100
|
||||
# This will save DCP checkpoints to /data/outputs/sft/checkpoints/step_100
|
||||
```
|
||||
|
||||
### Step 3: Deploy RL Training
|
||||
@@ -212,11 +194,11 @@ kubectl exec -it my-exp-trainer-0 -- bash
|
||||
|
||||
# If inference server isn't running with the RL model, start it in another terminal:
|
||||
kubectl exec -it my-exp-inference-0 -- bash
|
||||
uv run inference --vllm.model /data/outputs/weights/step_20
|
||||
uv run inference --vllm.model /data/outputs/weights_hf/step_20
|
||||
|
||||
# Back in trainer pod, run evaluation
|
||||
uv run eval reverse-text --harness.id null \
|
||||
-m /data/outputs/weights/step_20 \
|
||||
-m /data/outputs/weights_hf/step_20 \
|
||||
--client.base-url $INFERENCE_URL \
|
||||
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
```
|
||||
|
||||
@@ -17,15 +17,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -22,15 +22,9 @@ max_completion_tokens = 1024
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -103,11 +103,7 @@ The unified config file automatically configures:
|
||||
- **Orchestrator**: Rollout generation with tool calling enabled
|
||||
- **Inference**: vLLM server for Qwen3-4B-Instruct-2507 with tool parsing enabled
|
||||
|
||||
This will write weight checkpoints in `outputs/rl/weights/step_*`. Upload the final checkpoint to HuggingFace:
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-4B-Instruct-WikiSearch-RL outputs/rl/weights/step_500
|
||||
```
|
||||
This will write DCP checkpoints in `outputs/rl/checkpoints/step_*`.
|
||||
|
||||
## Evaluation
|
||||
|
||||
|
||||
@@ -45,15 +45,9 @@ max_completion_tokens = 512
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wiki-search"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -62,11 +62,7 @@ uv run torchrun \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
After training completes, you will find the final weight checkpoint in `outputs/sft/weights/step_20`. Upload it to HF to be able to use it as the base model for RL we will do in the next section.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-1.7B-Wordle-SFT outputs/sft/weights/step_20
|
||||
```
|
||||
After training completes, you will find the final DCP checkpoint in `outputs/sft/checkpoints/step_20`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-SFT).
|
||||
|
||||
@@ -86,11 +82,7 @@ uv run rl @ examples/basic/wordle/rl.toml \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
This will write a weight checkpoint in `outputs/rl/weights/step_100`. As before, let's upload it to HF.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-1.7B-Wordle-RL outputs/rl/weights/step_100
|
||||
```
|
||||
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-RL).
|
||||
|
||||
|
||||
@@ -20,15 +20,9 @@ group_size = 16
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.player.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wordle"
|
||||
env.player.harness.id = "null"
|
||||
env.player.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
+6
-18
@@ -21,24 +21,12 @@ max_inflight = 32
|
||||
|
||||
[[eval.source]]
|
||||
name = "swebench-verified"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
[[eval.source]]
|
||||
name = "terminal-bench-2"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "terminal-bench-2"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
max_steps = 20
|
||||
|
||||
[ckpt]
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.5-0.8B"
|
||||
|
||||
@@ -47,8 +47,6 @@ lr = 1e-5
|
||||
|
||||
[ckpt]
|
||||
interval = 200
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
|
||||
@@ -15,15 +15,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
@@ -5,6 +5,7 @@ from pydantic import Field, model_validator
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
@@ -40,14 +41,14 @@ class EvalsEvalConfig(EvalConfig):
|
||||
|
||||
|
||||
class OnlineConfig(BaseConfig):
|
||||
"""Checkpoint-driven online evals: watch a weights directory for new HF checkpoints
|
||||
and evaluate each eligible one. Without this block the evals process runs every eval
|
||||
source once against the weights the inference server currently serves, then exits."""
|
||||
"""Broadcast-driven online evals: watch a broadcasts directory for new weight
|
||||
broadcasts and evaluate each eligible one. Without this block the evals process runs
|
||||
every eval source once against the weights the inference server currently serves,
|
||||
then exits."""
|
||||
|
||||
weights_dir: Path | None = None
|
||||
"""Directory to watch for ``step_{n}`` HF weight checkpoints. The ``sft`` launcher
|
||||
fills it from ``ckpt.output_dir`` when checkpoints are redirected to another volume;
|
||||
defaults to ``<output_dir>/weights``."""
|
||||
broadcasts_dir: Path | None = None
|
||||
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
|
||||
``<output_dir>/broadcasts``."""
|
||||
|
||||
max_steps: int | None = None
|
||||
"""Trainer step at which the run ends. The final checkpoint always fires every
|
||||
@@ -64,15 +65,15 @@ class EvalsConfig(BaseConfig):
|
||||
"""``uv run evals``: run the configured evals against a live inference server.
|
||||
Standalone (no ``[online]``), one epoch of every eval source runs against the
|
||||
served weights and the evals process exits. With ``[online]``, the evals process watches a
|
||||
weights directory for new HF checkpoints, points the inference server at each one
|
||||
(``/update_weights`` from disk), and runs the configured evals against the updated
|
||||
weights — the ``sft`` launcher writes this config; it also works standalone against
|
||||
any trainer that writes ``weights/step_{n}`` HF checkpoints with ``STABLE`` markers."""
|
||||
broadcasts directory for new weight broadcasts, updates the inference server through
|
||||
the configured transport, and runs the configured evals against the updated weights.
|
||||
The ``sft`` launcher writes this config; filesystem mode also works standalone against
|
||||
any trainer that writes ``broadcasts/step_{n}`` directories with ``STABLE`` markers."""
|
||||
|
||||
model: str = "Qwen/Qwen3-0.6B"
|
||||
"""Name the inference server serves the model under — the ``model`` field of every
|
||||
eval request and the startup model check. Auto-filled from ``model.name`` by the
|
||||
``sft`` launcher; the name stays fixed across checkpoint reloads (weights are
|
||||
``sft`` launcher; the name stays fixed across weight updates (weights are
|
||||
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
|
||||
|
||||
eval: EvalsEvalConfig
|
||||
@@ -81,6 +82,10 @@ class EvalsConfig(BaseConfig):
|
||||
online: OnlineConfig | None = None
|
||||
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
"""Weight transport for online evals. The ``sft`` launcher fills this from its
|
||||
resolved trainer transport. None uses filesystem reloads."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — rollout traces and logs are written as
|
||||
subdirectories. Shared with the trainer for online evals."""
|
||||
@@ -91,9 +96,9 @@ class EvalsConfig(BaseConfig):
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weights_dir(self):
|
||||
if self.online is not None and self.online.weights_dir is None:
|
||||
self.online.weights_dir = self.output_dir / "weights"
|
||||
def auto_setup_broadcasts_dir(self):
|
||||
if self.online is not None and self.online.broadcasts_dir is None:
|
||||
self.online.broadcasts_dir = self.output_dir / "broadcasts"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -530,7 +530,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""Maximum training steps. If None, runs indefinitely."""
|
||||
|
||||
max_off_policy_steps: int = Field(8, ge=0)
|
||||
"""Maximum policies allowed to generate a single rollout. Rollouts generated more than ``max_off_policy_steps`` ahead of training are discarded. Higher values yield better throughput at the cost of off-policy noise."""
|
||||
"""Maximum staleness of a trained rollout: the version a batch trains on (v{step-1}) minus the oldest version that generated the rollout (a rollout can span several weight updates), queue time included. Episodes past the bound are dropped, in-flight and queued; a group shares one dispatch version, so its episodes age out together. Higher values yield better throughput at the cost of off-policy noise."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
@@ -23,11 +23,15 @@ from prime_rl.configs.trainer import (
|
||||
AdamWConfig,
|
||||
CheckpointConfig,
|
||||
ConstantSchedulerConfig,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
GCConfig,
|
||||
ModelConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
OptimizerConfig,
|
||||
SchedulerConfig,
|
||||
TokenizerConfig,
|
||||
WeightBroadcastConfig,
|
||||
validate_scheduler,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
|
||||
@@ -42,8 +46,8 @@ class BaseDataConfig(BaseConfig):
|
||||
micro_batch_size: int = Field(1, ge=1)
|
||||
"""Per-step micro batch size. ``batch_size`` must be divisible by this."""
|
||||
|
||||
num_workers: int = Field(1, ge=0)
|
||||
"""Number of dataloader worker processes. With ``>= 1``, batches are prepared and pinned in the background so tokenization/packing overlaps with training. ``0`` loads inline on the main process."""
|
||||
num_workers: int = Field(1, ge=1)
|
||||
"""Number of dataloader worker processes. Batches are prepared and pinned in the background so tokenization/packing overlaps with training."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_batch_size(self):
|
||||
@@ -172,9 +176,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
|
||||
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
|
||||
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
|
||||
from the trainer job: the handoff is weight checkpoints on the shared filesystem,
|
||||
so the eval job can outlive the trainer job (evals drain after training ends) and
|
||||
exits after evaluating the final checkpoint."""
|
||||
from the trainer job. The eval job can outlive the trainer job while it evaluates
|
||||
the final weight broadcast."""
|
||||
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
@@ -203,13 +206,16 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
eval: EvalsEvalConfig | None = None
|
||||
"""Online evaluation configuration: rollout-based evals against a live inference
|
||||
server that reloads the trainer's HF weight checkpoints from disk. If None, no
|
||||
online evals run."""
|
||||
server that receives the trainer's weight broadcasts. If None, no online evals run."""
|
||||
|
||||
inference: InferenceConfig | None = None
|
||||
"""Inference server for online evals. If None (with ``eval`` set), the launcher
|
||||
does not start a server and evals connect to ``eval.client.base_url``."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
"""Trainer-to-inference weight transport for online evals. Defaults to NCCL.
|
||||
LoRA and external inference use filesystem broadcast."""
|
||||
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
scheduler: SchedulerConfig = ConstantSchedulerConfig()
|
||||
@@ -349,29 +355,39 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_online_eval(self):
|
||||
"""Wire online evals: require weight checkpoints (the disk handoff to
|
||||
inference) and connect the eval client to the launcher-managed server."""
|
||||
"""Wire online evals and the trainer-to-inference weight transport."""
|
||||
if self.eval is None:
|
||||
if self.inference is not None:
|
||||
raise ValueError("[inference] is only used for online evals — add an [eval] block or remove it.")
|
||||
return self
|
||||
|
||||
# The trainer's HF weight checkpoints are how inference picks up new policies.
|
||||
if self.ckpt is None:
|
||||
self.ckpt = CheckpointConfig()
|
||||
if self.ckpt.weights is None or self.ckpt.skip_gather_master_weights:
|
||||
raise ValueError(
|
||||
"Online evals require HF weight checkpoints. Enable ckpt.weights and "
|
||||
"disable ckpt.skip_gather_master_weights."
|
||||
)
|
||||
# LoRA runs broadcast the raw adapter, which evals reload via /load_lora_adapter
|
||||
if self.model.lora is not None:
|
||||
if self.inference is not None:
|
||||
self.inference.vllm.enable_lora = True
|
||||
self.inference.vllm.max_lora_rank = self.model.lora.rank
|
||||
else:
|
||||
warnings.warn(
|
||||
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
|
||||
"make sure to set --enable_lora and --max-lora-rank.",
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
if self.ckpt.keep_last is not None or self.ckpt.keep_interval is not None:
|
||||
warnings.warn(
|
||||
"ckpt.keep_last / ckpt.keep_interval can delete a weight checkpoint before the "
|
||||
"evals consumes it when evals run slower than training - such steps are "
|
||||
"skipped with a warning instead of evaluated.",
|
||||
stacklevel=2,
|
||||
)
|
||||
if self.weight_broadcast is None:
|
||||
if self.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = FileSystemWeightBroadcastConfig()
|
||||
else:
|
||||
self.weight_broadcast = NCCLWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type != "filesystem":
|
||||
if self.weight_broadcast.type == "nixl":
|
||||
raise ValueError("NIXL weight broadcast is not supported for SFT online evals.")
|
||||
if self.model.lora is not None:
|
||||
raise ValueError(
|
||||
"LoRA training is not yet supported with in-memory weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
if self.eval.retrigger_on_resume:
|
||||
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
|
||||
|
||||
if self.deployment.type == "multi_node":
|
||||
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
|
||||
@@ -398,10 +414,11 @@ class SFTConfig(BaseConfig):
|
||||
f"deployment.gpus_per_node ({self.deployment.gpus_per_node}) must be divisible by "
|
||||
f"inference.vllm.tensor_parallel_size ({self.inference.vllm.tensor_parallel_size})."
|
||||
)
|
||||
if self.inference.weight_broadcast.type != "filesystem":
|
||||
raise ValueError(
|
||||
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
self.weight_broadcast.inference_world_size = (
|
||||
self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
)
|
||||
self.inference.weight_broadcast.type = self.weight_broadcast.type
|
||||
if self.max_steps is None:
|
||||
warnings.warn(
|
||||
"Online evals without max_steps: the evals process never sees a final checkpoint, "
|
||||
@@ -450,10 +467,9 @@ class SFTConfig(BaseConfig):
|
||||
vllm.data_parallel_size = num_infer_gpus // vllm.tensor_parallel_size
|
||||
if vllm.api_server_count < vllm.data_parallel_size and not vllm.enable_lora:
|
||||
vllm.api_server_count = vllm.data_parallel_size
|
||||
if self.inference.weight_broadcast.type != "filesystem":
|
||||
raise ValueError(
|
||||
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size
|
||||
self.inference.weight_broadcast.type = self.weight_broadcast.type
|
||||
|
||||
host = self.inference.server.host or "localhost"
|
||||
client = self.eval.client
|
||||
@@ -545,14 +561,8 @@ class SFTConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
lora_enabled = self.model and self.model.lora
|
||||
if not lora_enabled:
|
||||
raise ValueError(
|
||||
"save_adapter_separately=True requires LoRA to be enabled. "
|
||||
"Set model.lora or disable save_adapter_separately."
|
||||
)
|
||||
def validate_scheduler_steps(self):
|
||||
validate_scheduler(self.scheduler, self.max_steps)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -242,6 +242,9 @@ class ModelConfig(BaseModelConfig):
|
||||
moe_use_grouped_mm: bool = True
|
||||
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
|
||||
|
||||
moe_fused_kernel: bool = False
|
||||
"""Run MoE routed experts through the vendored fused MoE CUDA kernel (``prime_kernels.flash_moe``) in forward; backward recomputes the reference grouped-mm path. Picks the mxfp8 kernel when ``quantization`` is MXFP8 with ``enable_grouped_gemm`` (which additionally needs ``hidden_size`` divisible by 256), otherwise the bf16 one. Requires the ``prime-kernels`` wheel, Blackwell (SM100) GPUs, ``ep=1``, ``model.impl='custom'``, MoE layers with output-weighted scores (``score_before_experts=False``), and ``moe_intermediate_size`` divisible by 128."""
|
||||
|
||||
quantization: QuantizationConfig | None = None
|
||||
|
||||
index_cache: IndexCacheConfig | None = None
|
||||
@@ -387,6 +390,28 @@ SchedulerConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
def validate_scheduler(scheduler: SchedulerConfig, max_steps: int | None) -> None:
|
||||
"""Check scheduler phases against max_steps so misconfigurations fail at config time."""
|
||||
if isinstance(scheduler, LinearSchedulerConfig):
|
||||
if scheduler.warmup_steps == 0 and scheduler.decay_steps == 0:
|
||||
raise ValueError(
|
||||
"Linear scheduler requires warmup_steps > 0 or decay_steps > 0 (use the constant scheduler instead)"
|
||||
)
|
||||
if scheduler.decay_steps > 0:
|
||||
if max_steps is None:
|
||||
raise ValueError("Must specify max_steps when using a linear scheduler with decay_steps > 0")
|
||||
if scheduler.warmup_steps + scheduler.decay_steps > max_steps:
|
||||
raise ValueError(
|
||||
f"warmup_steps ({scheduler.warmup_steps}) + decay_steps ({scheduler.decay_steps}) "
|
||||
f"must not exceed max_steps ({max_steps})"
|
||||
)
|
||||
if isinstance(scheduler, CosineSchedulerConfig):
|
||||
if max_steps is None:
|
||||
raise ValueError("Must specify max_steps when using a cosine scheduler")
|
||||
if scheduler.warmup_steps >= max_steps:
|
||||
raise ValueError(f"warmup_steps ({scheduler.warmup_steps}) must be less than max_steps ({max_steps})")
|
||||
|
||||
|
||||
class BaseOptimizerConfig(BaseConfig):
|
||||
lr: float = Field(1e-6, ge=0)
|
||||
"""Peak learning rate."""
|
||||
@@ -440,33 +465,13 @@ OptimizerConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class WeightCheckpointConfig(BaseConfig):
|
||||
save_sharded: bool = True
|
||||
"""Save the weight checkpoint in sharded format."""
|
||||
|
||||
save_format: Literal["safetensors", "torch"] = "safetensors"
|
||||
"""Weight checkpoint serialization format."""
|
||||
|
||||
save_adapter_separately: bool = False
|
||||
"""Save LoRA adapters separately before merging into full model weights."""
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
output_dir: Path | None = None
|
||||
"""Override directory for checkpoints and weights. If set, checkpoints and weight snapshots are written here instead of under the trainer ``output_dir`` — useful for writing large checkpoints to a separate storage volume."""
|
||||
"""Override directory for checkpoints. If set, checkpoints are written here instead of under the trainer ``output_dir`` — useful for writing large checkpoints to a separate storage volume."""
|
||||
|
||||
interval: int | None = Field(None, ge=1)
|
||||
"""Interval at which to save the training checkpoint. If None, only checkpoints at the end of training."""
|
||||
|
||||
weights: WeightCheckpointConfig | None = WeightCheckpointConfig()
|
||||
"""Weight-checkpoint sub-configuration. If None, no HF-compatible weight checkpoints are written."""
|
||||
|
||||
skip_gather_master_weights: bool = False
|
||||
"""Skip gathering and saving HF-compatible weight checkpoints. Useful for large models where the gather is expensive and only DCP checkpoints are needed."""
|
||||
|
||||
weights_only: bool = False
|
||||
"""Save only weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training."""
|
||||
|
||||
keep_last: int | None = Field(None, ge=1)
|
||||
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
|
||||
|
||||
@@ -547,12 +552,6 @@ class BaseWeightBroadcastConfig(BaseConfig):
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
save_sharded: bool = True
|
||||
"""Save the weight checkpoint in sharded format."""
|
||||
|
||||
save_format: Literal["safetensors", "torch"] = "safetensors"
|
||||
"""Weight checkpoint serialization format."""
|
||||
|
||||
|
||||
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
host: str = "localhost"
|
||||
@@ -721,14 +720,8 @@ class TrainerConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
lora_enabled = self.model and self.model.lora
|
||||
if not lora_enabled:
|
||||
raise ValueError(
|
||||
"save_adapter_separately=True requires LoRA to be enabled. "
|
||||
"Set model.lora or disable save_adapter_separately."
|
||||
)
|
||||
def validate_scheduler_steps(self):
|
||||
validate_scheduler(self.scheduler, self.max_steps)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -16,8 +16,8 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "qwen3_coder"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3"), "qwen3_coder"),
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
# Qwen3.5 and Qwen3-Coder use qwen3_coder — must be before the Qwen3 catch-all.
|
||||
(re.compile(r"^Qwen/Qwen3\.5-"), "qwen3_coder"),
|
||||
# Qwen3.5/3.6/3.8 and Qwen3-Coder use qwen3_coder — must be before the Qwen3 catch-all.
|
||||
(re.compile(r"^Qwen/Qwen3\.(5|6|8)-"), "qwen3_coder"),
|
||||
(re.compile(r"^Qwen/Qwen3-Coder"), "qwen3_coder"),
|
||||
(re.compile(r"^Qwen/Qwen3-"), "hermes"),
|
||||
]
|
||||
@@ -37,7 +37,7 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
# Only Qwen3 Thinking models reason — Instruct/base models do not.
|
||||
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
|
||||
(re.compile(r"^Qwen/Qwen3\.5-"), "qwen3"),
|
||||
(re.compile(r"^Qwen/Qwen3\.(5|6|8)-"), "qwen3"),
|
||||
]
|
||||
|
||||
|
||||
|
||||
+10
-3
@@ -86,6 +86,11 @@ gpt-oss = [
|
||||
quack = [
|
||||
"quack-kernels>=0.4.1",
|
||||
]
|
||||
# Prebuilt `prime-kernels` wheels from a release (see the `kernels` skill). Compiled for
|
||||
# sm_100a; on other GPUs the package installs fine and reports its kernels unavailable.
|
||||
kernels = [
|
||||
"prime-kernels",
|
||||
]
|
||||
all = [
|
||||
"prime-rl[flash-attn]",
|
||||
"prime-rl[disagg]",
|
||||
@@ -196,6 +201,7 @@ deep-ep = false
|
||||
deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
torchao = false
|
||||
prime-kernels = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
@@ -227,6 +233,10 @@ deep-gemm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-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_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
flash_attn_3 = { index = "pytorch-cu128-test" }
|
||||
@@ -261,9 +271,6 @@ select = ["F", "I"]
|
||||
"src/prime_rl/trainer/sft/data.py" = ["F722", "F821"]
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
# `prime_rl` is split across two editable wheels (prime-rl + prime-rl-configs).
|
||||
# Without this, ruff classifies prime_rl.configs.* as third-party because it
|
||||
# doesn't live under src/.
|
||||
known-first-party = ["prime_rl"]
|
||||
known-third-party = ["verifiers", "renderers", "pydantic_config"]
|
||||
|
||||
|
||||
+10
-20
@@ -34,7 +34,9 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
|
||||
|
||||
## Special syntax
|
||||
|
||||
**No inline tables** — checked-in configs use `[section]` headers, never `key = { ... }`. Expand `env.taskset = { id = "..." }` to a full-path header (`[orchestrator.train.source.env.taskset]` — subtable headers after a `[[...]]` entry attach to that entry).
|
||||
**No inline tables** — checked-in configs use `[section]` headers or dotted keys, never `key = { ... }`.
|
||||
|
||||
**Sources are one block** — inside a `[[...source]]` entry, write nested sub-configs as dotted keys in the same block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`), not one subsection header per nested config. Nested arrays of tables (e.g. `[[orchestrator.train.source.env.taskset.task.judges]]`) keep full-path headers — they attach to the preceding `[[...source]]` entry.
|
||||
|
||||
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
|
||||
|
||||
@@ -45,28 +47,16 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
|
||||
```toml
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text-eval"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
split = "test"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.taskset.split = "test"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
|
||||
|
||||
@@ -35,6 +35,25 @@ When bumping a package past the workspace-wide `exclude-newer = "7 days"` window
|
||||
|
||||
## Optional extras
|
||||
|
||||
### CUDA kernels
|
||||
|
||||
Prebuilt wheels, pinned at a release in `[tool.uv.sources]`:
|
||||
|
||||
```bash
|
||||
uv sync --extra kernels
|
||||
```
|
||||
|
||||
No plain sync compiles CUDA — building from source stays an explicit, manual step (needs
|
||||
`nvcc` whose CUDA major matches torch's and the `deps/prime-kernels` submodule initialized),
|
||||
and overrides the wheel until the next sync:
|
||||
|
||||
```bash
|
||||
git submodule update --init deps/prime-kernels
|
||||
uv pip install --no-build-isolation -e deps/prime-kernels
|
||||
```
|
||||
|
||||
See the `kernels` skill.
|
||||
|
||||
### NemotronH (Mamba SSD kernels)
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
---
|
||||
name: kernels
|
||||
description: How prime-rl vendors, builds, and ships CUDA kernels (the `deps/prime-kernels` submodule and the `prime-kernels` wheel). Use when adding a kernel, building it locally, calling one from training code, or publishing prebuilt wheels.
|
||||
---
|
||||
|
||||
# CUDA kernels
|
||||
|
||||
CUDA kernels live in their own monorepo,
|
||||
[prime-kernels](https://github.com/PrimeIntellect-ai/prime-kernels), checked out here as the
|
||||
git submodule `deps/prime-kernels`, alongside prime-rl's other submodules. That repo is the
|
||||
wheel root (`setup.py`, `pyproject.toml`) and `prime_kernels/` inside it is the importable
|
||||
package: one folder per kernel, holding the
|
||||
kernel's Python surface *and* its C++/CUDA sources under `csrc/`, all declared in the single
|
||||
manifest `prime_kernels/kernels.toml`. See `deps/prime-kernels/README.md` once the submodule
|
||||
is initialized.
|
||||
|
||||
Nothing about a kernel lives in prime-rl. prime-rl pins a prime-kernels commit, builds the
|
||||
wheel from it, and installs the result — and stays a pure-Python wheel itself; never add
|
||||
compiled extensions to it.
|
||||
|
||||
Living under `deps/` means `tool.ruff.extend-exclude = ["deps"]` in `pyproject.toml`
|
||||
already covers it — prime-rl lints none of it.
|
||||
|
||||
## Calling a kernel from prime-rl
|
||||
|
||||
Kernels are compiled for exact compute capabilities and may not be built at all, so always
|
||||
gate. Never import `prime_kernels.<name>` directly in training code:
|
||||
|
||||
```python
|
||||
import prime_kernels
|
||||
|
||||
if prime_kernels.is_available("flash_moe"):
|
||||
flash_moe = prime_kernels.load("flash_moe")
|
||||
```
|
||||
|
||||
`prime_kernels.status()` maps every kernel to `"available"` or the reason it is not — log
|
||||
it once at startup rather than failing a run halfway through. `unavailable_reason(name)` is
|
||||
the same answer for one kernel (`None` when it is usable), which is what a test's skip guard
|
||||
wants; `is_available` is just that call compared to `None`.
|
||||
|
||||
`flash_moe` is the one kernel today: fused MoE forward (bf16 + mxfp8) on Blackwell
|
||||
tcgen05, reached through `model.moe_fused_kernel=true`.
|
||||
|
||||
What a kernel requires of its inputs — block sizes, alignments, shape constraints — belongs
|
||||
to prime-kernels, which exports it: `flash_moe.BLOCK_M`, `flash_moe.MXFP8_SCALE_BLOCK`, and
|
||||
`flash_moe.unsupported_shape_reason(dim, hidden_dim, mxfp8=...)`, which
|
||||
`apply_fused_moe_kernel` calls once at setup so an unsupported model fails before training
|
||||
rather than mid-step. Never hardcode a `128` on this side: then every requirement change is
|
||||
a change in both repos.
|
||||
|
||||
## Building locally
|
||||
|
||||
`uv sync --extra kernels` installs the prebuilt wheel (see "Pinning installs at the prebuilt
|
||||
wheels"); building from source is for changing kernels. It is manual by design — no `uv sync`
|
||||
may compile CUDA, so the extra resolves to release wheels, never to this source tree:
|
||||
|
||||
```bash
|
||||
git submodule update --init deps/prime-kernels
|
||||
uv pip install --no-build-isolation -e deps/prime-kernels
|
||||
```
|
||||
|
||||
Requirements: `nvcc` on `CUDA_HOME` with the **same CUDA major as torch** (torch refuses to
|
||||
build extensions otherwise).
|
||||
|
||||
Kernels whose toolkit is unsuitable are skipped with a message and reported unavailable at
|
||||
runtime — the build still succeeds. `PRIME_KERNELS=a,b` builds a subset;
|
||||
`PRIME_KERNELS_REQUIRE=1` turns any skip into an error.
|
||||
|
||||
## Changing or adding a kernel
|
||||
|
||||
The work happens in the prime-kernels repo, not here. Inside `deps/prime-kernels/`:
|
||||
|
||||
1. Commit the sources under `prime_kernels/<name>/csrc/`.
|
||||
2. Add a `[<name>]` table to `prime_kernels/kernels.toml` — `sources`, `include-dirs`,
|
||||
`arch`, `cxx-std`; paths are relative to the kernel folder.
|
||||
3. Write `prime_kernels/<name>/__init__.py` — `from . import _C`, then per op a wrapper
|
||||
calling `torch.ops.<ns>.<op>` and a `torch.library.register_fake`. No
|
||||
`torch.library.custom_op` decorator: that defines a *Python* op, and `TORCH_LIBRARY`
|
||||
has already defined these C++ side — only the fake (meta) kernel is missing. A kernel
|
||||
used in training also needs `torch.library.register_autograd`, since a schema carries
|
||||
no backward. (`flash_moe` is forward only; prime-rl wraps it in an `autograd.Function`
|
||||
of its own.)
|
||||
4. Nothing else: `setup.py` and the runtime registry both read the manifest.
|
||||
|
||||
Rules the build assumes:
|
||||
|
||||
- The extension is always `prime_kernels.<name>._C`, so the C++ side defines
|
||||
`PYBIND11_MODULE(_C, m)` and registers ops with `TORCH_LIBRARY*`.
|
||||
- `arch` matches the device **exactly** at runtime (`10.0a` runs only on sm_100a); no PTX is
|
||||
shipped to JIT from.
|
||||
- Two packages registering the same `torch.ops` namespace collide. If a kernel's sources are
|
||||
also installed as a standalone package (e.g. `prime_moe` from prime-flash-moe, where
|
||||
`flash_moe` originally came from), uninstall it.
|
||||
- Only the Python surface and the compiled `_C` ship in the wheel; `csrc/` is build input.
|
||||
|
||||
Then land it in prime-rl as a submodule bump.
|
||||
|
||||
## Bumping the pin
|
||||
|
||||
Kernel sources are pinned by the submodule commit, so picking up any kernel change — yours
|
||||
or someone else's — is a bump:
|
||||
|
||||
```bash
|
||||
git -C deps/prime-kernels fetch origin
|
||||
git -C deps/prime-kernels log --oneline HEAD..origin/main
|
||||
git -C deps/prime-kernels checkout origin/main
|
||||
git add deps/prime-kernels
|
||||
```
|
||||
|
||||
Then, in order:
|
||||
|
||||
- Read the diff for **host-side contract changes**, not just kernel internals. A change to
|
||||
what the caller must pass (weight layout, scale packing, argument order) is silently wrong
|
||||
numbers, not a build error, and prime-rl's call sites have to absorb it.
|
||||
- Rebuild and re-run whatever exercises the kernel — the ABI is not checked for you. For
|
||||
`flash_moe` that is `tests/unit/train/models/test_fused_moe.py`, which compares its
|
||||
forward and its hand-written backward against the grouped-mm expert path; it is
|
||||
`gpu`-marked and skips itself unless the kernel is available, so it only means anything
|
||||
on a machine the kernel was built for.
|
||||
- The bump alone ships nothing: installs resolve `prime-kernels` from a release wheel, so the
|
||||
new code only reaches users once a release rebuilds the wheels and the pin below moves.
|
||||
|
||||
## Prebuilt wheels
|
||||
|
||||
[`build_kernels.yaml`](../../.github/workflows/build_kernels.yaml) builds the wheel for
|
||||
x86_64 and aarch64 in the CUDA devel image (no GPU needed — nvcc cross compiles). It inits
|
||||
the `deps/prime-kernels` submodule itself, runs on every bump of it, and attaches the wheels
|
||||
to a release when given a `release_tag`, alongside the deep-ep/deep-gemm/torchao wheels.
|
||||
|
||||
Its `paths` trigger is `deps/prime-kernels` (the gitlink), **not** `deps/prime-kernels/**` —
|
||||
no file under it is tracked by prime-rl, so a `**` pattern would match nothing and submodule
|
||||
bumps would build no wheels.
|
||||
|
||||
Every release gets them: [`tag-and-release.yaml`](../../.github/workflows/tag-and-release.yaml)
|
||||
calls this workflow after the tag is cut and **before** it promotes the draft, so a published
|
||||
release always carries its wheels. To backfill a release that predates this, dispatch by hand:
|
||||
|
||||
```bash
|
||||
gh workflow run build_kernels.yaml -f release_tag=vX.Y.Z -f ref=vX.Y.Z
|
||||
```
|
||||
|
||||
The wheel version carries the ABI it was built against, e.g.
|
||||
`prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl` — it imports only under
|
||||
that exact torch, so the build installs the torch pinned in `uv.lock`, not the newest one.
|
||||
The base version comes from `deps/prime-kernels/pyproject.toml` in the prime-kernels repo.
|
||||
|
||||
### Pinning installs at the prebuilt wheels
|
||||
|
||||
`uv sync --extra kernels` installs `prime-kernels` from the wheels named in
|
||||
`[tool.uv.sources]` — the pattern deep-ep, deep-gemm and vllm already use, and the only form
|
||||
the extra may take, since a sync must never compile:
|
||||
|
||||
```toml
|
||||
[tool.uv.sources]
|
||||
prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
```
|
||||
|
||||
The wheels are prime-rl release assets — the kernels live in their own repo, but they ship
|
||||
with prime-rl's releases. To move the pin, the build prints both lines, ready to paste, in
|
||||
its job summary. Then `uv lock`.
|
||||
|
||||
The pin necessarily trails by one release: a release's own assets do not exist until that
|
||||
release is built, so `vX.Y.Z` can only point at wheels from an already published tag. Move it
|
||||
whenever the kernels or the torch/CUDA pin change — a stale pin ships stale kernels, and a
|
||||
pin whose torch no longer matches the lock fails at import, not at install.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- prime-kernels' `pyproject.toml` mirrors prime-rl's own `torch>=2.9.0`; keep the two
|
||||
identical, and build against the torch in `uv.lock` (`build_kernels.yaml` reads it) — the
|
||||
wheel imports only under the torch it was compiled against.
|
||||
- Never reintroduce `prime-kernels` as a path source: uv cannot read a source tree's metadata
|
||||
without building it, so every `uv lock` would then need nvcc. A release-asset URL has static
|
||||
metadata and does not.
|
||||
- A fresh clone without the submodule still installs and trains — only the source build needs
|
||||
it. `build_kernels.yaml` inits it and sets `PRIME_KERNELS_REQUIRE=1`, so a wheel is never
|
||||
published with kernels silently skipped.
|
||||
+16
-2
@@ -9,7 +9,8 @@ Releases are driven by [`.github/workflows/tag-and-release.yaml`](../../.github/
|
||||
|
||||
1. You create a **draft GitHub Release** with the notes inline (`gh release create --draft`).
|
||||
2. You open a **draft PR** that bumps `version` in `pyproject.toml`.
|
||||
3. Maintainer merges. The workflow tags the commit and promotes the draft.
|
||||
3. Maintainer merges. The workflow tags the commit, builds the `prime-kernels` wheels and
|
||||
attaches them to the draft, then promotes it.
|
||||
|
||||
Release notes live on the GitHub Release, not in the repo. Prime-rl is **not** on PyPI. `.dev` tags are handled separately by `devx_tag.yaml`; `tag-and-release.yaml` ignores them.
|
||||
|
||||
@@ -64,6 +65,19 @@ gh pr create --draft --title "chore: release $NEW" --body "Bumps version to ${NE
|
||||
|
||||
Stop. Do not tag, push tags, or flip the draft to published — the workflow does that on merge.
|
||||
|
||||
## 5. After it publishes: move the kernel pin
|
||||
|
||||
The release now carries `prime_kernels-*.whl` for x86_64 and aarch64. Point installs at them
|
||||
so nobody compiles CUDA, in a follow-up PR:
|
||||
|
||||
```bash
|
||||
gh release view "$NEW" --json assets --jq '.assets[].name' # exact filenames, ABI and all
|
||||
```
|
||||
|
||||
Update the `prime-kernels` URLs under `[tool.uv.sources]` in `pyproject.toml` to `$NEW`, then
|
||||
`uv sync --all-extras` to relock. The pin always trails one release — `$NEW`'s wheels do not
|
||||
exist until `$NEW` is built. See the `kernels` skill.
|
||||
|
||||
## Recovery
|
||||
|
||||
If the workflow tagged the commit but failed to promote the draft, the next main push (or `workflow_dispatch` with `tag: v{new}`) re-promotes it.
|
||||
If the workflow tagged the commit but failed to promote the draft, the next main push (or `workflow_dispatch` with `tag: v{new}`) re-promotes it. A rerun rebuilds and re-uploads the kernel wheels (`--clobber`), which is harmless.
|
||||
|
||||
@@ -58,7 +58,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the run dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
|
||||
- `{run_dir}/configs/` — resolved configs, written as JSON so explicit None settings round-trip (`rl.json` has the full picture).
|
||||
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
|
||||
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
|
||||
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
|
||||
|
||||
### Logs
|
||||
|
||||
@@ -130,7 +130,8 @@ All metrics print to the console log (and W&B when configured).
|
||||
| trainer | `perf/throughput`, `perf/mfu` | tokens/s and MFU % |
|
||||
| orchestrator | `time/step`, `time/save_ckpt` | phase timings |
|
||||
| orchestrator | `time/wait_for_policy` | **high → trainer is bottleneck** |
|
||||
| orchestrator | `dispatcher/off_policy_level/{mean,max}`, `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
|
||||
| orchestrator | `dispatcher/off_policy/{mean,max}`, `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
|
||||
| orchestrator | `off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`, `off_policy/dropped` | per-step staleness of trained rollouts |
|
||||
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
|
||||
|
||||
For live vLLM stats, query Prometheus directly:
|
||||
@@ -152,7 +153,7 @@ JSONL files of native `vf.Episode` records (training tensors excluded), one line
|
||||
curriculum-rejected work, and work that never enters a batch — so it is crash-durable.
|
||||
`effective` contains the admitted clean trainable traces grouped into their original episodes
|
||||
(eval: the non-errored trainable epoch cohort). Each record carries its provenance at the
|
||||
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group_id`,
|
||||
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
|
||||
and `run`. Training-run records discriminate train/eval work and include dispatch
|
||||
step plus an optional live-policy version span. Traces retain their own task,
|
||||
verifiers, agent, and runtime fields.
|
||||
|
||||
@@ -9,7 +9,7 @@ All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/t
|
||||
|
||||
## Run directories
|
||||
|
||||
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, weights, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
|
||||
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
|
||||
|
||||
## Config system at a glance
|
||||
|
||||
@@ -92,7 +92,7 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
|
||||
## `evals` — multi-env evals
|
||||
|
||||
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`weights_dir`, `max_steps`, `resume_step`): watch the weights dir for stable `step_{n}` HF checkpoints and evaluate each — the `sft` launcher writes this config for online evals.
|
||||
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
|
||||
@@ -114,15 +114,9 @@ max_inflight = 128
|
||||
[[eval.source]]
|
||||
num_examples = 32 # always cap eval size for smokes
|
||||
group_size = 4
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "aime25"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -19,12 +18,10 @@ from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_all_ckpt_steps,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_log_dir,
|
||||
get_step_path,
|
||||
get_weights_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
@@ -66,7 +63,7 @@ def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
|
||||
|
||||
|
||||
def get_ckpt_base(config: SFTConfig) -> Path:
|
||||
"""Where checkpoints and weights live: ``ckpt.output_dir`` when set, else the run dir."""
|
||||
"""Where checkpoints live: ``ckpt.output_dir`` when set, else the run dir."""
|
||||
return (config.ckpt.output_dir if config.ckpt else None) or config.run_dir
|
||||
|
||||
|
||||
@@ -92,8 +89,9 @@ def build_evals_config(config: SFTConfig) -> EvalsConfig:
|
||||
return EvalsConfig(
|
||||
model=config.model.name,
|
||||
eval=eval_config,
|
||||
weight_broadcast=config.weight_broadcast,
|
||||
online=OnlineConfig(
|
||||
weights_dir=get_weights_dir(get_ckpt_base(config)),
|
||||
broadcasts_dir=get_broadcast_dir(config.run_dir),
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(config),
|
||||
),
|
||||
@@ -176,6 +174,11 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
use_nccl_broadcast=(
|
||||
config.eval is not None
|
||||
and config.weight_broadcast is not None
|
||||
and config.weight_broadcast.type == "nccl"
|
||||
),
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -226,6 +229,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -235,9 +239,8 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
def sft_slurm(config: SFTConfig):
|
||||
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
|
||||
trainer and the eval deployment (inference pool + evals) are two independent
|
||||
SLURM jobs: the handoff is weight checkpoints on the shared filesystem, so the
|
||||
trainer job releases its allocation when training finishes while the eval job
|
||||
keeps draining evals and exits after the final checkpoint."""
|
||||
SLURM jobs. The trainer publishes its rank-0 hostname through the shared run
|
||||
directory so the eval deployment can join its NCCL weight-broadcast group."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
@@ -252,7 +255,7 @@ def sft_slurm(config: SFTConfig):
|
||||
else {"slurm", "dry_run", "clean"}
|
||||
)
|
||||
if decoupled_eval:
|
||||
# The trainer job only needs [eval] for the weight-checkpoint cadence; the
|
||||
# The trainer job only needs [eval] for the weight-broadcast cadence; the
|
||||
# inference pool lives in the eval job.
|
||||
exclude = exclude | {"inference"}
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
@@ -298,9 +301,19 @@ def sft_slurm(config: SFTConfig):
|
||||
).removeprefix("Logs:\n")
|
||||
|
||||
if config.dry_run:
|
||||
submit = "\n".join(f" sbatch {path}" for path in script_paths)
|
||||
if decoupled_eval:
|
||||
trainer_submit = f" TRAIN_JOB_ID=$(sbatch --parsable {script_paths[0]} | cut -d';' -f1)"
|
||||
eval_submit = f" sbatch --dependency=after:$TRAIN_JOB_ID {script_paths[1]}"
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
eval_submit = (
|
||||
" sbatch --dependency=after:$TRAIN_JOB_ID "
|
||||
f"--export=ALL,TRAIN_JOB_ID=$TRAIN_JOB_ID {script_paths[1]}"
|
||||
)
|
||||
submit = "\n".join((trainer_submit, eval_submit))
|
||||
else:
|
||||
submit = f" sbatch {script_paths[0]}"
|
||||
note = (
|
||||
"\n\nSubmit the trainer job first — the evals process joins the W&B run the trainer creates."
|
||||
"\n\nSubmit the trainer job first. The eval job starts after the trainer allocation is ready."
|
||||
if decoupled_eval
|
||||
else ""
|
||||
)
|
||||
@@ -315,6 +328,8 @@ def sft_slurm(config: SFTConfig):
|
||||
if submitted_job_ids:
|
||||
# Hold the eval job until the trainer job has started (not finished).
|
||||
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
cmd.append(f"--export=ALL,TRAIN_JOB_ID={submitted_job_ids[-1]}")
|
||||
cmd.append(str(path))
|
||||
logger.info(f"Submitting: {' '.join(cmd)}")
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
@@ -535,29 +550,28 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
|
||||
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
|
||||
"""Remove eval artifacts a previous run left behind: weight checkpoints and rollout
|
||||
"""Remove eval artifacts a previous run left behind: weight broadcasts and rollout
|
||||
trace dirs — everything on a fresh start, steps past the resume step on resume.
|
||||
Without this the evals process would replay stale checkpoints (and then skip the
|
||||
Without this the evals process would replay stale broadcasts (and then skip the
|
||||
re-trained ones at the same steps), and the append-only trace files would mix two
|
||||
policies' rollouts under one step."""
|
||||
logger = setup_logger(config.log.level or "info")
|
||||
if os.environ.get("NEVER_CLEAN"):
|
||||
logger.warning("NEVER_CLEAN is set - keeping stale weight checkpoints; the evals process may replay them")
|
||||
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the evals process may replay them")
|
||||
return
|
||||
resume_step = resolve_resume_step(config)
|
||||
weights_dir = get_weights_dir(get_ckpt_base(config))
|
||||
stale_steps = [step for step in get_all_ckpt_steps(weights_dir) if resume_step is None or step > resume_step]
|
||||
if stale_steps:
|
||||
logger.info(
|
||||
f"Deleting {len(stale_steps)} stale weight checkpoint(s) in {weights_dir} "
|
||||
f"({','.join(map(str, stale_steps))})"
|
||||
)
|
||||
for step in stale_steps:
|
||||
shutil.rmtree(get_step_path(weights_dir, step), ignore_errors=True)
|
||||
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
|
||||
|
||||
|
||||
def sft(config: SFTConfig):
|
||||
# Launcher-only check: the trainer re-parses a sub-config with [inference] and
|
||||
# [deployment] stripped, so the model validator cannot enforce this.
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl" and config.inference is None:
|
||||
raise ValueError(
|
||||
"NCCL weight broadcast requires launcher-managed inference. "
|
||||
"Add an [inference] block or set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
|
||||
# The run identity is runtime-only, never sub-config: $PRL_RUN_ID / $PRL_RUN_NAME are
|
||||
# the vehicle for runtime info between processes, and every spawned process inherits
|
||||
# them. Components launched standalone have no run identity.
|
||||
|
||||
+79
-37
@@ -2,12 +2,11 @@
|
||||
|
||||
Standalone (no ``[online]``), it runs one epoch of every configured eval
|
||||
source against the weights the inference server currently serves, then exits.
|
||||
With ``[online]``, it watches a weights directory for new HF checkpoints —
|
||||
the trainer writes ``weights/step_{n}`` with a ``STABLE`` marker on
|
||||
completion — tells the inference server to reload each eligible checkpoint
|
||||
from disk (``/update_weights``, no NCCL rendezvous), and runs the configured
|
||||
evals against the updated weights, sequentially per checkpoint so every epoch
|
||||
measures exactly one policy version.
|
||||
With ``[online]``, it watches a broadcasts directory for new weight
|
||||
broadcasts — the trainer writes ``broadcasts/step_{n}`` with a ``STABLE``
|
||||
marker on completion — tells the inference server to receive each eligible
|
||||
broadcast, and runs the configured evals against the updated weights,
|
||||
sequentially per broadcast so every epoch measures exactly one policy version.
|
||||
|
||||
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
|
||||
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
|
||||
@@ -44,7 +43,7 @@ from prime_rl.orchestrator.patches import (
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import EvalBatch, Policy
|
||||
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.client import InferencePool, init_nccl_broadcast
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir, get_step_path
|
||||
@@ -54,16 +53,21 @@ from prime_rl.utils.utils import clean_exit
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
|
||||
# How often to re-scan the weights directory for new checkpoints.
|
||||
# How often to re-scan the broadcasts directory for new weight broadcasts.
|
||||
POLL_INTERVAL_S = 2.0
|
||||
|
||||
# Served model name for adapter broadcasts of LoRA runs. Reloading the same name
|
||||
# with fresh weights each step is supported (the server forces an in-place
|
||||
# reload, see /load_lora_adapter).
|
||||
LORA_NAME = "eval-adapter"
|
||||
|
||||
|
||||
class Evals:
|
||||
def __init__(self, config: EvalsConfig) -> None:
|
||||
self.config = config
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
mode = f"online (weights_dir={config.online.weights_dir})" if config.online is not None else "standalone"
|
||||
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
|
||||
get_logger().info(f"Starting evals ({mode})")
|
||||
|
||||
# The last weight-checkpoint step already handled (evaluated or skipped).
|
||||
@@ -104,6 +108,18 @@ class Evals:
|
||||
await self.pool.wait_for_ready(config.model)
|
||||
get_logger().success("Inference pool ready")
|
||||
|
||||
weight_broadcast = config.weight_broadcast
|
||||
if weight_broadcast is not None and weight_broadcast.type == "nccl":
|
||||
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
|
||||
await init_nccl_broadcast(
|
||||
self.pool.admin_clients,
|
||||
weight_broadcast.host,
|
||||
weight_broadcast.port,
|
||||
weight_broadcast.timeout,
|
||||
inference_world_size=weight_broadcast.inference_world_size,
|
||||
quantize_in_weight_transfer=weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
|
||||
is_resumed = config.online is not None and config.online.resume_step is not None
|
||||
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
|
||||
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
|
||||
@@ -221,7 +237,7 @@ class Evals:
|
||||
get_logger().success("Evals finished!")
|
||||
|
||||
async def watch(self) -> None:
|
||||
"""Online mode: evaluate each eligible weight checkpoint as it appears."""
|
||||
"""Online mode: evaluate each eligible weight broadcast as it appears."""
|
||||
config = self.config
|
||||
assert config.online is not None
|
||||
online = config.online
|
||||
@@ -233,39 +249,58 @@ class Evals:
|
||||
await self.maybe_run_evals(step=0)
|
||||
elif config.eval.retrigger_on_resume:
|
||||
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
|
||||
# evals). Requires the resume step's weights on disk. The final checkpoint
|
||||
# force-fires every env, exactly like the watch loop below.
|
||||
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
|
||||
await self.maybe_run_evals(step=online.resume_step, reload_weights=True, force=is_final)
|
||||
# evals). The trainer rebroadcasts the resumed policy on startup, but only
|
||||
# after loading the model — wait for that broadcast instead of checking
|
||||
# once. A newer stable broadcast means the resume step's was already
|
||||
# cleaned away (only the newest is kept) and can never reappear. The
|
||||
# final broadcast force-fires every env, exactly like the watch loop below.
|
||||
assert online.broadcasts_dir is not None and online.resume_step is not None
|
||||
while True:
|
||||
if (get_step_path(online.broadcasts_dir, online.resume_step) / "STABLE").exists():
|
||||
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
|
||||
await self.maybe_run_evals(step=online.resume_step, reload_weights=True, force=is_final)
|
||||
break
|
||||
newer_stable = any(
|
||||
step > online.resume_step and (get_step_path(online.broadcasts_dir, step) / "STABLE").exists()
|
||||
for step in get_all_ckpt_steps(online.broadcasts_dir)
|
||||
)
|
||||
if newer_stable:
|
||||
get_logger().warning(
|
||||
f"Broadcast for resume step {online.resume_step} was cleaned before it could be "
|
||||
"re-evaluated (broadcast cleaning outpaced the evals process) - skipping the retrigger"
|
||||
)
|
||||
break
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
get_logger().info(f"Watching {online.weights_dir} for new weight checkpoints (max_steps={online.max_steps})")
|
||||
get_logger().info(f"Watching {online.broadcasts_dir} for new weight broadcasts (max_steps={online.max_steps})")
|
||||
while True:
|
||||
assert online.weights_dir is not None # resolved by the config validator
|
||||
steps = get_all_ckpt_steps(online.weights_dir)
|
||||
stable = {step: (get_step_path(online.weights_dir, step) / "STABLE").exists() for step in steps}
|
||||
assert online.broadcasts_dir is not None # resolved by the config validator
|
||||
steps = get_all_ckpt_steps(online.broadcasts_dir)
|
||||
stable = {step: (get_step_path(online.broadcasts_dir, step) / "STABLE").exists() for step in steps}
|
||||
newest_stable = max((step for step in steps if stable[step]), default=None)
|
||||
# Also walk eval-due steps that are no longer on disk: checkpoint cleaning
|
||||
# (ckpt.keep_last / keep_interval) can delete a step before this scan sees
|
||||
# it, and a vanished step would otherwise be skipped without a trace.
|
||||
# Also walk eval-due steps that are no longer on disk: broadcast cleaning
|
||||
# (the trainer keeps only the newest broadcast) can delete a step before
|
||||
# this scan sees it, and a vanished step would otherwise be skipped
|
||||
# without a trace.
|
||||
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_stable)):
|
||||
if step <= self.last_step:
|
||||
continue
|
||||
if step not in stable:
|
||||
get_logger().warning(
|
||||
f"Weight checkpoint for eval step {step} was deleted before it could be "
|
||||
"evaluated (checkpoint cleaning outpaced the evals process) - skipping its evals"
|
||||
f"Weight broadcast for eval step {step} was deleted before it could be "
|
||||
"evaluated (broadcast cleaning outpaced the evals process) - skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
if not stable[step]:
|
||||
# The trainer writes checkpoints in ascending order, so a marker-less
|
||||
# The trainer writes broadcasts in ascending order, so a marker-less
|
||||
# step below a stable one is an abandoned partial write (e.g. a crash
|
||||
# mid-save), not one in progress — skip it instead of wedging on it.
|
||||
if newest_stable is None or newest_stable < step:
|
||||
break # still being written — later steps can't be ready either
|
||||
get_logger().warning(
|
||||
f"Weight checkpoint step {step} has no STABLE marker but newer stable "
|
||||
"checkpoints exist - treating it as abandoned and skipping its evals"
|
||||
f"Weight broadcast step {step} has no STABLE marker but newer stable "
|
||||
"broadcasts exist - treating it as abandoned and skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
@@ -276,9 +311,10 @@ class Evals:
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
|
||||
"""Eval-due steps up to the newest stable checkpoint that are missing from the
|
||||
weights dir — the trainer wrote them (it saves at every due step), so their
|
||||
absence means checkpoint cleaning removed them before they were evaluated."""
|
||||
"""Eval-due steps up to the newest stable broadcast that are missing from the
|
||||
broadcasts dir — the trainer wrote them (it broadcasts at every due step), so
|
||||
their absence means broadcast cleaning removed them before they were
|
||||
evaluated."""
|
||||
if newest_stable is None:
|
||||
return set()
|
||||
due = {
|
||||
@@ -292,10 +328,10 @@ class Evals:
|
||||
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
|
||||
reloading the inference weights first. No-op when no env is due."""
|
||||
if reload_weights:
|
||||
assert self.config.online is not None and self.config.online.weights_dir is not None
|
||||
weight_dir = get_step_path(self.config.online.weights_dir, step)
|
||||
if not (weight_dir / "STABLE").exists():
|
||||
get_logger().warning(f"No stable weight checkpoint for step {step} ({weight_dir}) - skipping eval")
|
||||
assert self.config.online is not None and self.config.online.broadcasts_dir is not None
|
||||
broadcast_dir = get_step_path(self.config.online.broadcasts_dir, step)
|
||||
if not (broadcast_dir / "STABLE").exists():
|
||||
get_logger().warning(f"No stable weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
|
||||
self.last_step = max(self.last_step, step)
|
||||
return
|
||||
|
||||
@@ -313,16 +349,22 @@ class Evals:
|
||||
)
|
||||
|
||||
if reload_weights:
|
||||
get_logger().info(f"Updating inference weights to checkpoint step {step} ({weight_dir})")
|
||||
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
|
||||
# LoRA runs broadcast the raw adapter; load it under a fixed adapter name
|
||||
# and serve the evals against that name (mirrors WeightWatcher).
|
||||
lora_name = LORA_NAME if (broadcast_dir / "adapter_config.json").exists() else None
|
||||
try:
|
||||
await self.pool.update_weights(weight_dir, step=step)
|
||||
await self.pool.update_weights(broadcast_dir, lora_name=lora_name, step=step)
|
||||
except Exception as exc:
|
||||
# Skip this step instead of killing the run; drain the queued examples
|
||||
# so they don't leak into a later epoch with the wrong eval_step.
|
||||
while self.eval_source.next_example() is not None:
|
||||
# so they don't leak into a later epoch with the wrong step.
|
||||
while self.eval_source.next_task() is not None:
|
||||
pass
|
||||
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
|
||||
return
|
||||
if lora_name is not None:
|
||||
self.pool.update_model_name(lora_name)
|
||||
self.policy.model_name = lora_name
|
||||
|
||||
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
|
||||
# between the trigger above and the weight reload completing.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
|
||||
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`):
|
||||
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
|
||||
|
||||
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
|
||||
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``) — each named class owns
|
||||
@@ -55,7 +55,7 @@ def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm
|
||||
cls = ALGORITHM_CLASSES[config.type]
|
||||
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
|
||||
# The Algorithm is the runtime of the algorithm config's training signal
|
||||
# (its sibling Sampler interprets the sampling half). Every algorithm is
|
||||
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
|
||||
# handed the live policy pool — opsd self-distills against it, others may
|
||||
# judge against it or ignore it. Other models (a frozen teacher, a hint
|
||||
# renderer) are built from the algorithm's own config in setup().
|
||||
|
||||
@@ -7,21 +7,20 @@
|
||||
once.
|
||||
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
|
||||
- Emit-everything invariant: every dispatched episode eventually reaches
|
||||
``out_q`` exactly once. Failures remain episode errors;
|
||||
sinks decide drop / partial-train policy.
|
||||
``out_q`` exactly once — as a native episode, or covered by its group's
|
||||
single ``GroupCancellation`` message when the group is dropped. Failures
|
||||
remain episode errors; sinks decide drop / partial-train policy.
|
||||
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
source's emptiness), so in-flight episodes of the opposite kind drain
|
||||
naturally on either side of an eval boundary.
|
||||
- ``on_version_pending`` (called by the watcher before the engines pause for
|
||||
the weight update) bumps ``off_policy_steps`` on in-flight train episodes and
|
||||
drops groups past ``max_off_policy_steps``.
|
||||
Eval rollouts are measurements for the policy version they started with,
|
||||
so they are allowed to finish even if training advances. Train rollouts
|
||||
sampled from a frozen model never age — their sampler doesn't change
|
||||
with policy updates.
|
||||
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
|
||||
count-to-``group_size`` finalization still fires.
|
||||
the weight update) drops train groups already past ``max_off_policy_steps`` — a
|
||||
compute-saving early cancel; the sink's queue sweep is what guarantees the
|
||||
bound. Eval episodes are measurements for the policy version they started
|
||||
with, so they are allowed to finish even if training advances. Train
|
||||
episodes sampled from a frozen model never go stale — their generation
|
||||
source doesn't change with policy updates.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,7 +33,7 @@ from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum, auto
|
||||
from typing import Any, Literal
|
||||
from typing import Literal
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from aiolimiter import AsyncLimiter
|
||||
@@ -43,12 +42,16 @@ from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
CancelReason,
|
||||
DispatchResult,
|
||||
GroupCancellation,
|
||||
GroupState,
|
||||
InflightEpisode,
|
||||
Policy,
|
||||
Progress,
|
||||
WorkKind,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import min_fresh_version
|
||||
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import get_logger
|
||||
@@ -127,7 +130,7 @@ def _trace_task(task: vf.Task) -> vf.TraceTask:
|
||||
)
|
||||
|
||||
|
||||
def _validate_episode_task(episode: vf.Episode[Any, Any, Any], task: vf.Task) -> None:
|
||||
def _validate_episode_task(episode: vf.WireEpisode, task: vf.Task) -> None:
|
||||
expected = (task.key, task.hash)
|
||||
actual = (episode.task.key, episode.task.hash)
|
||||
if actual != expected:
|
||||
@@ -138,7 +141,7 @@ class Dispatcher:
|
||||
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
|
||||
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules episodes
|
||||
under shared capacity, and emits native verifier episodes to ``out_q``.
|
||||
The watcher drives ``on_version_pending`` for off-policy
|
||||
The watcher drives ``on_version_pending`` for staleness
|
||||
cancellation; the orchestrator triggers eval epochs."""
|
||||
|
||||
def __init__(
|
||||
@@ -163,7 +166,7 @@ class Dispatcher:
|
||||
self.progress = progress
|
||||
self.train_envs = train_envs
|
||||
self.eval_envs = eval_envs
|
||||
# Train rollouts go to the env sampler's pool; eval always
|
||||
# Train rollouts go to the env's generation source; eval always
|
||||
# evaluates the policy.
|
||||
self.policy_pool = policy_pool
|
||||
self.train_source = train_source
|
||||
@@ -199,9 +202,9 @@ class Dispatcher:
|
||||
# Bounded so the dispatcher backpressures on a slow sink (unbounded
|
||||
# when no hard ceiling is configured — the dynamic cap still bounds
|
||||
# in-flight work). One entry per episode — the sinks count episodes,
|
||||
# never loose traces.
|
||||
# never loose traces — plus one ``GroupCancellation`` per dropped group.
|
||||
maxsize = max(8, max_inflight_ceiling) if max_inflight_ceiling is not None else 0
|
||||
self.out_q: asyncio.Queue[vf.Episode[Any, Any, Any]] = asyncio.Queue(maxsize=maxsize)
|
||||
self.out_q: asyncio.Queue[DispatchResult] = asyncio.Queue(maxsize=maxsize)
|
||||
|
||||
self.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
|
||||
# Set by the orchestrator after the final train step; pipeline then
|
||||
@@ -218,14 +221,14 @@ class Dispatcher:
|
||||
self.stopped = asyncio.Event()
|
||||
self.task: asyncio.Task | None = None
|
||||
|
||||
def _train_pool_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
|
||||
def _train_generation_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
|
||||
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
|
||||
the env sampler's pool. (Eval always uses the policy.)"""
|
||||
eval always uses the policy."""
|
||||
assert self.train_envs is not None # train groups only exist when train is configured
|
||||
sampler = self.train_envs.get(env_name).sampler
|
||||
if sampler.samples_from_live_policy:
|
||||
return sampler.pool, self.policy.model_name, True
|
||||
return sampler.pool, sampler.pool.model_name, False
|
||||
source = self.train_envs.get(env_name).generation_source
|
||||
if source.uses_live_policy:
|
||||
return source.pool, self.policy.model_name, True
|
||||
return source.pool, source.pool.model_name, False
|
||||
|
||||
@property
|
||||
def inflight_train_count(self) -> int:
|
||||
@@ -267,9 +270,9 @@ class Dispatcher:
|
||||
if shed >= n:
|
||||
break
|
||||
# Count only live cancellations toward the excess: drop_group's
|
||||
# return includes never-dispatched markers, which free no permits
|
||||
# return includes never-dispatched episodes, which free no permits
|
||||
live = sum(1 for meta in self.inflight.values() if meta.group_id == group_id)
|
||||
await self.drop_group(group_id)
|
||||
await self.drop_group(group_id, reason="overload")
|
||||
shed += live
|
||||
if shed:
|
||||
get_logger().warning(f"Cancelled {shed} youngest in-flight episodes after overload cut")
|
||||
@@ -315,15 +318,17 @@ class Dispatcher:
|
||||
triggered eval drain naturally."""
|
||||
self.train_scheduling_disabled = True
|
||||
|
||||
@property
|
||||
def max_off_policy_level(self) -> int:
|
||||
steps = [m.off_policy_steps for m in self.inflight.values() if m.kind == "train"]
|
||||
return max(steps) if steps else 0
|
||||
|
||||
@property
|
||||
def mean_off_policy_level(self) -> float:
|
||||
steps = [m.off_policy_steps for m in self.inflight.values() if m.kind == "train"]
|
||||
return sum(steps) / len(steps) if steps else 0.0
|
||||
def inflight_staleness(self) -> list[int]:
|
||||
"""Current staleness of each in-flight live-sourced train episode: the
|
||||
version the batch being collected trains on (v{step-1}) minus the
|
||||
episode's dispatch version."""
|
||||
if self.train_envs is None or self.progress is None:
|
||||
return []
|
||||
return [
|
||||
(self.progress.step - 1) - meta.policy_version
|
||||
for meta in self.inflight.values()
|
||||
if meta.kind == "train" and self.train_envs.get(meta.env_name).generation_source.uses_live_policy
|
||||
]
|
||||
|
||||
# ── lifecycle ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -360,32 +365,32 @@ class Dispatcher:
|
||||
self.task = None
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""Bump off-policy counters and drop groups past
|
||||
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
|
||||
the sink still finalizes the partial group). Eval rollouts are not
|
||||
aged because they are tied to their start-time policy version.
|
||||
"""Drop train groups past ``max_off_policy_steps``: a group dispatched at
|
||||
v{k} ships at earliest in the batch currently collecting, at staleness
|
||||
``(progress.step - 1) - k`` — beyond the bound it can never train, so
|
||||
cut it before more inference sinks in. This is a compute saver; the
|
||||
sink's queue sweep is what guarantees no stale episode ships. Eval
|
||||
groups never go stale (they are tied to their start-time policy
|
||||
version), nor do frozen-sourced train groups (their generation source
|
||||
doesn't change with policy updates).
|
||||
|
||||
Runs *before* the inference engines are paused for the weight update so
|
||||
the resulting aborts are processed while the engine is still stepping —
|
||||
otherwise the orphaned KV transfers crash the decode engine on resume
|
||||
(see ``WeightWatcher.apply_policy_update``)."""
|
||||
stale_groups: set[uuid.UUID] = set()
|
||||
if self.train_envs is None or self.progress is None:
|
||||
return
|
||||
min_version = min_fresh_version(self.progress.step, self.max_off_policy_steps)
|
||||
stale_groups = [
|
||||
gid
|
||||
for gid, group in self.groups.items()
|
||||
if group.kind == "train"
|
||||
and self.train_envs.get(group.env_name).generation_source.uses_live_policy
|
||||
and group.policy_version_at_start < min_version
|
||||
]
|
||||
cancelled = 0
|
||||
for meta in self.inflight.values():
|
||||
if meta.kind != "train":
|
||||
continue
|
||||
# Frozen-sourced rollouts never go stale — their sampler doesn't
|
||||
# change with policy updates.
|
||||
assert self.train_envs is not None
|
||||
if not self.train_envs.get(meta.env_name).sampler.samples_from_live_policy:
|
||||
continue
|
||||
meta.off_policy_steps += 1
|
||||
if meta.off_policy_steps > self.max_off_policy_steps:
|
||||
stale_groups.add(meta.group_id)
|
||||
|
||||
for gid in stale_groups:
|
||||
removed = await self.drop_group(gid)
|
||||
cancelled += removed
|
||||
cancelled += await self.drop_group(gid, reason="stale")
|
||||
|
||||
if cancelled:
|
||||
get_logger().warning(
|
||||
@@ -457,29 +462,29 @@ class Dispatcher:
|
||||
return await self.schedule_group_episode(gid, fresh)
|
||||
|
||||
def next_fresh_group(self, kind: WorkKind, envs) -> GroupState | None:
|
||||
"""Pop the next example from the corresponding source and wrap it in
|
||||
"""Pop the next task from the corresponding source and wrap it in
|
||||
a ``GroupState``. Returns ``None`` if the source is empty."""
|
||||
if kind == "train":
|
||||
assert self.train_source is not None
|
||||
source = self.train_source
|
||||
if self.progress is None:
|
||||
raise RuntimeError("Train dispatch requires progress state")
|
||||
request = self.train_source.next_task(step=self.progress.step)
|
||||
else:
|
||||
assert self.eval_source is not None
|
||||
source = self.eval_source
|
||||
example = source.next_example()
|
||||
if example is None:
|
||||
request = self.eval_source.next_task()
|
||||
if request is None:
|
||||
return None
|
||||
|
||||
env_name = example["env_name"]
|
||||
env_name = request.env_name
|
||||
group_size = envs.get(env_name).config.group_size
|
||||
eval_step: int | None = example.get("eval_step") if kind == "eval" else None
|
||||
|
||||
return GroupState(
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
task=example["task"],
|
||||
task=request.task,
|
||||
step=request.step,
|
||||
episodes_to_schedule=group_size,
|
||||
target_episodes=group_size,
|
||||
eval_step=eval_step,
|
||||
policy_version_at_start=self.policy.version,
|
||||
)
|
||||
|
||||
@@ -490,7 +495,7 @@ class Dispatcher:
|
||||
ready, no permits). Returns True after issuing one task — the caller
|
||||
loops to keep scheduling.
|
||||
"""
|
||||
# Train rollouts use the env sampler's pool via the
|
||||
# Train rollouts use the env's generation source via the
|
||||
# renderer/token train client. Eval always evaluates the policy and
|
||||
# goes through the eval client (chat-completions) so eval scores stay
|
||||
# comparable.
|
||||
@@ -498,7 +503,7 @@ class Dispatcher:
|
||||
pool, model_name = self.policy_pool, self.policy.model_name
|
||||
live_sourced = True
|
||||
else:
|
||||
pool, model_name, live_sourced = self._train_pool_for(group.env_name)
|
||||
pool, model_name, live_sourced = self._train_generation_for(group.env_name)
|
||||
|
||||
if group.pinned_client is None:
|
||||
group.pinned_client = pool.eval_client if group.kind == "eval" else pool.train_client
|
||||
@@ -534,21 +539,12 @@ class Dispatcher:
|
||||
group_id=group_id,
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start,
|
||||
step=self._work_step(group.kind, group.eval_step),
|
||||
step=group.step,
|
||||
client_config=client,
|
||||
eval_step=group.eval_step,
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
return True
|
||||
|
||||
def _work_step(self, kind: WorkKind, eval_step: int | None) -> int:
|
||||
if kind == "eval":
|
||||
assert eval_step is not None
|
||||
return eval_step
|
||||
if self.progress is None:
|
||||
raise RuntimeError("Train dispatch requires progress state")
|
||||
return self.progress.step
|
||||
|
||||
async def acquire(self) -> None:
|
||||
"""Reserve one permit + rate-limit it. Caller must precheck
|
||||
``available_permits >= 1``; this is not a blocking acquire."""
|
||||
@@ -574,7 +570,7 @@ class Dispatcher:
|
||||
|
||||
is_synth_exception = False
|
||||
try:
|
||||
episode: vf.Episode[Any, Any, Any] = task.result()
|
||||
episode: vf.WireEpisode = task.result()
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except Exception as exc:
|
||||
@@ -624,27 +620,23 @@ class Dispatcher:
|
||||
self,
|
||||
meta: InflightEpisode,
|
||||
group: GroupState | None,
|
||||
episode: vf.Episode[Any, Any, Any],
|
||||
episode: vf.WireEpisode,
|
||||
) -> None:
|
||||
"""Stamp one completed episode with its dispatch provenance and emit it."""
|
||||
_validate_episode_task(episode, meta.task)
|
||||
eval_step = meta.eval_step
|
||||
policy_version = meta.policy_version
|
||||
if group is not None:
|
||||
eval_step = group.eval_step
|
||||
policy_version = group.policy_version_at_start
|
||||
group.emitted += 1
|
||||
if group.emitted >= group.target_episodes:
|
||||
self.groups.pop(meta.group_id, None)
|
||||
|
||||
if meta.kind == "eval":
|
||||
assert eval_step is not None, "eval episode missing eval_step"
|
||||
episode.env.name = meta.env_name
|
||||
episode.group = vf.GroupInfo(id=str(meta.group_id))
|
||||
live_policy = meta.kind == "eval"
|
||||
if meta.kind == "train":
|
||||
assert self.train_envs is not None
|
||||
live_policy = self.train_envs.get(meta.env_name).sampler.samples_from_live_policy
|
||||
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
|
||||
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
|
||||
work: vf.WorkInfo = (
|
||||
vf.EvalWorkInfo(step=meta.step, policy=policy)
|
||||
@@ -655,11 +647,11 @@ class Dispatcher:
|
||||
episode.record_run(run)
|
||||
await self.out_q.put(episode)
|
||||
|
||||
async def drop_group(self, group_id: uuid.UUID) -> int:
|
||||
"""Cancel remaining in-flight tasks for this group and emit a
|
||||
``Cancelled`` marker for every rollout it still owes the sink
|
||||
(both in-flight and not-yet-scheduled). Returns the count for
|
||||
off-policy metrics."""
|
||||
async def drop_group(self, group_id: uuid.UUID, *, reason: CancelReason) -> int:
|
||||
"""Cancel this group's remaining in-flight tasks and emit one
|
||||
``GroupCancellation`` covering every episode it still owes the sink (both
|
||||
in-flight and never-dispatched), so count-to-``group_size``
|
||||
finalization still fires. Returns the owed count for metrics."""
|
||||
group = self.groups.pop(group_id, None)
|
||||
# Sync claim phase: pop matching tasks from ``self.inflight`` and
|
||||
# release their permits in one non-yielding sweep. After this loop
|
||||
@@ -674,69 +666,33 @@ class Dispatcher:
|
||||
self.release()
|
||||
claimed.append((task, meta))
|
||||
|
||||
tasks_to_cancel = [task for task, _ in claimed]
|
||||
inflight_cancelled = len(claimed)
|
||||
last_meta: InflightEpisode | None = claimed[-1][1] if claimed else None
|
||||
for _, meta in claimed:
|
||||
episode = vf.WireEpisode(
|
||||
env=vf.EnvInfo(id=meta.env_name),
|
||||
task=_trace_task(meta.task),
|
||||
ok=False,
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
)
|
||||
await self.emit_episode(meta, group, episode)
|
||||
|
||||
# The group may have episodes that were never dispatched. Emit markers
|
||||
# for those too so the sink reaches ``target_episodes``.
|
||||
#
|
||||
# ``last_meta`` can be ``None`` if the only inflight task for this
|
||||
# group completed naturally between ``on_version_pending``'s snapshot
|
||||
# and us reaching it — synthesize a stand-in from the group state
|
||||
unscheduled_cancelled = 0
|
||||
if group is not None and group.episodes_to_schedule > 0:
|
||||
fallback_meta = last_meta or InflightEpisode(
|
||||
kind=group.kind,
|
||||
env_name=group.env_name,
|
||||
group_id=group_id,
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start,
|
||||
step=self._work_step(group.kind, group.eval_step),
|
||||
eval_step=group.eval_step,
|
||||
)
|
||||
unscheduled_cancelled = group.episodes_to_schedule
|
||||
for _ in range(unscheduled_cancelled):
|
||||
episode = vf.WireEpisode(
|
||||
env=vf.EnvInfo(id=group.env_name),
|
||||
task=_trace_task(group.task),
|
||||
ok=False,
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
)
|
||||
await self.emit_episode(fallback_meta, group, episode)
|
||||
|
||||
unscheduled_cancelled = group.episodes_to_schedule if group is not None else 0
|
||||
cancelled = inflight_cancelled + unscheduled_cancelled
|
||||
if cancelled > 0:
|
||||
meta_for_log = last_meta or (
|
||||
InflightEpisode(
|
||||
kind=group.kind,
|
||||
env_name=group.env_name,
|
||||
group_id=group_id,
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start if group else 0,
|
||||
step=self._work_step(group.kind, group.eval_step),
|
||||
eval_step=group.eval_step,
|
||||
)
|
||||
if group is not None
|
||||
else None
|
||||
)
|
||||
if meta_for_log is not None:
|
||||
self.metrics.record_cancellation(kind=meta_for_log.kind, env_name=meta_for_log.env_name, n=cancelled)
|
||||
get_logger().debug(
|
||||
f"drain {meta_for_log.kind} | group={str(group_id)[:8]} env={meta_for_log.env_name} | "
|
||||
f"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
|
||||
)
|
||||
|
||||
if tasks_to_cancel:
|
||||
await safe_cancel_all(tasks_to_cancel)
|
||||
if cancelled > 0:
|
||||
# ``group`` can be ``None`` only if every episode was already
|
||||
# emitted — then nothing is in flight or unscheduled, so kind/env
|
||||
# always resolve from the group or a claimed meta.
|
||||
kind = group.kind if group is not None else claimed[-1][1].kind
|
||||
env_name = group.env_name if group is not None else claimed[-1][1].env_name
|
||||
self.metrics.record_cancellation(kind=kind, env_name=env_name, n=cancelled)
|
||||
get_logger().debug(
|
||||
f"drop {kind} | group={str(group_id)[:8]} env={env_name} reason={reason} | "
|
||||
f"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
|
||||
)
|
||||
await self.out_q.put(
|
||||
GroupCancellation(
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
group_id=str(group_id),
|
||||
count=cancelled,
|
||||
reason=reason,
|
||||
)
|
||||
)
|
||||
|
||||
if claimed:
|
||||
await safe_cancel_all([task for task, _ in claimed])
|
||||
return cancelled
|
||||
|
||||
async def cancel_inflight_episodes(self) -> None:
|
||||
@@ -777,11 +733,12 @@ class Dispatcher:
|
||||
|
||||
def gauges(self) -> dict[str, float]:
|
||||
"""Instantaneous, read-only gauges sampled by the periodic logger."""
|
||||
staleness = self.inflight_staleness()
|
||||
return {
|
||||
"dispatcher/inflight/train": float(self.inflight_train_count),
|
||||
"dispatcher/inflight/eval": float(self.inflight_eval_count),
|
||||
"dispatcher/queued/eval": float(self.queued_eval_examples),
|
||||
"dispatcher/mode": float(self.mode == DispatcherMode.PREFER_EVAL),
|
||||
"dispatcher/off_policy_level/max": float(self.max_off_policy_level),
|
||||
"dispatcher/off_policy_level/mean": self.mean_off_policy_level,
|
||||
"dispatcher/off_policy/max": float(max(staleness, default=0)),
|
||||
"dispatcher/off_policy/mean": sum(staleness) / len(staleness) if staleness else 0.0,
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ from verifiers.v1.serve import EnvClient
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
|
||||
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
|
||||
from prime_rl.orchestrator.sampler import Sampler
|
||||
from prime_rl.orchestrator.generation_source import GenerationSource
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# Max wait for the env server to answer health. Generous because the launcher spawns
|
||||
@@ -74,11 +74,11 @@ class Env:
|
||||
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
|
||||
taskset = vf.load_taskset(self.config.env.taskset)
|
||||
if type(taskset).INFINITE:
|
||||
self.tasks = iter(taskset.load())
|
||||
self.tasks = iter(taskset)
|
||||
self.num_tasks = None
|
||||
else:
|
||||
# Materialize off the event loop — load() may pull a dataset.
|
||||
materialized = await asyncio.to_thread(lambda: list(taskset.load()))
|
||||
# Materialize off the event loop — iterating may pull a dataset.
|
||||
materialized = await asyncio.to_thread(lambda: list(taskset))
|
||||
self.tasks = iter(materialized)
|
||||
self.num_tasks = len(materialized)
|
||||
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
|
||||
@@ -118,11 +118,17 @@ class Env:
|
||||
class TrainEnv(Env):
|
||||
config: TrainSourceConfig
|
||||
|
||||
def __init__(self, config: TrainSourceConfig, address: str, sampler: Sampler, algorithm: Algorithm):
|
||||
def __init__(
|
||||
self,
|
||||
config: TrainSourceConfig,
|
||||
address: str,
|
||||
generation_source: GenerationSource,
|
||||
algorithm: Algorithm,
|
||||
):
|
||||
super().__init__(config, address)
|
||||
self.sampler = sampler
|
||||
self.generation_source = generation_source
|
||||
self.algorithm = algorithm
|
||||
self.sampling_args = sampler.sampling_args(config.sampling.to_sampling_args())
|
||||
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
|
||||
|
||||
|
||||
class EvalEnv(Env):
|
||||
@@ -131,7 +137,7 @@ class EvalEnv(Env):
|
||||
def __init__(self, config: EvalSourceConfig, address: str):
|
||||
super().__init__(config, address)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
self.examples: list[dict] = []
|
||||
self.examples: list[vf.Task] = []
|
||||
|
||||
async def start(self) -> None:
|
||||
await super().start()
|
||||
@@ -140,7 +146,7 @@ class EvalEnv(Env):
|
||||
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
|
||||
# A fixed eval set, pulled off the tasks once and reused every epoch.
|
||||
tasks = list(self.tasks) if n < 0 else list(islice(self.tasks, n))
|
||||
self.examples = [{"task": task} for task in tasks]
|
||||
self.examples = tasks
|
||||
|
||||
|
||||
EnvT = TypeVar("EnvT", bound=Env)
|
||||
@@ -175,8 +181,8 @@ class Envs(Generic[EnvT]):
|
||||
|
||||
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
"""Collection of training environments, each paired with its rollout
|
||||
:class:`Sampler` and runtime :class:`Algorithm`, built from the env's
|
||||
"""Collection of training environments, each paired with its
|
||||
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
|
||||
resolved algorithm config."""
|
||||
|
||||
def __init__(
|
||||
@@ -193,7 +199,7 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
env = TrainEnv(
|
||||
config,
|
||||
addresses[("train", config.resolved_name)],
|
||||
Sampler(config.algo.sampling, policy_pool, renderer_config),
|
||||
GenerationSource(config.algo.sampling, policy_pool, renderer_config),
|
||||
build_algorithm(config.algo, policy_pool),
|
||||
)
|
||||
self._envs[env.name] = env
|
||||
|
||||
@@ -86,4 +86,8 @@ class EvalSink:
|
||||
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
|
||||
env_name, step = key
|
||||
episodes = self.pending_batches.pop(key, [])
|
||||
return EvalBatch(env_name=env_name, step=step, episodes=EvalEpisodes(episodes))
|
||||
return EvalBatch(
|
||||
env_name=env_name,
|
||||
step=step,
|
||||
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""EvalSource: trigger-driven, finite-per-epoch pull of eval examples.
|
||||
|
||||
The orchestrator pokes ``trigger(step)`` after each ship + once at
|
||||
startup; the dispatcher pulls via ``next_example()`` until
|
||||
startup; the dispatcher pulls via ``next_task()`` until
|
||||
``bool(source) == False``. Constructed only when eval is configured."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -9,8 +9,11 @@ from __future__ import annotations
|
||||
from collections import deque
|
||||
from itertools import zip_longest
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import EvalConfig
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.types import TaskRequest
|
||||
|
||||
|
||||
class EvalSource:
|
||||
@@ -26,18 +29,13 @@ class EvalSource:
|
||||
self.eval_envs = eval_envs
|
||||
self.eval_config = eval_config
|
||||
|
||||
self.examples_by_env: dict[str, list[dict]] = {}
|
||||
self.tasks_by_env: dict[str, list[vf.Task]] = {}
|
||||
self.intervals: dict[str, int] = {}
|
||||
for env in eval_envs:
|
||||
rows: list[dict] = []
|
||||
for ex in env.examples:
|
||||
row = dict(ex)
|
||||
row["env_name"] = env.name
|
||||
rows.append(row)
|
||||
self.examples_by_env[env.name] = rows
|
||||
self.tasks_by_env[env.name] = list(env.examples)
|
||||
self.intervals[env.name] = env.config.interval
|
||||
|
||||
self.queue: deque[dict] = deque()
|
||||
self.queue: deque[TaskRequest] = deque()
|
||||
|
||||
# On resume we skip the startup eval; on fresh start the first
|
||||
# trigger fires every env (subject to ``skip_first_step``)
|
||||
@@ -59,18 +57,16 @@ class EvalSource:
|
||||
# dispatcher rotates at example granularity. ``try_schedule``'s
|
||||
# continue-group branch still keeps each example's group_size
|
||||
# rollouts back-to-back, so per-example prefix-cache locality holds
|
||||
iters = [iter(self.examples_by_env[name]) for name in fired]
|
||||
for round_examples in zip_longest(*iters):
|
||||
for example in round_examples:
|
||||
if example is None:
|
||||
iters = [iter(self.tasks_by_env[name]) for name in fired]
|
||||
for round_tasks in zip_longest(*iters):
|
||||
for env_name, task in zip(fired, round_tasks, strict=True):
|
||||
if task is None:
|
||||
continue
|
||||
row = dict(example)
|
||||
row["eval_step"] = step
|
||||
self.queue.append(row)
|
||||
self.queue.append(TaskRequest(env_name=env_name, task=task, step=step))
|
||||
return fired
|
||||
|
||||
def next_example(self) -> dict | None:
|
||||
"""Pop the next eval example, or ``None`` when the queue is empty."""
|
||||
def next_task(self) -> TaskRequest | None:
|
||||
"""Pop the next eval task, or ``None`` when the queue is empty."""
|
||||
if not self.queue:
|
||||
return None
|
||||
return self.queue.popleft()
|
||||
|
||||
+6
-14
@@ -1,12 +1,4 @@
|
||||
"""How an env's train rollouts are produced — the sample strategy.
|
||||
|
||||
The algorithm (``algo/``) consumes finalized rollouts and compiles them into
|
||||
per-token loss-component weights; the sampler owns where those rollouts come
|
||||
from. Today that is one question — which model generates them — and its
|
||||
consequences (sampling logprobs, prefix-cache salting, and off-policy
|
||||
staleness are all liveness questions about the source). Future sampling
|
||||
strategies (replay buffers, branching) extend here, not the algorithm.
|
||||
"""
|
||||
"""Resolve the model source used to generate an env's train episodes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -21,8 +13,8 @@ if TYPE_CHECKING:
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
class Sampler:
|
||||
"""One env's rollout source.
|
||||
class GenerationSource:
|
||||
"""One env's generation model and inference pool.
|
||||
|
||||
``pool`` is the pool train rollouts are generated from: the policy pool,
|
||||
swapped for a connected frozen pool in :meth:`setup` when the source is an
|
||||
@@ -40,20 +32,20 @@ class Sampler:
|
||||
self.connected_pools: list[InferencePool] = [] # client pools connected in setup(); closed at shutdown
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Connect a client pool to a frozen sampling source and wait for
|
||||
"""Connect a client pool to a frozen generation source and wait for
|
||||
readiness. Must run before dispatching."""
|
||||
if isinstance(self.config.source, FrozenModelConfig):
|
||||
self.pool = await connect_frozen_pool(self.config.source, renderer_config=self.renderer_config)
|
||||
self.connected_pools.append(self.pool)
|
||||
|
||||
@property
|
||||
def samples_from_live_policy(self) -> bool:
|
||||
def uses_live_policy(self) -> bool:
|
||||
return self.config.source == "policy"
|
||||
|
||||
def sampling_args(self, args: dict) -> dict:
|
||||
"""Source-specific sampling-arg overrides. Sampling logprobs are only
|
||||
needed for importance ratios on policy-sampled tokens — frozen
|
||||
endpoints may reject the knob."""
|
||||
if not self.samples_from_live_policy:
|
||||
if not self.uses_live_policy:
|
||||
args.pop("logprobs", None)
|
||||
return args
|
||||
@@ -16,18 +16,22 @@ Subset = Literal["all", "effective"]
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TraceRecord:
|
||||
"""A trace joined with its episode and training selection state."""
|
||||
"""A trace joined with its episode and training selection state.
|
||||
``cancelled`` marks episodes the pipeline voided (stale drop) — a
|
||||
selection verdict disjoint from trace errors."""
|
||||
|
||||
episode: vf.Episode
|
||||
trace: vf.Trace
|
||||
sampled: bool
|
||||
admitted: bool
|
||||
cancelled: bool
|
||||
|
||||
|
||||
def _records(
|
||||
episodes: list[vf.Episode],
|
||||
sampled_trace_ids: set[str],
|
||||
admitted: set[str],
|
||||
cancelled: set[str],
|
||||
) -> list[TraceRecord]:
|
||||
return [
|
||||
TraceRecord(
|
||||
@@ -35,6 +39,7 @@ def _records(
|
||||
trace=trace,
|
||||
sampled=trace.id in sampled_trace_ids,
|
||||
admitted=episode.id in admitted,
|
||||
cancelled=episode.id in cancelled,
|
||||
)
|
||||
for episode in episodes
|
||||
for trace in episode.traces
|
||||
@@ -202,6 +207,11 @@ class TraceMetrics(StatGroup):
|
||||
def has_error(self) -> Stat:
|
||||
return Stat([float(trace.has_error) for trace in self.traces])
|
||||
|
||||
@property
|
||||
def cancelled(self) -> Stat:
|
||||
"""Pipeline cancellations (stale drop) — disjoint from errors."""
|
||||
return Stat([float(record.cancelled) for record in self.records])
|
||||
|
||||
def stop_conditions(self) -> dict[str, float]:
|
||||
out = {
|
||||
"generation_truncated": sum(
|
||||
@@ -243,6 +253,7 @@ class TraceMetrics(StatGroup):
|
||||
out |= self.rewards.to_dict(f"{prefix}/rewards")
|
||||
if subset == "all":
|
||||
out[f"{prefix}/has_error/mean"] = self.has_error.mean()
|
||||
out[f"{prefix}/cancelled/mean"] = self.cancelled.mean()
|
||||
out |= {f"{prefix}/error/{key}": float(value) for key, value in self.error_types().items()}
|
||||
out |= {f"{prefix}/{key}": value for key, value in self.solve_rates().items()}
|
||||
out |= {f"{prefix}/stop_condition/{key}": value for key, value in self.stop_conditions().items()}
|
||||
@@ -250,9 +261,15 @@ class TraceMetrics(StatGroup):
|
||||
|
||||
|
||||
class EpisodeMetrics:
|
||||
def __init__(self, episodes: list[vf.Episode], records: list[TraceRecord]) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
episodes: list[vf.Episode],
|
||||
records: list[TraceRecord],
|
||||
cancelled: set[str] | None = None,
|
||||
) -> None:
|
||||
self.episodes = episodes
|
||||
self.records = records
|
||||
self.cancelled_ids = cancelled if cancelled is not None else set()
|
||||
|
||||
def by_agent(self) -> dict[str, TraceMetrics]:
|
||||
per_agent: dict[str, list[TraceRecord]] = {}
|
||||
@@ -296,6 +313,14 @@ class EpisodeMetrics:
|
||||
[float(not episode.ok or any(trace.has_error for trace in episode.traces)) for episode in self.episodes]
|
||||
)
|
||||
|
||||
@property
|
||||
def cancelled(self) -> Stat:
|
||||
"""Per-episode pipeline-cancellation rate — same denominator as
|
||||
``has_error``. Read from the id-set, not the trace records, so
|
||||
trace-less episodes (synthetic error episodes inside a voided group)
|
||||
still count."""
|
||||
return Stat([float(episode.id in self.cancelled_ids) for episode in self.episodes])
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
if not self.episodes:
|
||||
return {}
|
||||
@@ -305,6 +330,7 @@ class EpisodeMetrics:
|
||||
out |= getattr(self, name).to_dict(f"{metric_prefix}/{name}")
|
||||
if subset == "all":
|
||||
out[f"{metric_prefix}/has_error/mean"] = self.has_error.mean()
|
||||
out[f"{metric_prefix}/cancelled/mean"] = self.cancelled.mean()
|
||||
for agent, metrics in self.by_agent().items():
|
||||
out |= metrics.to_dict(f"{metric_prefix}/{agent}", subset=subset)
|
||||
return out
|
||||
@@ -368,16 +394,18 @@ class EpisodeCollection:
|
||||
episodes: list[vf.Episode] | None = None,
|
||||
sampled_trace_ids: set[str] | None = None,
|
||||
admitted: set[str] | None = None,
|
||||
cancelled: set[str] | None = None,
|
||||
predicate: Callable[[TraceRecord], bool] | None = None,
|
||||
) -> None:
|
||||
self.episodes = episodes if episodes is not None else []
|
||||
self.sampled_trace_ids = sampled_trace_ids if sampled_trace_ids is not None else set()
|
||||
self.admitted = admitted if admitted is not None else {episode.id for episode in self.episodes}
|
||||
self.cancelled = cancelled if cancelled is not None else set()
|
||||
self._predicate = predicate
|
||||
|
||||
@property
|
||||
def records(self) -> list[TraceRecord]:
|
||||
records = _records(self.episodes, self.sampled_trace_ids, self.admitted)
|
||||
records = _records(self.episodes, self.sampled_trace_ids, self.admitted, self.cancelled)
|
||||
if self._predicate is None:
|
||||
return records
|
||||
return [record for record in records if self._predicate(record)]
|
||||
@@ -420,11 +448,14 @@ class EpisodeCollection:
|
||||
*,
|
||||
sampled_trace_ids: set[str] | None = None,
|
||||
admitted: bool = True,
|
||||
cancelled: bool = False,
|
||||
) -> None:
|
||||
self.episodes.append(episode)
|
||||
self.sampled_trace_ids.update(sampled_trace_ids or set())
|
||||
if admitted:
|
||||
self.admitted.add(episode.id)
|
||||
if cancelled:
|
||||
self.cancelled.add(episode.id)
|
||||
|
||||
def extend(
|
||||
self,
|
||||
@@ -432,11 +463,14 @@ class EpisodeCollection:
|
||||
*,
|
||||
sampled_trace_ids: set[str] | None = None,
|
||||
admitted: bool = True,
|
||||
cancelled: bool = False,
|
||||
) -> None:
|
||||
self.episodes.extend(episodes)
|
||||
self.sampled_trace_ids.update(sampled_trace_ids or set())
|
||||
if admitted:
|
||||
self.admitted.update(episode.id for episode in episodes)
|
||||
if cancelled:
|
||||
self.cancelled.update(episode.id for episode in episodes)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.selected_episodes)
|
||||
@@ -452,8 +486,13 @@ class TrainEpisodes(EpisodeCollection):
|
||||
self.episodes,
|
||||
self.sampled_trace_ids,
|
||||
self.admitted,
|
||||
self.cancelled,
|
||||
predicate=lambda record: (
|
||||
record.admitted and record.sampled and not record.trace.has_error and record.trace.agent.trainable
|
||||
record.admitted
|
||||
and record.sampled
|
||||
and not record.cancelled
|
||||
and not record.trace.has_error
|
||||
and record.trace.agent.trainable
|
||||
),
|
||||
)
|
||||
|
||||
@@ -462,42 +501,31 @@ class TrainEpisodes(EpisodeCollection):
|
||||
for episode in self.selected_episodes:
|
||||
grouped.setdefault(episode_env_name(episode), []).append(episode)
|
||||
return {
|
||||
env_name: TrainEpisodes(episodes, self.sampled_trace_ids, self.admitted, self._predicate)
|
||||
env_name: TrainEpisodes(episodes, self.sampled_trace_ids, self.admitted, self.cancelled, self._predicate)
|
||||
for env_name, episodes in grouped.items()
|
||||
}
|
||||
|
||||
@property
|
||||
def metrics(self) -> TrainMetrics:
|
||||
return TrainMetrics(self.selected_episodes, self.records)
|
||||
return TrainMetrics(self.selected_episodes, self.records, self.cancelled)
|
||||
|
||||
|
||||
class EvalEpisodes(EpisodeCollection):
|
||||
def __init__(
|
||||
self,
|
||||
episodes: list[vf.Episode] | None = None,
|
||||
episodes: list[vf.Episode],
|
||||
group_size: int,
|
||||
predicate: Callable[[TraceRecord], bool] | None = None,
|
||||
group_size: int | None = None,
|
||||
) -> None:
|
||||
super().__init__(episodes, predicate=predicate)
|
||||
self._group_size = group_size
|
||||
|
||||
@property
|
||||
def group_size(self) -> int:
|
||||
if self._group_size is not None:
|
||||
return self._group_size
|
||||
counts: dict = {}
|
||||
for record in self.records:
|
||||
if record.trace.agent.trainable:
|
||||
group_id = episode_group_id(record.episode)
|
||||
counts[group_id] = counts.get(group_id, 0) + 1
|
||||
return max(counts.values(), default=0)
|
||||
self.group_size = group_size
|
||||
|
||||
@property
|
||||
def effective(self) -> EvalEpisodes:
|
||||
return EvalEpisodes(
|
||||
self.episodes,
|
||||
self.group_size,
|
||||
predicate=lambda record: not record.trace.has_error and record.trace.agent.trainable,
|
||||
group_size=self.group_size,
|
||||
)
|
||||
|
||||
@property
|
||||
|
||||
@@ -59,18 +59,19 @@ from prime_rl.orchestrator.train_sink import TrainSink
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
EvalBatch,
|
||||
GroupCancellation,
|
||||
Policy,
|
||||
Progress,
|
||||
TrainBatch,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import (
|
||||
episode_group_id,
|
||||
episode_staleness,
|
||||
eval_work,
|
||||
get_weight_dir,
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
setup_policy_inference_pool,
|
||||
train_work,
|
||||
trim_process_memory,
|
||||
)
|
||||
from prime_rl.orchestrator.watcher import WeightWatcher
|
||||
@@ -270,10 +271,10 @@ class Orchestrator:
|
||||
get_logger().info("Waiting for policy inference pool to be ready")
|
||||
await self.policy_inference.wait_for_ready(config.model.name)
|
||||
get_logger().success("Policy inference pool ready")
|
||||
# Build + ready pools for each env's frozen sampling source and the
|
||||
# Build + ready pools for each env's frozen generation source and the
|
||||
# algorithm's frozen reference model
|
||||
await asyncio.gather(
|
||||
*(env.sampler.setup() for env in self.train_envs),
|
||||
*(env.generation_source.setup() for env in self.train_envs),
|
||||
*(env.algorithm.setup() for env in self.train_envs),
|
||||
)
|
||||
|
||||
@@ -412,6 +413,7 @@ class Orchestrator:
|
||||
tokenizer=self.tokenizer,
|
||||
train_envs=self.train_envs,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
progress=self.progress,
|
||||
batch_size=config.batch_size,
|
||||
token_batch_size=config.token_batch_size,
|
||||
on_result=self.train_source.on_result,
|
||||
@@ -453,13 +455,6 @@ class Orchestrator:
|
||||
wandb_enabled=wandb_enabled,
|
||||
)
|
||||
|
||||
def off_policy_steps(self, episode: vf.Episode, training_step: int) -> int:
|
||||
"""Policy updates between generation and the batch that trains on it."""
|
||||
work = train_work(episode)
|
||||
if work.policy is None:
|
||||
return 0
|
||||
return max(0, (training_step - 1) - work.policy.start)
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Run the orchestrator until shutdown. Drives setup, spawns the
|
||||
background tasks, runs the main loop in this task, then cleans up."""
|
||||
@@ -496,6 +491,7 @@ class Orchestrator:
|
||||
clean_exit = False
|
||||
try:
|
||||
await self.main_loop()
|
||||
await self.wait_for_final_broadcast()
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
@@ -524,10 +520,44 @@ class Orchestrator:
|
||||
get_logger().warning("Orchestrator cleanup complete (forced).")
|
||||
trim_process_memory()
|
||||
|
||||
async def wait_for_final_broadcast(self) -> None:
|
||||
"""Stay alive for the trainer's last in-memory broadcast (v{max_steps-1};
|
||||
nothing samples from v{max_steps}, so it is never sent). An in-memory
|
||||
broadcast is a blocking collective — tearing down the watcher before
|
||||
the rendezvous would strand the trainer inside it."""
|
||||
config = self.config
|
||||
if config.weight_broadcast.type not in ("nccl", "nixl") or config.max_steps is None:
|
||||
return
|
||||
final_version = config.max_steps - 1
|
||||
if self.policy.version >= final_version:
|
||||
return
|
||||
get_logger().info(f"Waiting for the trainer's final broadcast (v{final_version}) before shutdown")
|
||||
|
||||
async def wait() -> None:
|
||||
while self.policy.version < final_version:
|
||||
self.version_advanced.clear()
|
||||
if self.policy.version >= final_version:
|
||||
return
|
||||
# A dead watcher can never deliver the broadcast — fail out
|
||||
# instead of idling until the timeout.
|
||||
self._raise_if_component_stopped()
|
||||
try:
|
||||
await asyncio.wait_for(self.version_advanced.wait(), timeout=5)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(wait(), timeout=config.weight_broadcast.timeout)
|
||||
except asyncio.TimeoutError:
|
||||
get_logger().warning(
|
||||
f"Trainer did not broadcast v{final_version} within {config.weight_broadcast.timeout}s — "
|
||||
"shutting down anyway"
|
||||
)
|
||||
|
||||
async def main_loop(self) -> None:
|
||||
"""Consume completed episodes from the dispatcher and route them
|
||||
to the train / eval sink. Both sinks return a finalized batch (or
|
||||
``None``) from ``add()``; we just dispatch on the result."""
|
||||
"""Consume completed episodes and ``GroupCancellation`` events from the
|
||||
dispatcher and route them to the train / eval sink. The sinks return a
|
||||
finalized batch (or ``None``); we just dispatch on the result."""
|
||||
while not self.stopped.is_set():
|
||||
self._raise_if_component_stopped()
|
||||
if self.draining and self.dispatcher.is_idle:
|
||||
@@ -536,11 +566,19 @@ class Orchestrator:
|
||||
break
|
||||
|
||||
try:
|
||||
episode = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
|
||||
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
|
||||
except asyncio.TimeoutError:
|
||||
self._raise_if_component_stopped()
|
||||
continue
|
||||
|
||||
if isinstance(item, GroupCancellation):
|
||||
assert item.kind == "train" # eval groups are never dropped
|
||||
train_batch = await self.train_sink.cancel(item)
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
continue
|
||||
episode = item
|
||||
|
||||
# Every completed rollout — errored, rejected, or never batched — lands in the
|
||||
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
|
||||
# Train rollouts belong to the batch window currently collecting (``progress.step``),
|
||||
@@ -593,14 +631,10 @@ class Orchestrator:
|
||||
step_time = (now - self.last_batch_at) if self.last_batch_at is not None else 0.0
|
||||
self.last_batch_at = now
|
||||
|
||||
# A resume can start past the end (checkpoint written at the final
|
||||
# step, or a lowered ``max_steps``): never ship beyond the budget.
|
||||
if config.max_steps is not None and step > config.max_steps:
|
||||
self.draining = True
|
||||
self.dispatcher.disable_train_scheduling()
|
||||
n_cancelled = await self.dispatcher.cancel_inflight_train_episodes()
|
||||
get_logger().info(
|
||||
f"Draining pipeline (cancelled {n_cancelled} in-flight train rollout(s); "
|
||||
f"any in-flight evals will complete)"
|
||||
)
|
||||
await self.start_draining(f"Step {step} exceeds max_steps={config.max_steps}")
|
||||
return
|
||||
|
||||
if not batch.samples:
|
||||
@@ -626,11 +660,11 @@ class Orchestrator:
|
||||
)
|
||||
|
||||
# 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.
|
||||
# Without this, fast envs fill batches from buffered rollouts and the
|
||||
# orchestrator races arbitrarily far ahead of the trainer. Always
|
||||
# satisfiable: the trainer broadcasts every version except v{max_steps},
|
||||
# and ``wait_for_final_broadcast`` keeps the watcher alive through the
|
||||
# last rendezvous after the pipeline drains.
|
||||
required_version = step - 1 - TARGET_LAG
|
||||
if self.policy.version < required_version:
|
||||
get_logger().info(
|
||||
@@ -691,6 +725,22 @@ class Orchestrator:
|
||||
"time/wait_for_policy": self.wait_for_policy_time,
|
||||
"step": step,
|
||||
}
|
||||
# Staleness of the shipped cohort, decomposed into its in-flight and
|
||||
# in-queue shares; ``dropped`` counts queued traces the sink voided
|
||||
# since the last ship.
|
||||
staleness = [episode_staleness(episode, step) for episode in effective]
|
||||
if staleness:
|
||||
totals, in_flight, in_queue = (list(values) for values in zip(*staleness))
|
||||
metrics |= {
|
||||
"off_policy/mean": sum(totals) / len(totals),
|
||||
"off_policy/max": float(max(totals)),
|
||||
"off_policy/in_flight/mean": sum(in_flight) / len(in_flight),
|
||||
"off_policy/in_flight/max": float(max(in_flight)),
|
||||
"off_policy/in_queue/mean": sum(in_queue) / len(in_queue),
|
||||
"off_policy/in_queue/max": float(max(in_queue)),
|
||||
}
|
||||
metrics["off_policy/dropped"] = float(self.train_sink.stale_drops)
|
||||
self.train_sink.stale_drops = 0
|
||||
for env_name, env_pool in batch.episodes.by_env().items():
|
||||
metrics[f"batch/{env_name}"] = env_pool.num_traces / batch.episodes.num_traces
|
||||
metrics |= self.train_source.metrics()
|
||||
@@ -707,8 +757,25 @@ class Orchestrator:
|
||||
self.log_train_batch(batch, step=step, step_time=step_time)
|
||||
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
# Drain right after shipping the final batch. Waiting for a further
|
||||
# batch to fill would burn inference on data that can never train —
|
||||
# and with a tight ``max_off_policy_steps`` it never fills at all (the
|
||||
# versions it would need are never broadcast).
|
||||
if config.max_steps is not None and step >= config.max_steps:
|
||||
await self.start_draining("Shipped the final batch")
|
||||
trim_process_memory()
|
||||
|
||||
async def start_draining(self, reason: str) -> None:
|
||||
"""Stop scheduling train work and let the pipeline empty; triggered
|
||||
eval epochs still run to completion."""
|
||||
self.draining = True
|
||||
self.dispatcher.disable_train_scheduling()
|
||||
n_cancelled = await self.dispatcher.cancel_inflight_train_episodes()
|
||||
get_logger().info(
|
||||
f"{reason} — draining pipeline (cancelled {n_cancelled} in-flight "
|
||||
f"train episode(s); any in-flight evals will complete)"
|
||||
)
|
||||
|
||||
def maybe_trigger_eval(self, step: int) -> None:
|
||||
"""Fire eligible eval epochs and flip to ``PREFER_EVAL`` if anything
|
||||
fires. No-op when eval is not configured."""
|
||||
@@ -794,8 +861,12 @@ 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``."""
|
||||
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
|
||||
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
|
||||
``Error``, ``Cancelled``, and ``Ratio`` are rates over the step's full arrival window —
|
||||
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
|
||||
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
|
||||
decision, not a rollout failure)."""
|
||||
episodes = batch.episodes
|
||||
effective = batch.cohort.effective
|
||||
eff = effective.metrics
|
||||
@@ -803,14 +874,15 @@ class Orchestrator:
|
||||
n_effective = effective.num_traces
|
||||
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
|
||||
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
|
||||
max_off_policy = max((self.off_policy_steps(episode, step) for episode in effective), default=0)
|
||||
max_off_policy_steps = max((episode_staleness(episode, step)[0] for episode 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"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max_off_policy} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
f"Max Off-Policy {max_off_policy_steps} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
if len(self.train_envs) <= 1:
|
||||
get_logger().success(head)
|
||||
@@ -829,8 +901,9 @@ class Orchestrator:
|
||||
lines.append(
|
||||
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
|
||||
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max((self.off_policy_steps(episode, step) for episode in env_eff_pool), default=0)} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Truncation {env_eff.is_truncated.mean():.1%}"
|
||||
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {env_eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
|
||||
@@ -902,16 +975,9 @@ class Orchestrator:
|
||||
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
|
||||
count is ``progress.step - 1``."""
|
||||
lead = (self.progress.step - 1) - self.policy.version
|
||||
# The trainer skips the final in-memory weight broadcasts, so policy.version never
|
||||
# reaches the last step. Let the final batch through instead of waiting for it.
|
||||
building_final_batch_without_update = (
|
||||
self.config.weight_broadcast.type in ("nccl", "nixl")
|
||||
and self.config.max_steps is not None
|
||||
and self.progress.step >= self.config.max_steps - 1
|
||||
)
|
||||
gate = self.dispatcher.dispatch_allowed
|
||||
was_set = gate.is_set()
|
||||
if lead > TARGET_LAG and not building_final_batch_without_update:
|
||||
if lead > TARGET_LAG:
|
||||
if was_set:
|
||||
get_logger().info(
|
||||
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
|
||||
@@ -965,7 +1031,7 @@ class Orchestrator:
|
||||
await self.policy_inference.stop()
|
||||
if self.train_envs is not None:
|
||||
for env in self.train_envs:
|
||||
for pool in (*env.sampler.connected_pools, *env.algorithm.connected_pools):
|
||||
for pool in (*env.generation_source.connected_pools, *env.algorithm.connected_pools):
|
||||
await pool.stop()
|
||||
|
||||
task = asyncio.create_task(teardown())
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
"""Training-side episode, group, and batch assembly."""
|
||||
"""Training-side episode, group, and batch assembly.
|
||||
|
||||
``add()`` takes one completed episode and ``cancel()`` a dropped group's
|
||||
``GroupCancellation``; both return ``TrainBatch | None``. Before every readiness
|
||||
check the sink sweeps ``pending_batch`` for traces past ``max_off_policy_steps`` —
|
||||
this sweep, not the dispatcher's in-flight cancel, is what guarantees nothing
|
||||
stale ships."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
@@ -14,8 +20,8 @@ from prime_rl.orchestrator.algo.routing import stamp_loss_routing
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.metrics import TrainEpisodes
|
||||
from prime_rl.orchestrator.trajectories import trace_to_samples
|
||||
from prime_rl.orchestrator.types import TrainBatch
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id
|
||||
from prime_rl.orchestrator.types import GroupCancellation, Progress, TrainBatch
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, min_fresh_version, train_work
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -65,6 +71,7 @@ class TrainSink:
|
||||
tokenizer,
|
||||
train_envs: TrainEnvs,
|
||||
mm_token_type_ids_mapping: dict[int, int] | None,
|
||||
progress: Progress,
|
||||
batch_size: int | None,
|
||||
token_batch_size: int | None,
|
||||
on_result: Callable[[list[vf.Episode]], bool] | None = None,
|
||||
@@ -76,15 +83,25 @@ class TrainSink:
|
||||
self.tokenizer = tokenizer
|
||||
self.train_envs = train_envs
|
||||
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
|
||||
self.progress = progress
|
||||
self.batch_size = batch_size
|
||||
self.token_batch_size = token_batch_size
|
||||
self.on_result = on_result
|
||||
|
||||
self.pending_episodes = TrainEpisodes()
|
||||
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
|
||||
# A dropped group's terminal marker; its ``count`` fills in for the
|
||||
# episodes the group will never deliver.
|
||||
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
|
||||
self.pending_batch: dict[str, list[TrainingSample]] = {}
|
||||
self.episode_by_trace: dict[str, vf.Episode] = {}
|
||||
self.pending_tokens = 0
|
||||
# Queued traces voided by the staleness sweep since the last ship;
|
||||
# read and reset by the orchestrator's per-step metrics.
|
||||
self.stale_drops = 0
|
||||
# Step of the last full staleness sweep — queued traces only age when
|
||||
# ``progress.step`` advances, so one full sweep per step suffices.
|
||||
self._swept_step = 0
|
||||
self.zero_output_units = 0
|
||||
self.reported_zero_output_windows = 0
|
||||
|
||||
@@ -112,12 +129,33 @@ class TrainSink:
|
||||
await self.process_episode(episode)
|
||||
group_id = episode_group_id(episode)
|
||||
env_name = episode_env_name(episode)
|
||||
group = self.pending_groups[group_id]
|
||||
group.append(episode)
|
||||
if len(group) < self.group_size_for(env_name):
|
||||
self.pending_groups[group_id].append(episode)
|
||||
if not self._group_complete(group_id, env_name):
|
||||
return None
|
||||
|
||||
await self.process_group(group_id)
|
||||
return self._maybe_batch()
|
||||
|
||||
async def cancel(self, cancellation: GroupCancellation) -> TrainBatch | None:
|
||||
"""Process a dropped group's terminal marker: its ``count`` completes
|
||||
the group's episode accounting so finalization still fires. A
|
||||
``stale`` drop also voids the group's already-arrived episodes in
|
||||
``process_group`` — they share the group's dispatch version, so they
|
||||
are equally stale."""
|
||||
self.pending_group_cancellations[cancellation.group_id] = cancellation
|
||||
if not self._group_complete(cancellation.group_id, cancellation.env_name):
|
||||
return None
|
||||
await self.process_group(cancellation.group_id)
|
||||
return self._maybe_batch()
|
||||
|
||||
def _group_complete(self, group_id: str, env_name: str) -> bool:
|
||||
cancellation = self.pending_group_cancellations.get(group_id)
|
||||
cancelled = cancellation.count if cancellation is not None else 0
|
||||
return len(self.pending_groups[group_id]) + cancelled >= self.group_size_for(env_name)
|
||||
|
||||
def _maybe_batch(self) -> TrainBatch | None:
|
||||
"""Sweep stale queued traces, then cut a batch if the survivors still
|
||||
meet the threshold."""
|
||||
self._drop_stale()
|
||||
ready = (
|
||||
len(self.pending_batch) >= self.batch_size
|
||||
if self.batch_size is not None
|
||||
@@ -125,6 +163,47 @@ class TrainSink:
|
||||
)
|
||||
return self.process_batch() if ready else None
|
||||
|
||||
def _drop_stale(self, trace_ids: Iterable[str] | None = None) -> None:
|
||||
"""Void queued traces past ``max_off_policy_steps``. The batch being
|
||||
collected is ``progress.step`` and trains policy v{step-1}, so a
|
||||
queued trace generated from v{k} would ship at staleness
|
||||
``(step-1) - k``. This sweep is the hard guarantee on trained
|
||||
staleness; the dispatcher's in-flight cancel only saves compute.
|
||||
Queued traces only age when ``progress.step`` advances, so the full
|
||||
sweep runs once per step; ``trace_ids`` scopes the check to a freshly
|
||||
inserted group, whose traces may already be stale on arrival.
|
||||
Frozen-sourced episodes (no policy span) never go stale.
|
||||
|
||||
A swept trace whose window already shipped is visible only in
|
||||
``stale_drops`` — its episode was reported with that window, and
|
||||
re-observing it would double-count its stats."""
|
||||
if trace_ids is None:
|
||||
if self._swept_step == self.progress.step:
|
||||
return
|
||||
self._swept_step = self.progress.step
|
||||
trace_ids = list(self.pending_batch)
|
||||
min_version = min_fresh_version(self.progress.step, self.config.max_off_policy_steps)
|
||||
if min_version <= 0:
|
||||
return
|
||||
dropped = 0
|
||||
for trace_id in trace_ids:
|
||||
episode = self.episode_by_trace[trace_id]
|
||||
policy = train_work(episode).policy
|
||||
if policy is None or policy.start >= min_version:
|
||||
continue
|
||||
samples = self.pending_batch.pop(trace_id)
|
||||
if self.token_batch_size is not None:
|
||||
self.pending_tokens -= payload_tokens(samples, self._trace(trace_id))
|
||||
del self.episode_by_trace[trace_id]
|
||||
self.pending_episodes.cancelled.add(episode.id)
|
||||
dropped += 1
|
||||
if dropped:
|
||||
self.stale_drops += dropped
|
||||
get_logger().warning(
|
||||
f"Dropped {dropped} queued traces past max_off_policy_steps={self.config.max_off_policy_steps}. "
|
||||
"Consider increasing it to avoid this."
|
||||
)
|
||||
|
||||
async def process_episode(self, episode: vf.Episode) -> None:
|
||||
"""Run rollout-local algorithm work on one native episode."""
|
||||
env_name = episode_env_name(episode)
|
||||
@@ -132,24 +211,39 @@ class TrainSink:
|
||||
|
||||
async def process_group(self, group_id: str) -> None:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
if not group:
|
||||
cancellation = self.pending_group_cancellations.pop(group_id, None)
|
||||
if not group and cancellation is None:
|
||||
return
|
||||
|
||||
env_name = episode_env_name(group[0])
|
||||
env_name = episode_env_name(group[0]) if group else cancellation.env_name
|
||||
env = self.train_envs.get(env_name)
|
||||
traces = [trace for episode in group for trace in episode.traces]
|
||||
survivors = [trace for _, trace in iter_trainable_traces(group)]
|
||||
task_idx = next((trace.task.data.idx for trace in traces), None)
|
||||
num_errored = sum(trace.has_error for trace in traces) + sum(
|
||||
not episode.ok for episode in group if not episode.traces
|
||||
)
|
||||
n_owed = len(group) + (cancellation.count if cancellation is not None else 0)
|
||||
|
||||
# A stale drop voids the whole group: every member shares the dispatch
|
||||
# version, so the arrived episodes are exactly as stale as the
|
||||
# cancelled tail. Stale groups bypass the curriculum — a pipeline
|
||||
# decision is not a task result.
|
||||
if cancellation is not None and cancellation.reason == "stale":
|
||||
self.pending_episodes.extend(group, admitted=False, cancelled=True)
|
||||
self._record_zero_output(group, [], n_owed)
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | dropped: cancelled (stale)"
|
||||
)
|
||||
return
|
||||
|
||||
survivors = [trace for _, trace in iter_trainable_traces(group)]
|
||||
if survivors:
|
||||
await env.algorithm.finalize_group(group)
|
||||
admitted = self._admit(group)
|
||||
admitted = self._admit(group) if group else False
|
||||
if not survivors or not admitted:
|
||||
self.pending_episodes.extend(group, admitted=admitted)
|
||||
self._record_zero_output(group, survivors)
|
||||
self._record_zero_output(group, survivors, n_owed)
|
||||
reason = "no trainable survivors" if not survivors else "rejected by curriculum"
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
@@ -174,7 +268,7 @@ class TrainSink:
|
||||
|
||||
self.pending_episodes.extend(group, sampled_trace_ids=set(samples_by_trace), admitted=True)
|
||||
if not samples_by_trace:
|
||||
self._record_zero_output(group, survivors)
|
||||
self._record_zero_output(group, survivors, n_owed)
|
||||
return
|
||||
|
||||
self.pending_batch.update(samples_by_trace)
|
||||
@@ -186,6 +280,15 @@ class TrainSink:
|
||||
self.pending_tokens += sum(
|
||||
payload_tokens(samples, self._trace(trace_id)) for trace_id, samples in samples_by_trace.items()
|
||||
)
|
||||
self._drop_stale(samples_by_trace)
|
||||
# A group's traces share one dispatch version, so the insertion sweep
|
||||
# voids all or none of them. A fully-voided group shipped nothing —
|
||||
# advance the zero-output budget instead of resetting it, or a stalled
|
||||
# trainer plus a tight bound could void groups forever without ever
|
||||
# tripping the abort.
|
||||
if not any(trace_id in self.pending_batch for trace_id in samples_by_trace):
|
||||
self._record_zero_output(group, [], n_owed)
|
||||
return
|
||||
self.zero_output_units = 0
|
||||
self.reported_zero_output_windows = 0
|
||||
|
||||
@@ -203,14 +306,17 @@ class TrainSink:
|
||||
def _admit(self, group: list[vf.Episode]) -> bool:
|
||||
return self.on_result(group) if self.on_result is not None else True
|
||||
|
||||
def _record_zero_output(self, group: list[vf.Episode], survivors: list[vf.Trace]) -> None:
|
||||
def _record_zero_output(self, group: list[vf.Episode], survivors: list[vf.Trace], n_owed: int) -> None:
|
||||
"""``n_owed`` counts the group's full episode budget (arrived +
|
||||
cancelled), so dropped groups advance the zero-output budget at the
|
||||
same rate as fully-delivered ones."""
|
||||
if self.batch_size is not None:
|
||||
returned_traces = sum(len(episode.traces) for episode in group)
|
||||
self.zero_output_units += len(survivors) or returned_traces or len(group)
|
||||
self.zero_output_units += len(survivors) or returned_traces or n_owed
|
||||
else:
|
||||
survivor_tokens = sum(trace.num_total_tokens for trace in survivors)
|
||||
episode_tokens = sum(episode.num_total_tokens for episode in group)
|
||||
self.zero_output_units += survivor_tokens or episode_tokens or self.config.seq_len * len(group)
|
||||
self.zero_output_units += survivor_tokens or episode_tokens or self.config.seq_len * n_owed
|
||||
self._check_zero_output_budget()
|
||||
|
||||
def _check_zero_output_budget(self) -> None:
|
||||
@@ -228,7 +334,7 @@ class TrainSink:
|
||||
if windows >= MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS:
|
||||
raise RuntimeError(
|
||||
f"{windows} consecutive zero-output batch equivalents — "
|
||||
"check the curriculum admission policy and task difficulty."
|
||||
"check the curriculum admission policy, task difficulty, and staleness drops."
|
||||
)
|
||||
|
||||
def process_batch(self) -> TrainBatch:
|
||||
|
||||
@@ -10,6 +10,7 @@ import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.curriculum import Curriculum
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.types import TaskRequest
|
||||
from prime_rl.orchestrator.utils import episode_env_name
|
||||
|
||||
|
||||
@@ -34,12 +35,9 @@ class TrainSource:
|
||||
self._admitted: dict[str, int] = defaultdict(int)
|
||||
self._rejected: dict[str, int] = defaultdict(int)
|
||||
|
||||
def next_example(self) -> dict[str, Any]:
|
||||
def next_task(self, *, step: int) -> TaskRequest:
|
||||
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
|
||||
return {
|
||||
"env_name": env_name,
|
||||
"task": next(self.curricula[env_name].sampler),
|
||||
}
|
||||
return TaskRequest(env_name=env_name, task=next(self.curricula[env_name].sampler), step=step)
|
||||
|
||||
def on_result(self, group: list[vf.Episode]) -> bool:
|
||||
"""Report a finalized group and return whether it should train."""
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Literal, Protocol
|
||||
from typing import TYPE_CHECKING, Literal, Protocol, TypeAlias
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
@@ -35,6 +35,34 @@ class Progress:
|
||||
|
||||
WorkKind = Literal["train", "eval"]
|
||||
|
||||
CancelReason = Literal["stale", "overload"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class GroupCancellation:
|
||||
"""Terminal marker for a dropped group: one message covering every episode
|
||||
the group still owed the sink (in-flight and never-dispatched), so
|
||||
count-to-``group_size`` finalization still fires. ``reason`` distinguishes
|
||||
pipeline decisions (staleness, overload cut) from episode errors."""
|
||||
|
||||
kind: WorkKind
|
||||
env_name: str
|
||||
group_id: str
|
||||
count: int
|
||||
reason: CancelReason
|
||||
|
||||
|
||||
DispatchResult: TypeAlias = vf.WireEpisode | GroupCancellation
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TaskRequest:
|
||||
"""A task selected by a train or eval source with its pinned run step."""
|
||||
|
||||
env_name: str
|
||||
task: vf.Task
|
||||
step: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class InflightEpisode:
|
||||
@@ -47,25 +75,22 @@ class InflightEpisode:
|
||||
policy_version: int
|
||||
step: int
|
||||
client_config: vf.ClientConfig | None = None
|
||||
off_policy_steps: int = 0
|
||||
eval_step: int | None = None
|
||||
started_at: float = 0.0
|
||||
"""``time.monotonic()`` at dispatch; feeds episode-duration estimates."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class GroupState:
|
||||
"""Per-group dispatcher state: what's left to schedule + the pinned
|
||||
client (for prefix-cache hits)."""
|
||||
"""Per-group dispatcher state with pinned run context and client."""
|
||||
|
||||
kind: WorkKind
|
||||
env_name: str
|
||||
task: vf.Task
|
||||
"""The group's task — its data is shipped on every dispatch."""
|
||||
step: int
|
||||
episodes_to_schedule: int
|
||||
target_episodes: int
|
||||
emitted: int = 0
|
||||
eval_step: int | None = None
|
||||
pinned_client: vf.ClientConfig | None = None
|
||||
policy_version_at_start: int = 0
|
||||
|
||||
|
||||
@@ -48,6 +48,28 @@ def eval_work(episode: vf.Episode[Any, Any, Any]) -> vf.EvalWorkInfo:
|
||||
return run.work
|
||||
|
||||
|
||||
def min_fresh_version(step: int, max_off_policy_steps: int) -> int:
|
||||
"""Oldest dispatch version whose episodes may still train in batch
|
||||
``step`` — anything older would ship past ``max_off_policy_steps``."""
|
||||
return (step - 1) - max_off_policy_steps
|
||||
|
||||
|
||||
def episode_staleness(episode: vf.Episode[Any, Any, Any], training_step: int) -> tuple[int, int, int]:
|
||||
"""``(total, in_flight, in_queue)`` staleness of one train episode when
|
||||
consumed by batch ``training_step``: the version the batch trains on
|
||||
(v{step-1}) minus the version that generated the episode. ``in_flight``
|
||||
is the span's share (weight updates during generation); ``in_queue`` is
|
||||
time spent buffered between completion and ship. Frozen-sourced episodes
|
||||
(no policy span) are never stale."""
|
||||
policy = train_work(episode).policy
|
||||
if policy is None:
|
||||
return 0, 0, 0
|
||||
total = max(0, (training_step - 1) - policy.start)
|
||||
in_flight = min(total, max(0, policy.end - policy.start))
|
||||
in_queue = total - in_flight
|
||||
return total, in_flight, in_queue
|
||||
|
||||
|
||||
async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
"""Build the live policy inference pool + matching renderer. Returns
|
||||
``(renderer, inference_pool)``.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""WeightWatcher: polls the broadcast dir, advances ``Policy``, notifies
|
||||
observers (dispatcher → off-policy cancel). Standalone async task; the
|
||||
observers (dispatcher → staleness cancel). Standalone async task; the
|
||||
orchestrator's barrier bounds the in-flight lead."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -77,7 +77,8 @@ class WeightWatcher:
|
||||
def compute_next_ckpt_step(self) -> int:
|
||||
"""Return the next policy version exposed by the configured transport."""
|
||||
if self.model_express is not None:
|
||||
if self.config.max_steps is not None and self.ckpt_step >= self.config.max_steps - 2:
|
||||
# The trainer broadcasts every version except v{max_steps}.
|
||||
if self.config.max_steps is not None and self.ckpt_step >= self.config.max_steps - 1:
|
||||
return self.ckpt_step
|
||||
# ModelExpress status changes are unversioned, so its rendezvous advances
|
||||
# exactly one policy version per READY/INITIALIZING cycle.
|
||||
@@ -116,7 +117,7 @@ class WeightWatcher:
|
||||
self.ckpt_step = next_step
|
||||
self.policy.version = next_step
|
||||
|
||||
# Drain off-policy rollouts BEFORE pausing the inference engines.
|
||||
# Drain stale rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
# ``_reqs_not_processed``), which is only propagated to the workers
|
||||
# while the engine is stepping. If we drain after resume instead,
|
||||
|
||||
@@ -62,6 +62,11 @@ export MASTER_ADDR="${HOSTNAMES[0]}"
|
||||
export MASTER_PORT=29500
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
echo "MASTER_PORT=${MASTER_PORT}"
|
||||
{% if use_nccl_broadcast %}
|
||||
# The eval job has a separate allocation. Publish the trainer's NCCL host through
|
||||
# the shared run directory under this job ID.
|
||||
printf '%s\n' "$MASTER_ADDR" > "$OUTPUT_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
{% endif %}
|
||||
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
@@ -155,5 +160,8 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.sft.train \
|
||||
@ $CONFIG_PATH \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host 0.0.0.0 \
|
||||
{%- endif %}
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
LAUNCH_SH
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user