Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3fdadedc5 | ||
|
|
84e7312f33 | ||
|
|
fe325ac460 | ||
|
|
0f22eeb862 | ||
|
|
1fbf0b47a4 | ||
|
|
799ac26258 | ||
|
|
d5b38216a5 |
+30
-36
@@ -96,7 +96,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
# mount here: .git would bust the cache every commit.
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
--no-install-workspace \
|
||||
--no-install-package prime-rl-configs \
|
||||
--no-install-package verifiers \
|
||||
@@ -132,9 +132,9 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
|
||||
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
|
||||
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
|
||||
@@ -167,34 +167,6 @@ RUN find /usr/local/cuda-13.0/targets/*/lib \
|
||||
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
|
||||
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
|
||||
|
||||
# AWS EFA userspace stack: libfabric + the aws-ofi-nccl NCCL net plugin,
|
||||
# installed as one version-matched unit via AWS's official installer
|
||||
# rather than picking versions by hand. Do not substitute a host-mounted
|
||||
# copy of these libraries instead of building them in -- symbol-version
|
||||
# mismatches between a host's rdma-core and a container's can silently
|
||||
# break the NCCL plugin. --skip-kmod: containers share the host kernel and
|
||||
# must never build/load a kernel module themselves; the EFA driver is
|
||||
# expected to already be present on the host. --skip-limit-conf: ulimits
|
||||
# config doesn't apply inside a build. Same base OS as the runtime stage
|
||||
# below for glibc/rdma-core ABI compatibility.
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS efa-installer
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ARG EFA_INSTALLER_VERSION=1.47.0
|
||||
# One RUN: efa_installer.sh apt-get installs its own deps (pciutils,
|
||||
# libnl-3-200, tcl, ...) internally, so the package index has to survive
|
||||
# until after it runs. Purging /var/lib/apt/lists/* only at the very end
|
||||
# (not between the curl/tar deps and the installer invocation) keeps that
|
||||
# available.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
curl ca-certificates tar gzip \
|
||||
&& curl -fsSL "https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_INSTALLER_VERSION}.tar.gz" \
|
||||
-o /tmp/aws-efa-installer.tar.gz \
|
||||
&& tar -xzf /tmp/aws-efa-installer.tar.gz -C /tmp \
|
||||
&& cd /tmp/aws-efa-installer \
|
||||
&& ./efa_installer.sh -y --skip-kmod --skip-limit-conf \
|
||||
&& cd / && rm -rf /tmp/aws-efa-installer.tar.gz /tmp/aws-efa-installer \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Runtime image
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
|
||||
|
||||
@@ -226,10 +198,37 @@ RUN apt-get update && apt-get install -y \
|
||||
libibverbs1 \
|
||||
ibverbs-providers \
|
||||
librdmacm1 \
|
||||
libhwloc15 \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
|
||||
&& apt-get clean autoclean \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
# AWS EFA userspace stack: libfabric + the aws-ofi-nccl NCCL net plugin,
|
||||
# installed as one version-matched unit via AWS's official installer rather
|
||||
# than picking versions by hand. Do not substitute a host-mounted copy of
|
||||
# these libraries instead of building them in -- symbol-version mismatches
|
||||
# between a host's rdma-core and a container's can silently break the NCCL
|
||||
# plugin. Run directly in this stage (not a separate one COPY'd in after):
|
||||
# the installer's own apt-get/dpkg step upgrades system rdma-core packages
|
||||
# (libibverbs, ibverbs-providers, librdmacm) in place to versions libfabric
|
||||
# actually links against -- copying only /opt/amazon out of an isolated
|
||||
# stage leaves that system-wide upgrade behind, so libfabric ends up paired
|
||||
# with whatever older rdma-core this image's own apt install pulled in and
|
||||
# fails to load (symbol version mismatch on libefa.so.1). --skip-kmod:
|
||||
# containers share the host kernel and must never build/load a kernel
|
||||
# module themselves; the EFA driver is expected to already be present on
|
||||
# the host. --skip-limit-conf: ulimits config doesn't apply inside a build.
|
||||
ARG EFA_INSTALLER_VERSION=1.47.0
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates tar gzip \
|
||||
&& curl -fsSL "https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_INSTALLER_VERSION}.tar.gz" \
|
||||
-o /tmp/aws-efa-installer.tar.gz \
|
||||
&& tar -xzf /tmp/aws-efa-installer.tar.gz -C /tmp \
|
||||
&& cd /tmp/aws-efa-installer \
|
||||
&& ./efa_installer.sh -y --skip-kmod --skip-limit-conf \
|
||||
&& cd / && rm -rf /tmp/aws-efa-installer.tar.gz /tmp/aws-efa-installer \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# CUDA 13.0 toolkit (TileLang's runtime nvcc JIT)
|
||||
COPY --from=cuda-trim /usr/local/cuda-13.0 /usr/local/cuda-13.0
|
||||
RUN ln -sfn /usr/local/cuda-13.0 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
|
||||
@@ -267,11 +266,6 @@ COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packa
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
|
||||
COPY --from=builder /opt/ucx /opt/ucx
|
||||
|
||||
# EFA userspace stack from the dedicated stage above. Not added to
|
||||
# LD_LIBRARY_PATH here -- deployment configs opt into that only where
|
||||
# EFA is actually available, so this is inert everywhere else.
|
||||
COPY --from=efa-installer /opt/amazon /opt/amazon
|
||||
|
||||
# Copy and set up entrypoint script
|
||||
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
|
||||
@@ -23,6 +23,7 @@ import torch
|
||||
from pydantic import Field
|
||||
|
||||
from prime_rl.utils.config import BaseConfig, cli
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
|
||||
MAX_LORAS = 4
|
||||
|
||||
@@ -207,13 +208,16 @@ def aggregate_metrics(metrics_path: Path) -> dict:
|
||||
|
||||
Each metrics.jsonl line is one monitor.log call (``{"step": N, ...}``);
|
||||
merge the lines per step, drop the first (warmup) step, and compute
|
||||
mean/std/min/max per metric like the old --bench JSON export did.
|
||||
mean/std/min/max per metric like the old --bench JSON export did. Rows
|
||||
keyed by wall time rather than step (``step: null``) are not per-step and
|
||||
are skipped.
|
||||
"""
|
||||
per_step: dict[int, dict] = {}
|
||||
with open(metrics_path) as f:
|
||||
for line in f:
|
||||
row = json.loads(line)
|
||||
per_step.setdefault(row["step"], {}).update(row)
|
||||
if row.get("step") is not None:
|
||||
per_step.setdefault(row["step"], {}).update(row)
|
||||
|
||||
steps = sorted(per_step)[1:] # Exclude first warmup step
|
||||
columns = {
|
||||
@@ -255,7 +259,8 @@ def run_benchmark(config: BenchmarkConfig) -> None:
|
||||
return
|
||||
|
||||
# The SFT entrypoint writes to output_dir/<run.name>, the RL trainer to output_dir directly
|
||||
metrics_path = output_dir / "bench" / "metrics.jsonl" if config.type == "sft" else output_dir / "metrics.jsonl"
|
||||
run_dir = output_dir / "bench" if config.type == "sft" else output_dir
|
||||
metrics_path = get_file_monitor_dir(run_dir) / "metrics.jsonl"
|
||||
|
||||
start_time = time.perf_counter()
|
||||
try:
|
||||
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: 9b47901de1...f91c3e7061
Vendored
+1
-1
Submodule deps/verifiers updated: e2103d6fb4...3ed6ef7c2c
@@ -2,7 +2,7 @@
|
||||
|
||||
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions) that aren't surfaced here.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
|
||||
+17
-1
@@ -285,7 +285,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
|
||||
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`.
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.28 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
@@ -298,3 +298,19 @@ enable_return_routed_experts = true
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
|
||||
|
||||
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
|
||||
|
||||
### Sampling Replay
|
||||
|
||||
Truncated sampling (`top_p < 1`, `top_k`) renormalizes the sampling distribution over a sampling mask of surviving token ids. The rollout logprobs reflect that (`logprobs_mode = "processed_logprobs"`), so the trainer must renormalize over the same mask — otherwise every importance ratio is biased and training collapses (DeepSeek V3.2's "Keep Sampling Mask", [arXiv:2512.02556](https://arxiv.org/abs/2512.02556) §3.1; Cognition's [SWE-1.7 post](https://cognition.com/blog/swe-1-7)). prime-rl handles this automatically: vLLM records the sampling mask at sampling time (`--return-sampling-mask`, native since vLLM 0.28) and the trainer renormalizes its logprobs over it.
|
||||
|
||||
```toml
|
||||
[orchestrator.train.sampling]
|
||||
top_p = 0.95
|
||||
top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling mask)
|
||||
```
|
||||
|
||||
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`; Gemma-family (softcapped) lm_heads fail loudly. Frozen-source envs are exempt.
|
||||
|
||||
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
|
||||
|
||||
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
|
||||
|
||||
+1
-1
@@ -277,4 +277,4 @@ uv run sft @ sft.toml --data.type fake --max-steps 4
|
||||
uv run trainer @ train.toml --data.fake --max-steps 4
|
||||
```
|
||||
|
||||
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `metrics.jsonl` to the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
|
||||
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
|
||||
|
||||
+2
-2
@@ -351,13 +351,13 @@ tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
|
||||
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
|
||||
|
||||
### Weights & Biases
|
||||
|
||||
W&B is off by default (the file monitor, which writes `metrics.jsonl` and the per-step trace files to the run directory, is on by default):
|
||||
W&B is off by default (the file monitor, which writes the metrics and the trace stream under the run's `monitors/file/` directory, is on by default):
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --monitors.wandb # default project, random name
|
||||
|
||||
@@ -100,7 +100,7 @@ name = "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.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.taskset.id = "openseeker"
|
||||
|
||||
@@ -124,7 +124,7 @@ name = "redsearcher"
|
||||
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.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
|
||||
|
||||
@@ -154,7 +154,7 @@ num_examples = 500 # full set is 1266; cap eval at 500
|
||||
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.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "browsecomp"
|
||||
|
||||
@@ -96,7 +96,7 @@ num_turns_weight = 0.1
|
||||
[[orchestrator.train.source]]
|
||||
name = "tmax"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.taskset.id = "tmax"
|
||||
|
||||
@@ -123,7 +123,7 @@ interval = 20
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
@@ -144,7 +144,7 @@ env.taskset.id = "swebench-verified"
|
||||
name = "terminal-bench-2"
|
||||
group_size = 4 # avg@4
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
|
||||
@@ -84,7 +84,6 @@ partition = "all" # FILL IN: set to your cluster's partition
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 1800
|
||||
enable_token_export = true
|
||||
|
||||
[trainer.model]
|
||||
name = "zai-org/GLM-5.1"
|
||||
|
||||
@@ -89,7 +89,7 @@ truncate_history_thinking = false
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
@@ -99,7 +99,7 @@ interval = 20
|
||||
name = "swebench-verified"
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["nemotron-3-super-swe"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
|
||||
@@ -21,6 +21,19 @@ env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text-eval"
|
||||
num_examples = 256
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
|
||||
@@ -4,7 +4,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.shared import ClientConfig, LogConfig, ResumeConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
@@ -66,6 +66,13 @@ class OnlineConfig(BaseConfig):
|
||||
this step."""
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
"""Checkpoint progress for an interruptible standalone eval run."""
|
||||
|
||||
interval: int = Field(1, ge=1)
|
||||
"""Save after the task cursor advances by N completed groups."""
|
||||
|
||||
|
||||
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
|
||||
@@ -95,6 +102,12 @@ class EvalsConfig(BaseConfig):
|
||||
"""Directory to write outputs to — rollout traces and logs are written as
|
||||
subdirectories. Shared with the trainer for online evals. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
ckpt: CheckpointConfig | None = None
|
||||
"""Checkpoint standalone eval progress. Checkpoint steps are task cursor positions."""
|
||||
|
||||
resume: ResumeConfig | None = None
|
||||
"""Resume a standalone eval run from a cursor checkpoint. A bare block loads the latest checkpoint."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
@@ -117,3 +130,12 @@ class EvalsConfig(BaseConfig):
|
||||
"would skip its only eval epoch. Remove it or add an [online] block."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_checkpointing_is_standalone_only(self):
|
||||
if self.online is not None and (self.ckpt is not None or self.resume is not None):
|
||||
raise ValueError(
|
||||
"evals ckpt/resume only supports standalone evals - online evals are coordinated "
|
||||
"with the trainer's live weight-broadcast lifecycle"
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -458,6 +458,9 @@ class InferenceConfig(BaseConfig):
|
||||
use_pd_kv_transfer: bool = False
|
||||
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
|
||||
|
||||
enable_return_sampling_mask: bool = False
|
||||
"""Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs and selects the V2 model runner before vLLM starts. Capture is engine-wide: vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0`` while it is on."""
|
||||
|
||||
enable_fp32_lm_head: bool = True
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
|
||||
@@ -494,6 +497,20 @@ class InferenceConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
"""NIXL routed-expert capture uses the V1 runner, while sampling replay needs V2."""
|
||||
if (
|
||||
self.deployment.type == "disaggregated"
|
||||
and self.enable_return_sampling_mask
|
||||
and self.vllm.enable_return_routed_experts
|
||||
):
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_router_deployment(self):
|
||||
"""The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines."""
|
||||
@@ -619,6 +636,9 @@ class InferenceConfig(BaseConfig):
|
||||
hf_overrides.setdefault("moe_router_dtype", "float32")
|
||||
namespace.hf_overrides = hf_overrides
|
||||
|
||||
if self.enable_return_sampling_mask:
|
||||
namespace.return_sampling_mask = True
|
||||
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
namespace.kv_transfer_config = kv_transfer_config
|
||||
|
||||
@@ -25,7 +25,8 @@ class WandbMonitorConfig(BaseConfig):
|
||||
|
||||
class FileMonitorConfig(BaseConfig):
|
||||
path: Path = Path("metrics.jsonl")
|
||||
"""Path of the JSONL file, relative to the component's ``output_dir`` (absolute paths win)."""
|
||||
"""Path of the metrics JSONL file, relative to the file monitor's directory under the
|
||||
component's ``output_dir`` (``monitors/file/``; absolute paths win)."""
|
||||
|
||||
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
@@ -45,6 +46,16 @@ class TrainSamplingConfig(BaseConfig):
|
||||
temperature: float = Field(1.0, ge=0, le=2.0)
|
||||
"""Sampling temperature."""
|
||||
|
||||
top_p: float = Field(1.0, gt=0, le=1.0)
|
||||
"""Nucleus (top-p) sampling for train rollouts. Values below 1.0 truncate the sampling
|
||||
distribution; the ``rl`` entrypoint auto-enables sampling replay so trainer and
|
||||
rollout distributions stay consistent — see docs/inference.md (Sampling Replay)."""
|
||||
|
||||
top_k: int | None = Field(None, ge=1)
|
||||
"""Top-k sampling for train rollouts. Truncation triggers sampling replay, and
|
||||
a default top-k is injected when only top-p truncates so sampling masks stay
|
||||
bounded — see docs/inference.md (Sampling Replay)."""
|
||||
|
||||
max_completion_tokens: int | None = None
|
||||
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
|
||||
|
||||
@@ -53,18 +64,46 @@ class TrainSamplingConfig(BaseConfig):
|
||||
extra_body: dict[str, Any] = {}
|
||||
"""Extra body forwarded with each request to the inference server."""
|
||||
|
||||
def truncates_distribution(self) -> bool:
|
||||
return self.top_p < 1.0 or self.top_k is not None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_no_extra_body_truncation(self):
|
||||
"""Truncating values must come from the typed fields — the replay policy reads
|
||||
them. Disabled values pass so resolved configs (where ``resolve_env_config``
|
||||
stamped the ``top_k = -1`` / ``min_p = 0.0`` sentinels) re-validate cleanly."""
|
||||
smuggled = [
|
||||
key
|
||||
for key, truncates in (
|
||||
("top_p", self.extra_body.get("top_p", 1.0) < 1.0),
|
||||
("top_k", self.extra_body.get("top_k") not in (None, -1, 0)),
|
||||
("min_p", self.extra_body.get("min_p", 0.0) > 0.0),
|
||||
)
|
||||
if truncates
|
||||
]
|
||||
if smuggled:
|
||||
raise ValueError(
|
||||
f"extra_body carries truncating {smuggled}; set them as fields on the train "
|
||||
"sampling config instead (they drive sampling replay)."
|
||||
)
|
||||
return self
|
||||
|
||||
def to_sampling_args(self) -> dict[str, Any]:
|
||||
"""Convert to OAI-compatible sampling args dict, omitting None values."""
|
||||
args: dict[str, Any] = {
|
||||
"temperature": self.temperature,
|
||||
"top_p": 1.0,
|
||||
"top_p": self.top_p,
|
||||
"logprobs": True,
|
||||
}
|
||||
if self.max_completion_tokens is not None:
|
||||
args["max_completion_tokens"] = self.max_completion_tokens
|
||||
|
||||
if self.extra_body:
|
||||
args["extra_body"] = dict(self.extra_body)
|
||||
# top_k rides extra_body (like EvalSamplingConfig), overriding the sentinel.
|
||||
extra_body = dict(self.extra_body)
|
||||
if self.top_k is not None:
|
||||
extra_body["top_k"] = self.top_k
|
||||
if extra_body:
|
||||
args["extra_body"] = extra_body
|
||||
|
||||
return args
|
||||
|
||||
@@ -442,6 +481,15 @@ class ConcurrencyConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
# Top-k injected on truncated policy sampling that has none, and the hard upper
|
||||
# bound for explicit top-k. vLLM's native sampling-mask capture requires a
|
||||
# per-request top_k > 0 to bound mask sizes, and the trainer pads each micro
|
||||
# batch's masks to the largest sampling mask, so the bound also caps trainer
|
||||
# mask tensors. Large enough that a 0.95-0.99 nucleus rarely reaches it (the
|
||||
# sampling policy is essentially unchanged).
|
||||
TRAIN_TOP_K_BOUND = 512
|
||||
|
||||
|
||||
class OrchestratorConfig(BaseConfig):
|
||||
algo: AlgoConfig = GRPOAlgoConfig()
|
||||
"""Training algorithm: sampling plus the per-token training signal (credit
|
||||
@@ -568,6 +616,55 @@ class OrchestratorConfig(BaseConfig):
|
||||
env_cfg.algo.validate_env(env_cfg.env)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def setup_truncated_sampling(self):
|
||||
"""Truncated policy sampling trains with sampling replay (rollout
|
||||
logprobs are renormalized — see docs/inference.md, Sampling Replay).
|
||||
Owned here: every truncating config gets a top-k bound (bounds the sampling
|
||||
masks); opd/opsd is rejected (full-vocab prefill refs would mix
|
||||
normalizations). Frozen-source envs sample externally and are exempt."""
|
||||
policy_samplings = [
|
||||
env.sampling for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
|
||||
] or ([self.train.sampling] if not self.train.source else [])
|
||||
truncating = [sampling for sampling in policy_samplings if sampling.truncates_distribution()]
|
||||
if not truncating:
|
||||
return self
|
||||
|
||||
if any(sampling.temperature == 0 for sampling in truncating):
|
||||
raise ValueError(
|
||||
"Truncated train sampling (top_p/top_k) requires temperature > 0: greedy sampling has "
|
||||
"no truncated distribution to replay, and the inference server rejects such requests "
|
||||
"while sampling-mask capture is on."
|
||||
)
|
||||
|
||||
oversized = [sampling.top_k for sampling in truncating if (sampling.top_k or 0) > TRAIN_TOP_K_BOUND]
|
||||
if oversized:
|
||||
raise ValueError(
|
||||
f"Truncated train sampling with top_k = {max(oversized)} exceeds the sampling-replay "
|
||||
f"bound ({TRAIN_TOP_K_BOUND}): the trainer pads each micro batch's masks to the largest "
|
||||
f"sampling mask, so unbounded masks blow up trainer memory. Use top_k <= {TRAIN_TOP_K_BOUND}."
|
||||
)
|
||||
|
||||
unbounded = [sampling for sampling in truncating if sampling.top_k is None]
|
||||
if unbounded:
|
||||
warnings.warn(
|
||||
f"Truncated train sampling: defaulting top_k = {TRAIN_TOP_K_BOUND} so every sampling mask is "
|
||||
"bounded and sampling replay stays exact. Set top_k explicitly to override.",
|
||||
stacklevel=2,
|
||||
)
|
||||
for sampling in unbounded:
|
||||
sampling.top_k = TRAIN_TOP_K_BOUND
|
||||
|
||||
algos = [env.algo for env in self.train.source if env.algo is not None] or [self.algo]
|
||||
if any(algo.type in ("opd", "opsd") for algo in algos):
|
||||
raise ValueError(
|
||||
"opd/opsd is not supported with truncated train sampling: reference logprobs are full-vocab "
|
||||
"prefill scores while trainer logprobs are renormalized over the sampling mask, biasing the "
|
||||
"ref_kl term. Remove the truncation (top_p/top_k) or the opd/opsd algo."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@property
|
||||
def any_policy_sourced(self) -> bool:
|
||||
"""True when at least one train env samples rollouts from the live policy."""
|
||||
@@ -646,6 +743,23 @@ class OrchestratorConfig(BaseConfig):
|
||||
env.sampling.extra_body.setdefault("return_token_ids", True)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_policy_top_k_consistency(self):
|
||||
"""Require one top-k capture mode across the live policy server."""
|
||||
policy_sources = [
|
||||
env for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
|
||||
]
|
||||
enabled = [env for env in policy_sources if env.sampling.top_k is not None]
|
||||
disabled = [env for env in policy_sources if env.sampling.top_k is None]
|
||||
if enabled and disabled:
|
||||
names = ", ".join(env.resolved_name for env in disabled)
|
||||
raise ValueError(
|
||||
"Live-policy train sources cannot mix top_k > 0 and top_k = -1 because "
|
||||
"sampling-mask capture is engine-wide. Set top_k > 0 for these sources: "
|
||||
f"{names}."
|
||||
)
|
||||
return self
|
||||
|
||||
@property
|
||||
def env_sources(self) -> list[tuple[str, EnvConfig]]:
|
||||
"""Every ``(split, source)`` this run pulls from, train first then eval — the
|
||||
|
||||
@@ -100,7 +100,7 @@ class SharedMonitorsConfig(BaseConfig):
|
||||
"""Shared W&B config. Propagated to trainer and orchestrator."""
|
||||
|
||||
file: FileMonitorConfig | None = None
|
||||
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator."""
|
||||
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/monitors/file/metrics.jsonl`` on both trainer and orchestrator."""
|
||||
|
||||
prime: PrimeMonitorConfig | None = None
|
||||
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
|
||||
@@ -640,6 +640,53 @@ class RLConfig(BaseConfig):
|
||||
raise ValueError("Multi-node deployments require inference.router to front the per-rank engines.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_sampling_mask_capture(self):
|
||||
"""Truncated train sampling needs the inference server to return the sampling
|
||||
masks the trainer replays (OrchestratorConfig guarantees truncating
|
||||
configs are bounded by TRAIN_TOP_K_BOUND). Capture is engine-wide: while it is
|
||||
on, vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0``,
|
||||
so eval sampling against the same server must set both."""
|
||||
policy_samplings = [
|
||||
env.sampling
|
||||
for env in self.orchestrator.train.source
|
||||
if env.algo is not None and env.algo.sampling.source == "policy"
|
||||
] or ([self.orchestrator.train.sampling] if not self.orchestrator.train.source else [])
|
||||
if not any(sampling.truncates_distribution() for sampling in policy_samplings):
|
||||
return self
|
||||
if self.inference is None:
|
||||
warnings.warn(
|
||||
"Truncated train sampling with no managed inference server: set "
|
||||
"`enable_return_sampling_mask = true` on the standalone server's config so it "
|
||||
"returns the sampling masks the trainer replays.",
|
||||
stacklevel=2,
|
||||
)
|
||||
return self
|
||||
self.inference.enable_return_sampling_mask = True
|
||||
if self.orchestrator.eval is not None:
|
||||
warnings.warn(
|
||||
"Sampling-mask capture is engine-wide: eval requests without top_k > 0 (from the "
|
||||
"eval sampling config or the model's generation config) or with temperature 0 are "
|
||||
"rejected by the inference server while truncated train sampling is on.",
|
||||
stacklevel=2,
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
inference = self.inference
|
||||
if (
|
||||
inference is not None
|
||||
and inference.deployment.type == "disaggregated"
|
||||
and inference.enable_return_sampling_mask
|
||||
and inference.vllm.enable_return_routed_experts
|
||||
):
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_router_replay_without_kv_offload(self):
|
||||
if (
|
||||
|
||||
@@ -668,9 +668,6 @@ class TrainerConfig(BaseConfig):
|
||||
metrics_server: MetricsServerConfig | None = None
|
||||
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
|
||||
|
||||
enable_token_export: bool = False
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"verifiers[harbor]>=0.3.1",
|
||||
"renderers[multimodal]>=0.1.11",
|
||||
"renderers[multimodal]>=0.1.12.dev2",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
"pandas>=2.0",
|
||||
|
||||
@@ -86,16 +86,6 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
|
||||
|
||||
In TOML, an empty section header (`[ckpt]`) does the same.
|
||||
|
||||
## RL trainer token exports
|
||||
|
||||
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `<run_dir>/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
|
||||
```toml
|
||||
enable_token_export = true
|
||||
```
|
||||
|
||||
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
|
||||
|
||||
## Key files
|
||||
|
||||
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
|
||||
|
||||
@@ -73,7 +73,9 @@ curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view
|
||||
|
||||
`run` is required; other fields are optional and leave unspecified UI state
|
||||
unchanged. For trace evidence, supply `step`, `kind`, and `subset` together and
|
||||
address the episode by stable `id`. Use optional `trace` and `branch` indices
|
||||
address the episode by stable `id`. The traces tab opens on the whole stream;
|
||||
`subset: "effective"` switches it to the cohort that shipped at one step. Use
|
||||
optional `trace` and `branch` indices
|
||||
for multi-agent traces and `highlight` entries shaped as `{node, quote,
|
||||
reason, field?}`. On `409`, tell the user to open the returned `url`; the stored
|
||||
command applies when the tab connects.
|
||||
|
||||
@@ -50,15 +50,15 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
|
||||
|
||||
- `{run_dir}/configs/latest/` — the current attempt's command, launch TOML, and `resolved/` JSON files. Each launch stays under `configs/attempt_<n>/`.
|
||||
- `{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 episodes (see Episodes below).
|
||||
- `{run_dir}/monitors/file/` — the metrics, and the traces with the annotations about them (see Episodes below).
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR` if set; several dirs can be tracked at
|
||||
once) serves a local web dashboard at `http://localhost:7788` with four views per run:
|
||||
metrics (the W&B overview sections, read from `metrics.jsonl`), per-attempt config
|
||||
files, a rollout trace viewer with a per-token advantage/logprob view, and merged
|
||||
component logs. It only reads the run dirs — safe to run against a live run.
|
||||
files, a rollout trace viewer with per-token overlays (advantage, trainer logprob,
|
||||
entropy, KL mismatch, stable/loss/content masks), and merged component logs. It only reads the run dirs — safe to run against a live run.
|
||||
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
|
||||
free one, so several dashboards run side by side without coordination. GPU deps live
|
||||
behind the `gpu` extra, so `uv sync --extra dashboard && uv run dashboard` works
|
||||
@@ -162,27 +162,47 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
### Episodes
|
||||
|
||||
```
|
||||
{run_dir}/rollouts/step_{n}/{train,eval}/all/traces.jsonl # appended per episode as it completes
|
||||
{run_dir}/rollouts/step_{n}/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
{run_dir}/monitors/file/metrics.jsonl # every metric row, tagged by producer
|
||||
{run_dir}/monitors/file/traces/stream.jsonl # every episode, appended as it arrives
|
||||
{run_dir}/monitors/file/traces/stream.index.jsonl # one compact row per episode, with its byte offset
|
||||
{run_dir}/monitors/file/traces/annotations/{producer}.jsonl # trace updates: orch ship-time facts, trainer per-token streams
|
||||
{run_dir}/monitors/file/traces/annotations/{producer}.index.jsonl # each update's scalars and where its record sits
|
||||
```
|
||||
|
||||
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
|
||||
`all` gets every completed episode as it arrives — including trace-less failures,
|
||||
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`),
|
||||
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.
|
||||
Everything the file monitor dumps lives under `monitors/file/`; nothing is written
|
||||
there when the monitor is off. The traces and everything written about them sit under
|
||||
`traces/`, and every index is named for the stream it indexes and sits beside it. Those
|
||||
indexes are what keep reading a run cheap: a consumer browses them instead of the
|
||||
streams, and seeks by the offsets they carry to read a single episode or its token
|
||||
streams. Both are derived, so deleting them only costs a reader the work of rebuilding
|
||||
what it needs. `stream.jsonl` is a stream of native `vf.Episode`
|
||||
records (training tensors excluded), one line per episode in arrival order, whatever
|
||||
kind of work it did — including trace-less failures, curriculum-rejected work, and
|
||||
work that never enters a batch, so it is crash-durable. Each record carries its
|
||||
provenance: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
|
||||
and `run`.
|
||||
|
||||
A trace has several steps, so each is stamped as its own event rather than implied by
|
||||
where the record sits. The file monitor stamps `info.kind` and `info.dispatch`/
|
||||
`info.arrival` (`{step, time}` each) as an episode lands; the ship-time annotation adds
|
||||
`info.effective` and `info.ship` — the orchestrator step whose batch shipped the
|
||||
cohort, or for eval the step that produced the policy it measured. Staleness is
|
||||
`ship.step - dispatch.step`. Only `effective` ties to a step; `all` is the whole stream.
|
||||
|
||||
Everything learned after arrival is an append-only trace update keyed by `trace_id`,
|
||||
one file per producer so each has a single writer: the orchestrator records cohort
|
||||
membership, the scalar advantage and per-branch advantage streams; the trainer records
|
||||
its recomputed per-token logprobs and entropies. Readers fold the updates onto the
|
||||
stream records, newest winning.
|
||||
|
||||
```bash
|
||||
wc -l {run_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
|
||||
jq '.traces[].rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
wc -l {run_dir}/monitors/file/traces/stream.jsonl
|
||||
jq '.traces[].rewards' {run_dir}/monitors/file/traces/stream.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/monitors/file/traces/stream.jsonl
|
||||
jq '{trace_id, info}' {run_dir}/monitors/file/traces/annotations/orch.jsonl
|
||||
```
|
||||
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/batches/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank).
|
||||
|
||||
### Common failure modes
|
||||
|
||||
|
||||
@@ -97,7 +97,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]` (`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. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
|
||||
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. Add `[ckpt]` (`interval` counts completed task groups in the eval-source order) to make the run interruptible, then use `--resume`, `--resume.step N`, or `--resume.dir path/to/checkpoints/step_N`; for standalone evals, checkpoint step N means resume from task cursor N. Checkpoints store only the cursor, not generated episode records; partially completed groups and groups beyond the durable cursor are retried. Resume loads without `[ckpt]` but does not save new checkpoints. Checkpoint/resume is rejected with `[online]` because that process is coupled to the trainer's live broadcast handshake. 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. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow 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
|
||||
@@ -122,6 +122,9 @@ group_size = 4
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # optional: make a standalone eval resumable
|
||||
interval = 10 # completed task groups between cursor saves
|
||||
```
|
||||
|
||||
- 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/latest/envs/eval/{name}.log`.
|
||||
|
||||
+462
-245
@@ -2,8 +2,8 @@
|
||||
|
||||
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
|
||||
|
||||
Reads everything from run output directories (metrics.jsonl, logs/attempt_N,
|
||||
rollouts/step_N) — no wandb or network required. Usage:
|
||||
Reads everything from run output directories (the file monitor's metrics and trace
|
||||
streams, logs/attempt_N) — no wandb or network required. Usage:
|
||||
|
||||
uv run dashboard [output_dir ...] [--port 7788] [--host 127.0.0.1]
|
||||
|
||||
@@ -13,6 +13,7 @@ Multiple output directories can be tracked at once.
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
@@ -23,7 +24,11 @@ from pathlib import Path
|
||||
import orjson
|
||||
|
||||
from prime_rl.entrypoints.dashboard import DAEMON_FILE, DIRS_FILE, STATE_DIR, registry_lock
|
||||
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
|
||||
from prime_rl.monitors.file.traces.index import summarize_episode
|
||||
from prime_rl.monitors.file.traces.update import branch_node_paths, fold_trace_updates
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
try:
|
||||
@@ -68,16 +73,18 @@ def _lru_put(cache: OrderedDict, key, value) -> None:
|
||||
# Append-only file caches keyed by absolute path: line-start offsets and per-episode summaries.
|
||||
_offsets_cache: OrderedDict[Path, tuple[int, bytes, list[int]]] = OrderedDict()
|
||||
_summaries_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
|
||||
_annotations_cache: OrderedDict[Path, tuple[tuple, dict[str, dict], dict[Path, int]]] = OrderedDict()
|
||||
_index_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
|
||||
_rows_cache: OrderedDict[Path, tuple] = OrderedDict() # key, rows, entered, by_trace, consumed, last row
|
||||
_tokenizer_cache: dict[str, object] = {}
|
||||
_piece_cache: dict[tuple[str, int], str] = {}
|
||||
_json_cache: dict[Path, tuple[tuple[int, float], dict]] = {}
|
||||
_steps_cache: dict[Path, tuple[float, list[int]]] = {}
|
||||
|
||||
|
||||
def is_run_dir(path: Path) -> bool:
|
||||
if not path.is_dir() or path.name.startswith("."):
|
||||
return False
|
||||
return any((path / marker).exists() for marker in ("configs", "logs", "metrics.jsonl", "rollouts"))
|
||||
return any((path / marker).exists() for marker in ("configs", "logs", "monitors", "traces.jsonl"))
|
||||
|
||||
|
||||
_dirs_file_state: tuple[float, list[Path]] = (0.0, [])
|
||||
@@ -193,15 +200,6 @@ def numbered_dirs(parent: Path, prefix: str) -> list[tuple[int, Path]]:
|
||||
)
|
||||
|
||||
|
||||
def size_etag(path: Path, etag: str | None) -> tuple[str, dict | None]:
|
||||
"""Etag = file size: the trace files are append-only, so an unchanged size means
|
||||
an unchanged response. Returns (current_etag, short-circuit response or None)."""
|
||||
current = str(path.stat().st_size)
|
||||
if etag is not None and etag == current:
|
||||
return current, {"unchanged": True, "etag": current}
|
||||
return current, None
|
||||
|
||||
|
||||
def model_name(config: dict) -> str | None:
|
||||
"""`model` is a string on eval configs, a {name} object on rl/sft ones."""
|
||||
model = config.get("model")
|
||||
@@ -248,22 +246,14 @@ def attempt_numbers(run_dir: Path) -> list[int]:
|
||||
return [n for n, _ in numbered_dirs(run_dir / "logs", "attempt_")]
|
||||
|
||||
|
||||
def metrics_file(run_dir: Path) -> Path:
|
||||
"""The run's metric stream, as the file monitor dumps it."""
|
||||
return get_file_monitor_dir(run_dir) / "metrics.jsonl"
|
||||
|
||||
|
||||
def step_numbers(run_dir: Path) -> list[int]:
|
||||
"""Rollout step numbers, cached by the rollouts dir mtime (which changes when a
|
||||
step dir is created) — polled per run on every /api/runs tick."""
|
||||
rollouts = run_dir / "rollouts"
|
||||
try:
|
||||
mtime = rollouts.stat().st_mtime
|
||||
except OSError:
|
||||
return []
|
||||
with _lock:
|
||||
cached = _steps_cache.get(rollouts)
|
||||
if cached and cached[0] == mtime:
|
||||
return cached[1]
|
||||
steps = [n for n, _ in numbered_dirs(rollouts, "step_")]
|
||||
with _lock:
|
||||
_steps_cache[rollouts] = (mtime, steps)
|
||||
return steps
|
||||
"""The steps a cohort shipped at — what a run's progress is measured in."""
|
||||
return sorted({step for _, step in effective_steps(run_dir)})
|
||||
|
||||
|
||||
def run_meta(run_dir: Path) -> dict:
|
||||
@@ -275,7 +265,7 @@ def run_meta(run_dir: Path) -> dict:
|
||||
return sorted(p.stem for p in (resolved / "envs" / split).glob("*.json"))
|
||||
|
||||
steps = step_numbers(run_dir)
|
||||
metrics_path = run_dir / "metrics.jsonl"
|
||||
metrics_path = metrics_file(run_dir)
|
||||
started = updated = None
|
||||
if metrics_path.is_file():
|
||||
updated = metrics_path.stat().st_mtime
|
||||
@@ -286,9 +276,9 @@ def run_meta(run_dir: Path) -> dict:
|
||||
started = orjson.loads(f.readline()).get("time")
|
||||
except orjson.JSONDecodeError:
|
||||
started = None
|
||||
root_traces = run_dir / "traces.jsonl"
|
||||
if updated is None and root_traces.is_file(): # eval runs have no metrics.jsonl
|
||||
updated = root_traces.stat().st_mtime
|
||||
stream = traces_file(run_dir)
|
||||
if updated is None and stream is not None: # eval runs have no metrics
|
||||
updated = stream.stat().st_mtime
|
||||
started = configs.stat().st_mtime if configs.is_dir() else None
|
||||
return {
|
||||
"name": run_dir.name,
|
||||
@@ -504,7 +494,7 @@ so the first charts paint long before a 100MB metrics.jsonl finishes loading."""
|
||||
|
||||
@app.get("/api/runs/{run}/metrics")
|
||||
def read_metrics(run: str, offset: int = 0) -> dict:
|
||||
path = get_run_dir(run) / "metrics.jsonl"
|
||||
path = metrics_file(get_run_dir(run))
|
||||
if not path.is_file():
|
||||
return {"rows": [], "offset": 0, "size": 0}
|
||||
size = path.stat().st_size
|
||||
@@ -528,49 +518,32 @@ def read_metrics(run: str, offset: int = 0) -> dict:
|
||||
# ------------------------------------------------------------------------ rollouts
|
||||
|
||||
|
||||
RECENT_STEPS = 64
|
||||
_avail_cache: dict[Path, dict[str, bool]] = {} # step dir -> known-present subsets
|
||||
_avail_scan_counter = 0
|
||||
def traces_file(run_dir: Path) -> Path | None:
|
||||
"""The run's episode stream. prime-rl dumps it through the file monitor; a
|
||||
verifiers ``uv run eval`` run writes its own at the run root."""
|
||||
for path in (get_trace_stream(run_dir), run_dir / "traces.jsonl"):
|
||||
if path.is_file() and path.stat().st_size > 0:
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
EVAL_ROOT_STEP = (0, "eval", "all")
|
||||
"""The virtual address of a stepless `uv run eval` run's root traces.jsonl —
|
||||
the one convention shared by the step listing and traces_path."""
|
||||
|
||||
|
||||
def eval_root_traces(run_dir: Path) -> Path | None:
|
||||
root = run_dir / "traces.jsonl"
|
||||
return root if root.is_file() and root.stat().st_size > 0 else None
|
||||
def require_stream(run_dir: Path) -> Path:
|
||||
path = traces_file(run_dir)
|
||||
if path is None:
|
||||
raise HTTPException(404, "no traces for this run")
|
||||
return path
|
||||
|
||||
|
||||
def rollout_steps(run_dir: Path) -> list[dict]:
|
||||
"""Presence only — never reads trace files. Presence is monotonic (files only
|
||||
appear), so known-present subsets are cached forever; absent ones re-stat every
|
||||
poll only for the newest steps — older gaps (an eval landing late at its trigger
|
||||
step) are picked up by a full rescan every 10th call."""
|
||||
global _avail_scan_counter
|
||||
_avail_scan_counter += 1
|
||||
full_rescan = _avail_scan_counter % 10 == 1
|
||||
numbered = numbered_dirs(run_dir / "rollouts", "step_")
|
||||
recent_cutoff = numbered[-1][0] - RECENT_STEPS if numbered else 0
|
||||
steps = []
|
||||
for number, step_dir in numbered:
|
||||
available = _avail_cache.setdefault(step_dir, {})
|
||||
if len(available) < 4 and (full_rescan or number >= recent_cutoff):
|
||||
for kind in ("train", "eval"):
|
||||
for subset in ("all", "effective"):
|
||||
key = f"{kind}/{subset}"
|
||||
if key in available:
|
||||
continue
|
||||
path = step_dir / kind / subset / "traces.jsonl"
|
||||
if path.is_file() and path.stat().st_size > 0:
|
||||
available[key] = True
|
||||
if available:
|
||||
steps.append({"step": number, "available": available})
|
||||
root = eval_root_traces(run_dir)
|
||||
if not steps and root is not None:
|
||||
steps.append({"step": EVAL_ROOT_STEP[0], "available": {f"{EVAL_ROOT_STEP[1]}/{EVAL_ROOT_STEP[2]}": True}})
|
||||
return steps
|
||||
"""The steps a cohort can be addressed by, and the kinds of work each one holds.
|
||||
|
||||
Only a cohort ties to a step — the orchestrator step whose batch shipped it, or
|
||||
for eval the policy version it measured — so the steps come from the annotations.
|
||||
The stream itself is not addressed by step."""
|
||||
by_step: dict[int, set[str]] = {}
|
||||
for kind, step in effective_steps(run_dir):
|
||||
by_step.setdefault(step, set()).add(kind)
|
||||
return [{"step": step, "kinds": sorted(kinds)} for step, kinds in sorted(by_step.items())]
|
||||
|
||||
|
||||
def line_offsets(path: Path) -> list[int]:
|
||||
@@ -616,88 +589,6 @@ def line_offsets(path: Path) -> list[int]:
|
||||
return current
|
||||
|
||||
|
||||
def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
|
||||
"""Flatten a trace timing tree to phase -> seconds (same walk as the viewer)."""
|
||||
if isinstance(obj.get("duration"), (int, float)):
|
||||
out[prefix] = out.get(prefix, 0.0) + obj["duration"]
|
||||
elif isinstance(obj.get("start"), (int, float)) and isinstance(obj.get("end"), (int, float)):
|
||||
out[prefix] = out.get(prefix, 0.0) + (obj["end"] - obj["start"])
|
||||
for key, value in obj.items():
|
||||
if isinstance(value, dict):
|
||||
walk_timing(value, f"{prefix}/{key}" if prefix else key, out)
|
||||
|
||||
|
||||
def summarize_episode(line: int, rec: dict) -> dict:
|
||||
rewards, advantages = [], []
|
||||
input_tokens = output_tokens = turns = branches = 0
|
||||
stop_condition = None
|
||||
reward_parts: dict[str, list[float]] = {}
|
||||
metric_parts: dict[str, list[float]] = {}
|
||||
timing: dict[str, float] = {}
|
||||
costs: list[float] = []
|
||||
for trace in rec.get("traces") or []:
|
||||
costs.extend(
|
||||
usage["cost"]
|
||||
for call in trace.get("calls") or []
|
||||
if isinstance(usage := call.get("usage") or {}, dict) and isinstance(usage.get("cost"), (int, float))
|
||||
)
|
||||
nodes = trace.get("nodes") or []
|
||||
parents = {node.get("parent") for node in nodes if "parent" in node}
|
||||
branches += max(0, len(nodes) - len(parents))
|
||||
if trace.get("rewards"): # skip reward-less seats (e.g. a judge) in the episode mean
|
||||
rewards.append(
|
||||
sum(
|
||||
(r.get("score") or 0) * (r.get("weight") if r.get("weight") is not None else 1)
|
||||
for r in trace["rewards"].values()
|
||||
if isinstance(r, dict)
|
||||
)
|
||||
)
|
||||
for name, r in (trace.get("rewards") or {}).items():
|
||||
if isinstance(r, dict) and isinstance(r.get("score"), (int, float)):
|
||||
reward_parts.setdefault(name, []).append(r["score"])
|
||||
for name, value in (trace.get("metrics") or {}).items():
|
||||
if isinstance(value, (int, float)):
|
||||
metric_parts.setdefault(name, []).append(value)
|
||||
if isinstance(trace.get("timing"), dict):
|
||||
walk_timing(trace["timing"], "", timing)
|
||||
advantage = (trace.get("info") or {}).get("advantage")
|
||||
if advantage is not None:
|
||||
advantages.append(advantage)
|
||||
for node in nodes:
|
||||
n_tokens = len(node.get("token_ids") or [])
|
||||
if node.get("sampled"):
|
||||
output_tokens += n_tokens
|
||||
else:
|
||||
input_tokens += n_tokens
|
||||
if (node.get("message") or {}).get("role") == "assistant":
|
||||
turns += 1
|
||||
stop_condition = trace.get("stop_condition", stop_condition)
|
||||
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
|
||||
for call in trace.get("calls") or []:
|
||||
usage = call.get("usage") or {}
|
||||
input_tokens += usage.get("prompt_tokens") or 0
|
||||
output_tokens += usage.get("completion_tokens") or 0
|
||||
return {
|
||||
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
|
||||
"metrics": {name: sum(v) / len(v) for name, v in metric_parts.items()},
|
||||
"timing": timing,
|
||||
"cost": sum(costs) if costs else None,
|
||||
"line": line,
|
||||
"id": rec.get("id"),
|
||||
"env": (rec.get("env") or {}).get("id") or (rec.get("env") or {}).get("name"),
|
||||
"group": (rec.get("group") or {}).get("id"),
|
||||
"ok": rec.get("ok"),
|
||||
"num_errors": len(rec.get("errors") or []),
|
||||
"reward": sum(rewards) / len(rewards) if rewards else None,
|
||||
"advantage": sum(advantages) / len(advantages) if advantages else None,
|
||||
"input_tokens": input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"turns": turns,
|
||||
"branches": branches,
|
||||
"stop_condition": stop_condition,
|
||||
}
|
||||
|
||||
|
||||
def episode_summaries(path: Path) -> list[dict]:
|
||||
offsets = line_offsets(path)
|
||||
with _lock:
|
||||
@@ -719,9 +610,9 @@ def episode_summaries(path: Path) -> list[dict]:
|
||||
for line_no in range(cached_count, len(offsets)):
|
||||
raw = f.readline()
|
||||
try:
|
||||
summaries.append(summarize_episode(line_no, orjson.loads(raw)))
|
||||
summaries.append(summarize_episode(line_no + 1, orjson.loads(raw)))
|
||||
except orjson.JSONDecodeError:
|
||||
summaries.append({"line": line_no, "id": None, "error": "unparseable"})
|
||||
summaries.append({"line": line_no + 1, "id": None, "error": "unparseable"})
|
||||
with _lock:
|
||||
_lru_put(_summaries_cache, path, (len(offsets), summaries))
|
||||
write_sidecar(path, summaries)
|
||||
@@ -733,6 +624,7 @@ def episode_summaries(path: Path) -> list[dict]:
|
||||
# result is persisted outside the run dir (the dashboard never writes there),
|
||||
# so a revisit — or a dashboard restart — skips the parse entirely.
|
||||
SIDECAR_DIR = STATE_DIR
|
||||
SIDECAR_FORMAT = 4
|
||||
SIDECAR_WRITE_INTERVAL_S = 20.0
|
||||
_sidecar_written: dict[Path, tuple[float, int]] = {} # path -> (last write time, count)
|
||||
|
||||
@@ -758,7 +650,8 @@ def load_sidecar(path: Path) -> list[dict] | None:
|
||||
data = read_json(sidecar_path(path))
|
||||
try:
|
||||
if (
|
||||
data.get("path") != str(path.resolve())
|
||||
data.get("format") != SIDECAR_FORMAT
|
||||
or data.get("path") != str(path.resolve())
|
||||
or path.stat().st_size < data["size"]
|
||||
or data.get("checkpoint") != file_checkpoint(path, data["size"]).hex()
|
||||
):
|
||||
@@ -777,6 +670,7 @@ def write_sidecar(path: Path, summaries: list[dict]) -> None:
|
||||
SIDECAR_DIR.mkdir(parents=True, exist_ok=True)
|
||||
size = path.stat().st_size
|
||||
payload = {
|
||||
"format": SIDECAR_FORMAT,
|
||||
"path": str(path.resolve()),
|
||||
"size": size,
|
||||
"checkpoint": file_checkpoint(path, size).hex(),
|
||||
@@ -789,26 +683,11 @@ def write_sidecar(path: Path, summaries: list[dict]) -> None:
|
||||
|
||||
|
||||
def traces_path(run: str, step: int, kind: str, subset: str) -> Path:
|
||||
"""The run's episode stream. ``step``/``kind``/``subset`` never select a file —
|
||||
every episode is on disk exactly once — they select the read-time filter."""
|
||||
if kind not in ("train", "eval") or subset not in ("all", "effective"):
|
||||
raise HTTPException(400, "kind must be train|eval, subset all|effective")
|
||||
run_dir = get_run_dir(run)
|
||||
path = run_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
|
||||
if path.is_file():
|
||||
return path
|
||||
if (step, kind, subset) == EVAL_ROOT_STEP:
|
||||
root = eval_root_traces(run_dir)
|
||||
if root is not None:
|
||||
return root
|
||||
raise HTTPException(404, "no traces for this step/kind/subset")
|
||||
|
||||
|
||||
def read_episode_record(path: Path, line: int) -> dict:
|
||||
offsets = line_offsets(path)
|
||||
if not 0 <= line < len(offsets):
|
||||
raise HTTPException(404, "episode line out of range")
|
||||
with path.open("rb") as f:
|
||||
f.seek(offsets[line])
|
||||
return orjson.loads(f.readline())
|
||||
return require_stream(get_run_dir(run))
|
||||
|
||||
|
||||
def message_text(message: dict) -> str:
|
||||
@@ -838,22 +717,111 @@ def timeline_reward(trace: dict) -> float | None:
|
||||
)
|
||||
|
||||
|
||||
def trace_branch_paths(nodes: list[dict]) -> list[list[int]]:
|
||||
"""Return VF-native root-to-leaf branches in leaf-index order."""
|
||||
if not nodes:
|
||||
def _file_size(path: Path) -> int:
|
||||
try:
|
||||
return path.stat().st_size
|
||||
except OSError:
|
||||
return -1
|
||||
|
||||
|
||||
def annotations_files(run_dir: Path) -> list[Path]:
|
||||
"""The annotation records themselves, one file per producer — their indexes are
|
||||
named for them, so a name that is already an index is one of those."""
|
||||
directory = get_annotations_dir(run_dir)
|
||||
if not directory.is_dir():
|
||||
return []
|
||||
parents = {parent for node in nodes if isinstance((parent := node.get("parent")), int) and 0 <= parent < len(nodes)}
|
||||
paths = []
|
||||
for leaf in (index for index in range(len(nodes)) if index not in parents):
|
||||
path = []
|
||||
seen = set()
|
||||
node_index: int | None = leaf
|
||||
while isinstance(node_index, int) and 0 <= node_index < len(nodes) and node_index not in seen:
|
||||
seen.add(node_index)
|
||||
path.append(node_index)
|
||||
node_index = nodes[node_index].get("parent")
|
||||
paths.append(list(reversed(path)))
|
||||
return paths
|
||||
return sorted(path for path in directory.glob("*.jsonl") if not path.name.endswith(".index.jsonl"))
|
||||
|
||||
|
||||
def annotation_source(data: Path) -> Path:
|
||||
"""The file a producer's rows are read from: its index when it wrote one, else the
|
||||
records themselves. Whatever depends on those rows versions itself by this file's
|
||||
size - the record file can grow before its index row is flushed, and a version
|
||||
taken from it would miss the index completing."""
|
||||
index = get_index_path(data)
|
||||
return index if index.is_file() else data
|
||||
|
||||
|
||||
def annotation_rows(data: Path) -> list[dict]:
|
||||
"""A producer's updates as index rows - ``{trace_id, info, offset}`` - read from its
|
||||
index when it wrote one, and derived from the records themselves when it did not."""
|
||||
rows = index_rows(get_index_path(data))
|
||||
if rows is not None:
|
||||
return rows
|
||||
size = data.stat().st_size
|
||||
with _lock:
|
||||
cached = _lru_get(_index_cache, data)
|
||||
if cached and cached[0] == size:
|
||||
return cached[1]
|
||||
rows, offset = [], 0
|
||||
with data.open("rb") as f:
|
||||
for raw in f:
|
||||
try:
|
||||
update = orjson.loads(raw)
|
||||
except orjson.JSONDecodeError:
|
||||
break
|
||||
rows.append({"trace_id": update.get("trace_id"), "info": update.get("info"), "offset": offset})
|
||||
offset += len(raw)
|
||||
with _lock:
|
||||
_lru_put(_index_cache, data, (size, rows))
|
||||
return rows
|
||||
|
||||
|
||||
def annotation_index(run_dir: Path) -> dict[str, dict]:
|
||||
"""Trace id -> the scalars its updates carry, and where each record sits.
|
||||
|
||||
Reads the producers' indexes when they exist, so answering "which cohort, what
|
||||
credit" never touches the token streams — they can outweigh the traces themselves.
|
||||
A producer that wrote no index is read in full."""
|
||||
files = annotations_files(run_dir)
|
||||
key = tuple((data.name, _file_size(annotation_source(data))) for data in files)
|
||||
cache_key = get_annotations_dir(run_dir)
|
||||
with _lock:
|
||||
cached = _lru_get(_annotations_cache, cache_key)
|
||||
if cached and cached[0] == key:
|
||||
return cached[1]
|
||||
# Producers only append, so the fold resumes from the row each one was last read
|
||||
# to. The map is copied rather than grown in place: a request already iterating
|
||||
# the previous one must not see it change size under it.
|
||||
consumed, index = ({}, {}) if cached is None else (dict(cached[2]), dict(cached[1]))
|
||||
|
||||
def note(trace_id: str | None, info: dict, data: Path, offset: int) -> None:
|
||||
if not trace_id:
|
||||
return
|
||||
entry = index.setdefault(trace_id, {"info": {}, "at": []})
|
||||
entry["info"].update(info)
|
||||
entry["at"].append((data, offset))
|
||||
|
||||
for data in files:
|
||||
rows = annotation_rows(data)
|
||||
for row in rows[consumed.get(data, 0) :]:
|
||||
note(row.get("trace_id"), row.get("info") or {}, data, row.get("offset", 0))
|
||||
consumed[data] = len(rows)
|
||||
with _lock:
|
||||
_lru_put(_annotations_cache, cache_key, (key, index, consumed))
|
||||
return index
|
||||
|
||||
|
||||
def trace_updates(run_dir: Path, trace_id: str) -> list[dict]:
|
||||
"""Every update recorded against one trace, read by seeking to each record."""
|
||||
entry = annotation_index(run_dir).get(trace_id)
|
||||
updates = []
|
||||
for path, offset in (entry or {}).get("at", []):
|
||||
try:
|
||||
with path.open("rb") as f:
|
||||
f.seek(offset)
|
||||
updates.append(orjson.loads(f.readline()))
|
||||
except (OSError, orjson.JSONDecodeError):
|
||||
continue
|
||||
return updates
|
||||
|
||||
|
||||
def ipo_eps(run_dir: Path) -> float:
|
||||
"""The run's IPO threshold: how far a token's probability may move before the
|
||||
loss drops it. It is what the stable-mask overlay colours against."""
|
||||
loss = read_json(resolved_config_dir(run_dir) / "trainer.json").get("loss") or {}
|
||||
eps = loss.get("eps") if loss.get("type") == "ipo" else None
|
||||
return eps if isinstance(eps, (int, float)) else 0.1
|
||||
|
||||
|
||||
def token_usage(usage: dict) -> tuple[int | None, int | None, int | None]:
|
||||
@@ -1015,7 +983,7 @@ def project_episode_timeline(episode: dict) -> dict:
|
||||
lane_groups = []
|
||||
for trace_index, trace in enumerate(episode.get("traces") or []):
|
||||
nodes = trace.get("nodes") or []
|
||||
branch_paths = trace_branch_paths(nodes)
|
||||
branch_paths = branch_node_paths(nodes)
|
||||
node_branch_counts: dict[int, int] = {}
|
||||
for path in branch_paths:
|
||||
for node_index in path:
|
||||
@@ -1102,40 +1070,264 @@ def project_episode_timeline(episode: dict) -> dict:
|
||||
return {"lanes": lanes}
|
||||
|
||||
|
||||
NICE_BINS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400]
|
||||
|
||||
|
||||
def nice_bin(ideal: float) -> float:
|
||||
"""The smallest round interval at least this wide, so bars land on seconds,
|
||||
minutes or hours a reader recognises rather than 93.4s."""
|
||||
return next((step for step in NICE_BINS if step >= ideal), NICE_BINS[-1])
|
||||
|
||||
|
||||
SORT_KEYS = {"arrival", "duration", "reward", "output_tokens", "turns", "group"}
|
||||
|
||||
|
||||
def stream_index_file(run_dir: Path) -> Path:
|
||||
"""Where the stream's index would sit — beside the stream, named for it. A stream
|
||||
written by a producer that indexes nothing simply has no file there."""
|
||||
stream = traces_file(run_dir)
|
||||
return get_index_path(stream) if stream else get_index_path(get_trace_stream(run_dir))
|
||||
|
||||
|
||||
def index_rows(path: Path) -> list[dict] | None:
|
||||
"""The rows of an index the file monitor wrote, read incrementally: an index is
|
||||
append-only, so only the bytes past the last read are parsed. ``None`` when there
|
||||
is no index, which is the reader's cue to derive what it needs itself."""
|
||||
if not path.is_file():
|
||||
return None
|
||||
size = path.stat().st_size
|
||||
with _lock:
|
||||
cached = _lru_get(_index_cache, path)
|
||||
if cached and cached[0] == size:
|
||||
return cached[1]
|
||||
rows, read_from = (list(cached[1]), cached[0]) if cached and cached[0] < size else ([], 0)
|
||||
with path.open("rb") as f:
|
||||
f.seek(read_from)
|
||||
for raw in f:
|
||||
if not raw.endswith(b"\n"):
|
||||
break # a torn tail line: the writer is mid-append
|
||||
try:
|
||||
rows.append(orjson.loads(raw))
|
||||
except orjson.JSONDecodeError:
|
||||
break
|
||||
read_from += len(raw)
|
||||
with _lock:
|
||||
_lru_put(_index_cache, path, (read_from, rows))
|
||||
return rows
|
||||
|
||||
|
||||
def written_index(run_dir: Path) -> list[dict] | None:
|
||||
"""The stream's own index, when the stream's producer wrote one."""
|
||||
return index_rows(stream_index_file(run_dir))
|
||||
|
||||
|
||||
def episode_rows(run_dir: Path) -> list[dict]:
|
||||
"""The run's episode index: one row per episode of the stream, in arrival order,
|
||||
carrying the cohort step its annotations give it.
|
||||
|
||||
Everything here is append-only, so the work tracks the growth rather than the run:
|
||||
new episodes are entered as they arrive, and a new ship-time update stamps only the
|
||||
episodes that own its trace. A browse request pays for what changed since the last
|
||||
one, however long the run gets."""
|
||||
path = traces_file(run_dir)
|
||||
if path is None:
|
||||
return []
|
||||
files = annotations_files(run_dir)
|
||||
key = (
|
||||
_file_size(stream_index_file(run_dir)),
|
||||
path.stat().st_size,
|
||||
*(_file_size(annotation_source(f)) for f in files),
|
||||
)
|
||||
with _lock:
|
||||
cached = _lru_get(_rows_cache, run_dir)
|
||||
if cached and cached[0] == key:
|
||||
return cached[1]
|
||||
rows = written_index(run_dir)
|
||||
if rows is None:
|
||||
rows = episode_summaries(path)
|
||||
# Resume only over the very rows stamped last time: a shorter list is a rewrite,
|
||||
# and a list rebuilt from disk holds new dicts the trace map would no longer reach.
|
||||
entered = cached[2] if cached else 0
|
||||
resume = bool(cached) and len(rows) >= entered and (entered == 0 or rows[entered - 1] is cached[5])
|
||||
by_trace, consumed = (cached[3], dict(cached[4])) if resume else ({}, {})
|
||||
if not resume:
|
||||
entered = 0
|
||||
for row in rows[entered:]:
|
||||
row["step"] = None
|
||||
for trace_id in row.get("trace_ids") or []:
|
||||
by_trace.setdefault(trace_id, []).append(row)
|
||||
for data in files:
|
||||
updates = annotation_rows(data)
|
||||
for update in updates[consumed.get(data, 0) :]:
|
||||
info = update.get("info") or {}
|
||||
step = (info.get("ship") or {}).get("step")
|
||||
if not info.get("effective") or not isinstance(step, int):
|
||||
continue
|
||||
for row in by_trace.get(update.get("trace_id"), ()):
|
||||
row["step"] = step if row["step"] is None else min(row["step"], step)
|
||||
consumed[data] = len(updates)
|
||||
with _lock:
|
||||
_lru_put(_rows_cache, run_dir, (key, rows, len(rows), by_trace, consumed, rows[-1] if rows else None))
|
||||
return rows
|
||||
|
||||
|
||||
def row_filter(
|
||||
*,
|
||||
step: int | None = None,
|
||||
kind: str | None = None,
|
||||
env: str | None = None,
|
||||
episode: str | None = None,
|
||||
errors_only: bool = False,
|
||||
start: float | None = None,
|
||||
end: float | None = None,
|
||||
):
|
||||
"""A predicate over index rows. A step selects the cohort shipped at it — for
|
||||
train work the orchestrator step, for eval the policy version — which is the only
|
||||
sense in which an episode belongs to a step."""
|
||||
|
||||
def keep(row: dict) -> bool:
|
||||
if step is not None and row.get("step") != step:
|
||||
return False
|
||||
if kind and row.get("kind") != kind:
|
||||
return False
|
||||
if env and row.get("env") != env:
|
||||
return False
|
||||
if episode is not None and row.get("id") != episode:
|
||||
return False
|
||||
if errors_only and not (row.get("num_errors") or not row.get("ok")):
|
||||
return False
|
||||
arrival = row.get("arrival") or 0
|
||||
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
|
||||
|
||||
return keep
|
||||
|
||||
|
||||
def filter_rows(rows: list[dict], **narrow) -> list[dict]:
|
||||
keep = row_filter(**narrow)
|
||||
return [row for row in rows if keep(row)]
|
||||
|
||||
|
||||
def index_facets(run_dir: Path) -> tuple[list[str], list[str]]:
|
||||
"""The envs and kinds the stream holds, for the filter controls."""
|
||||
rows = episode_rows(run_dir)
|
||||
envs = {row["env"] for row in rows if row.get("env")}
|
||||
kinds = {row.get("kind") for row in rows}
|
||||
return sorted(envs), [kind for kind in ("train", "eval") if kind in kinds]
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/episodes")
|
||||
def list_stream_episodes(
|
||||
run: str,
|
||||
step: int | None = None,
|
||||
kind: str | None = None,
|
||||
env: str | None = None,
|
||||
episode: str | None = None,
|
||||
errors_only: bool = False,
|
||||
sort: str = "arrival",
|
||||
order: str = "desc",
|
||||
offset: int = Query(default=0, ge=0),
|
||||
limit: int = Query(default=128, ge=1, le=512),
|
||||
start: float | None = None,
|
||||
end: float | None = None,
|
||||
etag: str | None = None,
|
||||
upto: int | None = Query(default=None, ge=0),
|
||||
) -> dict:
|
||||
"""One page of the stream. The client scrolls by asking for the next offset, so a
|
||||
run of any length costs the same to browse.
|
||||
|
||||
A live stream grows at its head, which would shift every offset under a reader
|
||||
mid-scroll. ``upto`` pins the page to the stream as it stood at that many lines -
|
||||
the length the first page reported - so later pages address a list that no longer
|
||||
moves, whatever the sort."""
|
||||
run_dir = get_run_dir(run)
|
||||
path = require_stream(run_dir)
|
||||
current_etag = stream_etag(run_dir, path)
|
||||
if etag is not None and etag == current_etag and offset == 0:
|
||||
return {"unchanged": True, "etag": current_etag}
|
||||
rows = episode_rows(run_dir)
|
||||
lines = len(rows)
|
||||
if upto is not None:
|
||||
rows = rows[:upto]
|
||||
envs, kinds = index_facets(run_dir)
|
||||
keep = row_filter(step=step, kind=kind, env=env, episode=episode, errors_only=errors_only, start=start, end=end)
|
||||
if sort == "arrival":
|
||||
# the index is already in arrival order: walk it from the right end and stop
|
||||
# once the page is full, so the common view costs a page rather than a run
|
||||
ordered = reversed(rows) if order == "desc" else rows
|
||||
page, total = [], 0
|
||||
for row in ordered:
|
||||
if not keep(row):
|
||||
continue
|
||||
if offset <= total < offset + limit:
|
||||
page.append(row)
|
||||
total += 1
|
||||
else:
|
||||
matching = [row for row in rows if keep(row)]
|
||||
blank = "" if sort == "group" else 0
|
||||
if sort in SORT_KEYS:
|
||||
matching.sort(key=lambda row: (row.get(sort) is None, row.get(sort) or blank), reverse=order == "desc")
|
||||
page, total = matching[offset : offset + limit], len(matching)
|
||||
return {
|
||||
"etag": current_etag,
|
||||
"lines": lines,
|
||||
"total": total,
|
||||
"offset": offset,
|
||||
"envs": envs,
|
||||
"kinds": kinds,
|
||||
"episodes": page,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/episodes/histogram")
|
||||
def episode_histogram(
|
||||
run: str,
|
||||
step: int | None = None,
|
||||
kind: str | None = None,
|
||||
env: str | None = None,
|
||||
errors_only: bool = False,
|
||||
bars: int = Query(default=80, ge=8, le=500),
|
||||
) -> dict:
|
||||
"""Episodes finishing per time bin, over the same filters as the table — the
|
||||
stream's shape, and the thing you click to narrow it to a moment. The range fits
|
||||
the episodes and the bin is the roundest interval that keeps the bar count sane,
|
||||
so a run of any length reads the same."""
|
||||
run_dir = get_run_dir(run)
|
||||
rows = filter_rows(episode_rows(run_dir), step=step, kind=kind, env=env, errors_only=errors_only)
|
||||
arrivals = sorted(row["arrival"] for row in rows if isinstance(row.get("arrival"), (int, float)))
|
||||
if not arrivals:
|
||||
return {"bins": [], "bin": 60, "start": None, "end": None, "total": 0}
|
||||
bin = nice_bin(max(arrivals[-1] - arrivals[0], 1e-9) / bars)
|
||||
# square the edges to bin boundaries so the bars carry round timestamps
|
||||
start = math.floor(arrivals[0] / bin) * bin
|
||||
end = math.floor(arrivals[-1] / bin) * bin + bin
|
||||
counts: dict[int, int] = {}
|
||||
for arrival in arrivals:
|
||||
index = int((arrival - start) // bin)
|
||||
counts[index] = counts.get(index, 0) + 1
|
||||
span = max(1, int(round((end - start) / bin)))
|
||||
return {
|
||||
"bins": [[start + index * bin, counts.get(index, 0)] for index in range(span)],
|
||||
"bin": bin,
|
||||
"start": start,
|
||||
"end": end,
|
||||
"total": sum(counts.values()),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts")
|
||||
def list_rollouts(run: str) -> dict:
|
||||
return {"steps": rollout_steps(get_run_dir(run))}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}")
|
||||
def list_episodes(
|
||||
run: str,
|
||||
step: int,
|
||||
kind: str,
|
||||
subset: str,
|
||||
limit: int = Query(default=5000, ge=1, le=5000),
|
||||
episode: str | None = None,
|
||||
env: str | None = None,
|
||||
errors_only: bool = False,
|
||||
sort: str = "line",
|
||||
order: str = "asc",
|
||||
etag: str | None = None,
|
||||
) -> dict:
|
||||
path = traces_path(run, step, kind, subset)
|
||||
current_etag, unchanged = size_etag(path, etag)
|
||||
if unchanged:
|
||||
return unchanged
|
||||
summaries = episode_summaries(path)
|
||||
envs = sorted({s["env"] for s in summaries if s.get("env")})
|
||||
if episode is not None:
|
||||
summaries = [s for s in summaries if s.get("id") == episode]
|
||||
if env:
|
||||
summaries = [s for s in summaries if s.get("env") == env]
|
||||
if errors_only:
|
||||
summaries = [s for s in summaries if s.get("num_errors") or not s.get("ok")]
|
||||
if sort in ("reward", "advantage", "output_tokens", "turns", "group"):
|
||||
summaries = sorted(summaries, key=lambda s: (s.get(sort) is None, s.get(sort) or 0), reverse=(order == "desc"))
|
||||
return {"total": len(summaries), "etag": current_etag, "envs": envs, "episodes": summaries[:limit]}
|
||||
def stream_etag(run_dir: Path, path: Path) -> str:
|
||||
"""What a listing depends on: the stream, and the annotations that give its rows
|
||||
their cohort and credit. Both are append-only, so their sizes are the version."""
|
||||
return f"{path.stat().st_size}-{sum(_file_size(annotation_source(f)) for f in annotations_files(run_dir))}"
|
||||
|
||||
|
||||
def effective_steps(run_dir: Path) -> set[tuple[str, int]]:
|
||||
"""The (kind, step) pairs an effective cohort can be addressed by."""
|
||||
return {(row["kind"], row["step"]) for row in episode_rows(run_dir) if row.get("step") is not None}
|
||||
|
||||
|
||||
def get_tokenizer(model: str):
|
||||
@@ -1217,16 +1409,17 @@ def rendered_token_text(trace: dict, model: str | None) -> dict:
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/series")
|
||||
def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None = None, after: int = 0) -> dict:
|
||||
"""Per-episode series over a traces file (x = episode order): reward, shape, and the
|
||||
@app.get("/api/runs/{run}/episodes/series")
|
||||
def episode_series(run: str, kind: str | None = None, etag: str | None = None, after: int = 0) -> dict:
|
||||
"""Per-episode series over the stream (x = arrival order): reward, shape, and the
|
||||
nested rewards/metrics/timing keys — the metrics view for eval runs. `after` returns
|
||||
only episodes past that index, so a growing file ships increments, not the world."""
|
||||
path = traces_path(run, step, kind, subset)
|
||||
current_etag, unchanged = size_etag(path, etag)
|
||||
if unchanged:
|
||||
return unchanged
|
||||
summaries = episode_summaries(path)
|
||||
only episodes past that index, so a growing stream ships increments, not the world."""
|
||||
run_dir = get_run_dir(run)
|
||||
path = require_stream(run_dir)
|
||||
current_etag = stream_etag(run_dir, path)
|
||||
if etag is not None and etag == current_etag:
|
||||
return {"unchanged": True, "etag": current_etag}
|
||||
summaries = [s for s in episode_summaries(path) if not kind or s.get("kind") == kind]
|
||||
keys: set[str] = set()
|
||||
for s in summaries:
|
||||
keys.update(
|
||||
@@ -1246,30 +1439,53 @@ def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None
|
||||
return {"etag": current_etag, "count": len(summaries), "after": max(0, after), "series": series}
|
||||
|
||||
|
||||
def read_episode_at(path: Path, line: int) -> dict:
|
||||
offsets = line_offsets(path)
|
||||
if not 0 <= line < len(offsets):
|
||||
raise HTTPException(404, "episode line out of range")
|
||||
def read_episode_at(path: Path, line: int, offset: int | None = None) -> dict:
|
||||
"""One episode. A written index carries the byte offset, so reading it never
|
||||
touches the rest of the stream."""
|
||||
if offset is None:
|
||||
offsets = line_offsets(path)
|
||||
if not 1 <= line <= len(offsets):
|
||||
raise HTTPException(404, "episode line out of range")
|
||||
offset = offsets[line - 1]
|
||||
with path.open("rb") as f:
|
||||
f.seek(offsets[line])
|
||||
return orjson.loads(f.readline())
|
||||
f.seek(offset)
|
||||
try:
|
||||
return orjson.loads(f.readline())
|
||||
except orjson.JSONDecodeError as error:
|
||||
# a record torn by a crash, or the stream's last line caught mid-append
|
||||
raise HTTPException(422, f"episode {line} is unparseable") from error
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}")
|
||||
def episode_offset(run_dir: Path, line: int) -> int | None:
|
||||
rows = written_index(run_dir)
|
||||
if rows is None or not 1 <= line <= len(rows):
|
||||
return None
|
||||
return rows[line - 1].get("offset")
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/episodes/{line}")
|
||||
def get_episode(
|
||||
run: str,
|
||||
step: int,
|
||||
kind: str,
|
||||
subset: str,
|
||||
line: int,
|
||||
tokens: bool = False,
|
||||
rendered: bool = False,
|
||||
) -> dict:
|
||||
path = traces_path(run, step, kind, subset)
|
||||
rec = read_episode_at(path, line)
|
||||
"""One episode, by its line in the stream, with every annotation folded on."""
|
||||
run_dir = get_run_dir(run)
|
||||
path = require_stream(run_dir)
|
||||
rec = read_episode_at(path, line, episode_offset(run_dir, line))
|
||||
# only the opened episode's streams are read, by seeking to each of its records
|
||||
for trace in rec.get("traces") or []:
|
||||
updates = trace_updates(run_dir, trace.get("id") or "")
|
||||
if not updates:
|
||||
continue
|
||||
stamped = fold_trace_updates(trace, updates)
|
||||
if stamped:
|
||||
ship_step = ((trace.get("info") or {}).get("ship") or {}).get("step")
|
||||
trace["train_annotations"] = {"step": ship_step, "nodes": stamped, "eps": ipo_eps(run_dir)}
|
||||
if not tokens and not rendered:
|
||||
return rec
|
||||
fallback_model = model_name(main_config(get_run_dir(run))[1])
|
||||
fallback_model = model_name(main_config(run_dir)[1])
|
||||
for trace in rec.get("traces") or []:
|
||||
client = ((trace.get("agent") or {}).get("config") or {}).get("client") or {}
|
||||
model = client.get("renderer_model_name") or fallback_model
|
||||
@@ -1364,7 +1580,7 @@ def validate_view_command(cmd: dict) -> dict:
|
||||
|
||||
rec = None
|
||||
if episode is not None:
|
||||
matches = [s["line"] for s in episode_summaries(path) if s.get("id") == episode]
|
||||
matches = [row["line"] for row in episode_rows(get_run_dir(run)) if row.get("id") == episode]
|
||||
if not matches:
|
||||
raise HTTPException(404, f"episode id {episode!r} not found in {kind}/{subset} at step {step}")
|
||||
if len(matches) > 1:
|
||||
@@ -1468,9 +1684,10 @@ async def view_events() -> "StreamingResponse":
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}/timeline")
|
||||
def get_episode_timeline(run: str, step: int, kind: str, subset: str, line: int) -> dict:
|
||||
return project_episode_timeline(read_episode_at(traces_path(run, step, kind, subset), line))
|
||||
@app.get("/api/runs/{run}/episodes/{line}/timeline")
|
||||
def get_episode_timeline(run: str, line: int) -> dict:
|
||||
run_dir = get_run_dir(run)
|
||||
return project_episode_timeline(read_episode_at(require_stream(run_dir), line, episode_offset(run_dir, line)))
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------- static
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -78,48 +78,60 @@
|
||||
</section>
|
||||
|
||||
<section id="tab-traces" hidden>
|
||||
<div class="controls" id="step-bar">
|
||||
<div class="controls" id="trace-bar">
|
||||
<div class="seg" id="trace-mode">
|
||||
<button data-mode="stream" class="active" title="every episode, newest first">Stream</button>
|
||||
<button data-mode="step" title="the cohort shipped at one step">Step</button>
|
||||
</div>
|
||||
<div id="trace-filter-wrap" class="dd-wrap">
|
||||
<button id="trace-filter-btn" class="btn dd-btn" title="filter">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
|
||||
filter
|
||||
<span id="trace-filter-count" class="badge" hidden></span>
|
||||
</button>
|
||||
<div class="dd-menu dd-filters" id="trace-filter-menu" hidden>
|
||||
<div class="dd-sec">filter</div>
|
||||
<div class="dd-row"><span class="t-label">kind</span>
|
||||
<div class="seg toggle-seg" id="trace-kinds">
|
||||
<button data-kind="train" class="on">train</button>
|
||||
<button data-kind="eval" class="on">eval</button>
|
||||
</div>
|
||||
</div>
|
||||
<label class="dd-row"><span class="t-label">env</span>
|
||||
<select id="trace-env"><option value="">all envs</option></select>
|
||||
</label>
|
||||
<label class="toggle dd-row"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
|
||||
</div>
|
||||
</div>
|
||||
<select id="trace-sort" title="sort" data-label="sort">
|
||||
<option value="arrival:desc">arrival ↓</option>
|
||||
<option value="arrival:asc">arrival ↑</option>
|
||||
<option value="group:asc">group</option>
|
||||
<option value="duration:desc">total time ↓</option>
|
||||
<option value="duration:asc">total time ↑</option>
|
||||
<option value="reward:desc">reward ↓</option>
|
||||
<option value="reward:asc">reward ↑</option>
|
||||
<option value="output_tokens:desc">tokens ↓</option>
|
||||
</select>
|
||||
<span id="trace-status" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<button id="trace-clear-bin" class="btn" hidden>clear selection</button>
|
||||
</div>
|
||||
<div class="controls" id="step-bar" hidden>
|
||||
<button id="step-prev" class="btn tm-nav" title="previous step">‹</button>
|
||||
<div id="step-blocks"></div>
|
||||
<button id="step-next" class="btn tm-nav" title="next step">›</button>
|
||||
<span id="step-label" class="t-label"></span>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<div id="trace-filter-wrap" class="dd-wrap">
|
||||
<button id="trace-filter-btn" class="btn dd-btn" title="filter & sort">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
|
||||
filter
|
||||
</button>
|
||||
<div id="trace-filter-menu" class="dd-menu" hidden>
|
||||
<label class="t-label">env</label>
|
||||
<select id="trace-env"><option value="">all envs</option></select>
|
||||
<label class="t-label">sort</label>
|
||||
<select id="trace-sort">
|
||||
<option value="line:asc">order: arrival</option>
|
||||
<option value="reward:desc">reward ↓</option>
|
||||
<option value="reward:asc">reward ↑</option>
|
||||
<option value="advantage:desc">advantage ↓</option>
|
||||
<option value="advantage:asc">advantage ↑</option>
|
||||
<option value="output_tokens:desc">tokens ↓</option>
|
||||
<option value="group:asc">group</option>
|
||||
</select>
|
||||
<label class="toggle"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="seg" id="trace-kind">
|
||||
<button data-kind="train" class="active">Train</button>
|
||||
<button data-kind="eval">Eval</button>
|
||||
</div>
|
||||
<div class="seg" id="trace-subset">
|
||||
<button data-subset="all">All</button>
|
||||
<button data-subset="effective" class="active">Effective</button>
|
||||
</div>
|
||||
<span id="trace-status" class="muted"></span>
|
||||
<div id="trace-chart">
|
||||
<div class="chart-head"><span class="chart-title">Episodes finished</span><span id="trace-chart-sub" class="muted"></span></div>
|
||||
<div id="trace-hist"></div>
|
||||
<div id="hist-tip" hidden></div>
|
||||
</div>
|
||||
<div id="episode-table-wrap">
|
||||
<table id="episode-table">
|
||||
<thead><tr>
|
||||
<th>#</th><th>env</th><th>group</th><th>reward</th><th>adv</th>
|
||||
<th>#</th><th>arrived</th><th>took</th><th>kind</th><th>env</th><th>group</th><th>reward</th>
|
||||
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>status</th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
@@ -165,44 +177,46 @@
|
||||
<div id="drawer-backdrop" hidden></div>
|
||||
<div id="trace-modal" hidden>
|
||||
<aside id="tm-left">
|
||||
<div class="tm-head tm-stephead">
|
||||
<div class="tm-head tm-stephead" id="tm-stephead">
|
||||
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
|
||||
<span id="tm-step-label"></span>
|
||||
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
|
||||
</div>
|
||||
<div class="tm-head tm-ctlrow">
|
||||
<div id="tm-filter-wrap" class="dd-wrap">
|
||||
<button id="tm-filter-btn" class="btn dd-btn" title="filter & sort">
|
||||
<button id="tm-filter-btn" class="btn dd-btn" title="filter">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
|
||||
filter
|
||||
</button>
|
||||
<div id="tm-filter-menu" class="dd-menu" hidden>
|
||||
<label class="t-label">env</label>
|
||||
<select id="tm-env"><option value="">all envs</option></select>
|
||||
<label class="t-label">sort</label>
|
||||
<select id="tm-sort">
|
||||
<option value="line:asc">order: arrival</option>
|
||||
<option value="reward:desc">reward ↓</option>
|
||||
<option value="reward:asc">reward ↑</option>
|
||||
<option value="advantage:desc">advantage ↓</option>
|
||||
<option value="advantage:asc">advantage ↑</option>
|
||||
<option value="output_tokens:desc">tokens ↓</option>
|
||||
<option value="group:asc">group</option>
|
||||
</select>
|
||||
<label class="toggle"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
|
||||
<div class="dd-menu dd-filters" id="tm-filter-menu" hidden>
|
||||
<div class="dd-sec">filter</div>
|
||||
<div class="dd-row"><span class="t-label">kind</span>
|
||||
<div class="seg toggle-seg" id="tm-kinds">
|
||||
<button data-kind="train" class="on">train</button>
|
||||
<button data-kind="eval" class="on">eval</button>
|
||||
</div>
|
||||
</div>
|
||||
<label class="dd-row"><span class="t-label">env</span>
|
||||
<select id="tm-env"><option value="">all envs</option></select>
|
||||
</label>
|
||||
<label class="toggle dd-row"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
|
||||
</div>
|
||||
</div>
|
||||
<select id="tm-sort" title="sort" data-label="sort">
|
||||
<option value="arrival:desc">arrival ↓</option>
|
||||
<option value="arrival:asc">arrival ↑</option>
|
||||
<option value="group:asc">group</option>
|
||||
<option value="duration:desc">total time ↓</option>
|
||||
<option value="duration:asc">total time ↑</option>
|
||||
<option value="reward:desc">reward ↓</option>
|
||||
<option value="reward:asc">reward ↑</option>
|
||||
<option value="output_tokens:desc">tokens ↓</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="tm-head tm-ctlrow" id="tm-kind-row">
|
||||
<div class="seg" id="tm-kind">
|
||||
<button data-kind="train">Train</button>
|
||||
<button data-kind="eval">Eval</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tm-head tm-ctlrow" id="tm-subset-row">
|
||||
<div class="seg" id="tm-subset">
|
||||
<button data-subset="all">All</button>
|
||||
<button data-subset="effective">Effective</button>
|
||||
<div class="tm-head tm-ctlrow" id="tm-mode-row">
|
||||
<div class="seg" id="tm-mode">
|
||||
<button data-mode="stream">Stream</button>
|
||||
<button data-mode="step">Step</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tm-head">
|
||||
@@ -224,12 +238,14 @@
|
||||
<button data-mode="messages" class="active">Messages</button>
|
||||
<button data-mode="rendered">Rendered</button>
|
||||
</div>
|
||||
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, log probability, training mask, or message-content membership.">
|
||||
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, loss/content mask membership, or the trainer's annotations (entropy, the mismatch between its recomputed logprobs and the sampling ones, and the IPO stable mask).">
|
||||
<option value="">Text</option>
|
||||
<option value="advantage">Advantage</option>
|
||||
<option value="logprob">Logprob</option>
|
||||
<option value="mask">Mask</option>
|
||||
<option value="is_content">Content</option>
|
||||
<option value="entropy">Entropy</option>
|
||||
<option value="mismatch_kl">Mismatch</option>
|
||||
<option value="stable_mask">Stable mask</option>
|
||||
<option value="mask">Loss Mask</option>
|
||||
<option value="is_content">Content Mask</option>
|
||||
</select>
|
||||
<button id="tm-collapse" class="btn">collapse</button>
|
||||
<button id="tm-expand" class="btn">expand</button>
|
||||
|
||||
@@ -135,9 +135,26 @@ select:focus, .search:focus { border-color: var(--grey-6); }
|
||||
.dd-opt:hover { background: var(--grey-2); color: var(--grey-6); }
|
||||
.dd-opt.active { color: var(--accent); }
|
||||
.dd-opt.disabled { color: var(--grey-3); cursor: default; }
|
||||
/* an option with nothing to offer greys out and names its reason */
|
||||
.dd-opt.unavailable { display: flex; justify-content: space-between; gap: 28px; }
|
||||
.dd-opt.unavailable:hover { background: none; color: var(--grey-3); }
|
||||
.dd-why { color: var(--grey-3); }
|
||||
.dd-note {
|
||||
padding: 5px 12px 7px;
|
||||
margin-bottom: 4px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
}
|
||||
.dd-btn.unavailable { color: var(--grey-4); }
|
||||
.dd-menu {
|
||||
position: absolute;
|
||||
top: 34px;
|
||||
/* anchor to the trigger's left edge: without it the menu lays out from its
|
||||
static position and runs off the side of the window */
|
||||
left: 0;
|
||||
z-index: 40;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
@@ -792,7 +809,8 @@ mark.hit {
|
||||
.tl-tooltip dd { color: var(--grey-6); margin: 0; }
|
||||
.tl-tooltip-hint { color: var(--grey-4); border-top: 1px solid var(--hairline); margin-top: 9px; padding-top: 7px; font-size: 9.5px; }
|
||||
|
||||
.trace-errors { margin-top: auto; padding-top: 12px; }
|
||||
/* the banners lead the transcript, so they stand off the first entry */
|
||||
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
|
||||
.trace-error-banner {
|
||||
border: 1px solid var(--negative);
|
||||
background: rgba(255, 69, 57, 0.08);
|
||||
@@ -892,7 +910,7 @@ details.sub .sub-name { font-weight: 500; color: var(--grey-6); }
|
||||
details.sub > .entry-body { border-top: 1px solid var(--hairline); }
|
||||
|
||||
/* tool definitions are model context, but deliberately sit outside numbered messages */
|
||||
details.tool-definitions, details.rendered-transcript {
|
||||
details.tool-definitions, .rendered-transcript {
|
||||
border: 1px solid var(--grey-3);
|
||||
margin-bottom: 12px;
|
||||
background: rgba(183, 166, 250, 0.025);
|
||||
@@ -1091,3 +1109,72 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
|
||||
font-size: 12px;
|
||||
}
|
||||
#view-toast .toast-text { color: var(--grey-6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
|
||||
/* filter & sort popover */
|
||||
.dd-filters { min-width: 210px; display: flex; flex-direction: column; gap: 6px; }
|
||||
.dd-sec {
|
||||
text-transform: uppercase;
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--grey-4);
|
||||
border-bottom: 1px solid var(--grey-3);
|
||||
padding-bottom: 3px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.dd-filters .dd-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 0; }
|
||||
/* controls sit right, sized to their content, so the label reads as the row's subject */
|
||||
.dd-filters .dd-row select, .dd-filters .dd-row .dd-select, .dd-filters .dd-row .seg { margin-left: auto; }
|
||||
.dd-filters .dd-row .dd-btn { justify-content: space-between; gap: 8px; }
|
||||
.dd-filters .t-label { white-space: nowrap; }
|
||||
|
||||
/* episodes-finished histogram */
|
||||
#trace-chart { padding: 8px 12px 4px; border-bottom: 1px solid var(--grey-2); }
|
||||
#trace-chart .chart-head { display: flex; align-items: baseline; gap: 10px; margin-bottom: 4px; }
|
||||
#trace-chart .chart-title { font-size: 12px; font-weight: 600; }
|
||||
#trace-hist { overflow-x: auto; }
|
||||
#trace-hist svg { display: block; max-width: 100%; }
|
||||
.hbar { fill: var(--accent); opacity: 0.7; cursor: pointer; }
|
||||
.hbar:hover { opacity: 1; }
|
||||
.hbar.on { opacity: 1; fill: #fff; }
|
||||
.hgrid { stroke: var(--grey-3); stroke-width: 1; vector-effect: non-scaling-stroke; }
|
||||
.hax { fill: var(--grey-4); font-size: 10px; }
|
||||
.hval { text-anchor: end; }
|
||||
|
||||
#episode-table td.nowrap { white-space: nowrap; }
|
||||
|
||||
/* kind filter: each side toggles on its own, so both or one can be shown */
|
||||
.toggle-seg button { opacity: 0.4; }
|
||||
.toggle-seg button.on { opacity: 1; color: var(--accent); }
|
||||
.toggle-seg button.absent.on { color: var(--grey-4); }
|
||||
|
||||
/* histogram hover card */
|
||||
#trace-chart { position: relative; }
|
||||
#hist-tip {
|
||||
position: absolute;
|
||||
z-index: 50;
|
||||
pointer-events: none;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
padding: 6px 8px;
|
||||
min-width: 150px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
|
||||
font-size: 11px;
|
||||
}
|
||||
#hist-tip .tip-head { color: var(--accent); margin-bottom: 4px; }
|
||||
#hist-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
|
||||
#hist-tip .tip-row span:first-child { color: var(--grey-4); }
|
||||
|
||||
/* the label reads as the button's own name, so it takes the button's colour */
|
||||
.dd-select .dd-btn .dd-label { text-transform: uppercase; font-weight: 400; color: inherit; }
|
||||
|
||||
/* rendered tokens: a header row over the sequence, not a disclosure */
|
||||
.rendered-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
padding: 7px 12px;
|
||||
background: var(--grey-2);
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Checkpoint standalone eval progress cursor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import pickle
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
|
||||
|
||||
|
||||
class CheckpointManager:
|
||||
def __init__(self, output_dir: Path) -> None:
|
||||
self.ckpt_dir = get_ckpt_dir(output_dir)
|
||||
|
||||
def get_ckpt_path(self, step: int) -> Path:
|
||||
return get_step_path(self.ckpt_dir, step) / "evals"
|
||||
|
||||
def latest_step(self) -> int:
|
||||
steps = [
|
||||
step for step in get_all_ckpt_steps(self.ckpt_dir) if (self.get_ckpt_path(step) / "progress.pt").is_file()
|
||||
]
|
||||
if not steps:
|
||||
raise FileNotFoundError(f"No evals checkpoints found in {self.ckpt_dir}")
|
||||
return steps[-1]
|
||||
|
||||
def save(self, eval_source: EvalSource) -> None:
|
||||
cursor = eval_source.cursor
|
||||
ckpt_path = self.get_ckpt_path(cursor)
|
||||
ckpt_path.mkdir(parents=True, exist_ok=True)
|
||||
start = time.perf_counter()
|
||||
# Replace atomically so resume never observes a partially written pickle.
|
||||
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as f:
|
||||
pickle.dump(eval_source.state_dict(), f)
|
||||
os.replace(tmp_name, ckpt_path / "progress.pt")
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(tmp_name)
|
||||
raise
|
||||
get_logger().debug(
|
||||
f"Evals checkpoint saved to {ckpt_path} (cursor={cursor}) in {format_time(time.perf_counter() - start)}"
|
||||
)
|
||||
|
||||
def load(
|
||||
self,
|
||||
step: int,
|
||||
eval_source: EvalSource,
|
||||
path: Path | None = None,
|
||||
) -> None:
|
||||
ckpt_path = path if path is not None else self.get_ckpt_path(step)
|
||||
state_file = ckpt_path / "progress.pt"
|
||||
if not state_file.is_file():
|
||||
raise FileNotFoundError(f"Evals checkpoint not found at {state_file}")
|
||||
get_logger().info(f"Loading evals checkpoint from {state_file}")
|
||||
with open(state_file, "rb") as f:
|
||||
state = pickle.load(f)
|
||||
if state["cursor"] != step:
|
||||
raise ValueError(f"Evals checkpoint contains cursor {state['cursor']}, expected step {step}")
|
||||
eval_source.load_state_dict(state)
|
||||
@@ -35,6 +35,8 @@ from subprocess import Popen
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.evals.ckpt import CheckpointManager
|
||||
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
|
||||
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
@@ -49,7 +51,12 @@ from prime_rl.orchestrator.patches import (
|
||||
)
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
|
||||
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
|
||||
from prime_rl.orchestrator.utils import (
|
||||
episode_group_id,
|
||||
eval_work,
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
)
|
||||
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
@@ -84,6 +91,8 @@ class Evals:
|
||||
# The last weight-checkpoint step already handled (evaluated or skipped).
|
||||
self.last_step = (config.online.resume_step if config.online is not None else None) or 0
|
||||
self.eval_triggered_at: dict[tuple[str, int], float] = {}
|
||||
self.ckpt_manager = CheckpointManager(config.output_dir)
|
||||
self.last_saved_cursor = 0
|
||||
self.env_server_procs: list[Popen] = []
|
||||
self.dispatcher_task: asyncio.Task | None = None
|
||||
|
||||
@@ -147,6 +156,20 @@ class Evals:
|
||||
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)
|
||||
if config.resume is not None:
|
||||
if config.resume.dir is not None:
|
||||
resume_step = config.resume.dir_step
|
||||
resume_path = config.resume.dir / "evals"
|
||||
else:
|
||||
resume_step = config.resume.step or self.ckpt_manager.latest_step()
|
||||
resume_path = None
|
||||
self.ckpt_manager.load(
|
||||
resume_step,
|
||||
self.eval_source,
|
||||
path=resume_path,
|
||||
)
|
||||
self.last_saved_cursor = self.eval_source.cursor
|
||||
get_logger().info(f"Resuming evals from task cursor {self.eval_source.cursor}")
|
||||
self.policy = Policy(version=0, model_name=config.model)
|
||||
|
||||
# Pessimistic per-episode token cost for the controller's starting cap,
|
||||
@@ -253,6 +276,8 @@ class Evals:
|
||||
else:
|
||||
await self.watch()
|
||||
|
||||
self.maybe_save_checkpoint(force=True)
|
||||
|
||||
# The periodic logger and the collector log to the W&B run, so they
|
||||
# must stop before finalize marks the run finished.
|
||||
await self.periodic_logger.stop()
|
||||
@@ -379,12 +404,17 @@ class Evals:
|
||||
if not fired:
|
||||
return
|
||||
|
||||
for env_name in fired:
|
||||
task_count = self.eval_source.triggered_task_count(env_name, step)
|
||||
self.eval_sink.set_batch_size(env_name, step, task_count * self.eval_sink.group_size_for(env_name))
|
||||
|
||||
now = time.perf_counter()
|
||||
for env_name in fired:
|
||||
self.eval_triggered_at[(env_name, step)] = now
|
||||
total_rollouts = sum(
|
||||
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
|
||||
for env_name in fired
|
||||
self.eval_envs.get(request.env_name).config.group_size
|
||||
for request in self.eval_source.queue
|
||||
if request.step == step and request.env_name in fired
|
||||
)
|
||||
|
||||
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
|
||||
@@ -397,7 +427,7 @@ class Evals:
|
||||
|
||||
async def consume_epoch(self, fired: list[str], step: int) -> None:
|
||||
"""Consume one epoch, preempting it when a newer checkpoint is ready."""
|
||||
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
|
||||
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name, step) > 0}
|
||||
cancellation_task: asyncio.Task[int] | None = None
|
||||
superseding_step: int | None = None
|
||||
online = self.config.online
|
||||
@@ -428,15 +458,30 @@ class Evals:
|
||||
|
||||
if isinstance(item, GroupCancellation):
|
||||
eval_batch = self.eval_sink.cancel(item)
|
||||
group_completed = False
|
||||
group_id = item.group_id
|
||||
elif isinstance(item, DispatchFailure):
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
group_completed = not self.eval_sink.has_pending_group(item.group_id)
|
||||
group_id = item.group_id
|
||||
else:
|
||||
item_step = eval_work(item).step
|
||||
stamp_arrival([item], "eval", item_step)
|
||||
await monitors.log([item], item_step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(item)
|
||||
group_id = episode_group_id(item)
|
||||
group_completed = not self.eval_sink.has_pending_group(group_id)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
pending.discard(eval_batch.env_name)
|
||||
if group_completed:
|
||||
source_index = self.dispatcher.pop_source_index(group_id)
|
||||
if self.config.online is not None:
|
||||
continue
|
||||
if source_index is None:
|
||||
raise RuntimeError(f"Eval group {group_id} is missing its source cursor")
|
||||
if self.eval_source.mark_completed(source_index):
|
||||
self.maybe_save_checkpoint()
|
||||
|
||||
if cancellation_task is not None:
|
||||
cancelled = await cancellation_task
|
||||
@@ -445,6 +490,17 @@ class Evals:
|
||||
f"advancing to checkpoint {superseding_step}"
|
||||
)
|
||||
|
||||
def maybe_save_checkpoint(self, *, force: bool = False) -> None:
|
||||
if self.config.ckpt is None:
|
||||
return
|
||||
cursor = self.eval_source.cursor
|
||||
if cursor <= 0 or cursor == self.last_saved_cursor:
|
||||
return
|
||||
if not force and cursor - self.last_saved_cursor < self.config.ckpt.interval:
|
||||
return
|
||||
self.ckpt_manager.save(self.eval_source)
|
||||
self.last_saved_cursor = cursor
|
||||
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch through the monitors, mirroring the
|
||||
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
|
||||
@@ -454,6 +510,7 @@ class Evals:
|
||||
|
||||
if batch.episodes.effective:
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
|
||||
|
||||
episodes = batch.episodes
|
||||
effective = episodes.effective
|
||||
|
||||
@@ -234,8 +234,7 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
|
||||
if config.use_v2_model_runner:
|
||||
raise ValueError(
|
||||
"The V2 model runner does not support routed experts capture - "
|
||||
"set VLLM_USE_V2_MODEL_RUNNER=0 (the prime-rl launcher does this automatically)."
|
||||
"Routed-expert capture with NIXL requires the V1 model runner. Set VLLM_USE_V2_MODEL_RUNNER=0."
|
||||
)
|
||||
|
||||
# vLLM rejects every KV connector, but our P/D path uses NIXL and
|
||||
|
||||
@@ -10,11 +10,15 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Router replay needs the V1 GPU model runner: V2 silently never captures
|
||||
# routed experts. Everything else follows vLLM's own V1/V2 resolution.
|
||||
# setdefault so it stays overridable.
|
||||
if config.vllm.enable_return_routed_experts:
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
# Standard deployments use V2 for both capture modes. NIXL P/D also uses V2
|
||||
# for sampling-mask capture, but router replay remains on V1 because vLLM
|
||||
# rejects routed-expert capture with KV connectors and prime-rl's stitching
|
||||
# patch is V1-only. setdefault keeps an explicit env-var choice authoritative.
|
||||
if config.enable_return_sampling_mask:
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
elif config.vllm.enable_return_routed_experts:
|
||||
use_v2_runner = config.deployment.type != "disaggregated"
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_runner else "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
|
||||
@@ -122,6 +122,15 @@ async def log(
|
||||
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
|
||||
async def log_annotations(updates: list[dict[str, Any]]) -> None:
|
||||
"""Log trace updates to all registered monitors."""
|
||||
for monitor in MONITORS:
|
||||
try:
|
||||
await monitor.log_annotations(updates)
|
||||
except Exception as e:
|
||||
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
|
||||
async def finalize() -> None:
|
||||
"""Finalize the run on all registered monitors."""
|
||||
for monitor in MONITORS:
|
||||
|
||||
@@ -53,5 +53,9 @@ class Monitor(ABC):
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Log episodes."""
|
||||
|
||||
async def log_annotations(self, updates: list[dict[str, Any]]) -> None:
|
||||
"""Log trace updates — post-hoc facts about traces this run already logged.
|
||||
Monitors that only carry scalars ignore them."""
|
||||
|
||||
async def finalize(self) -> None:
|
||||
"""Finalize run."""
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, TextIO
|
||||
|
||||
import orjson
|
||||
|
||||
from prime_rl.configs.monitors import FileMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.utils.utils import sanitize
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
|
||||
class FileMonitor(Monitor):
|
||||
"""Logs metrics and episodes to local JSONL files."""
|
||||
|
||||
config: FileMonitorConfig
|
||||
file: TextIO
|
||||
|
||||
async def init(self, output_dir: Path, producer: str | None = None) -> None:
|
||||
self.output_dir = output_dir
|
||||
self.producer = producer
|
||||
self.path = output_dir / self.config.path
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Line-buffered append so a concurrently-running dashboard can tail the file.
|
||||
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
|
||||
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
"""``step=None`` logs a time-keyed row (e.g. inference metrics, which are
|
||||
sampled on wall time rather than the training step)."""
|
||||
sanitized, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(
|
||||
f"Dropping {len(dropped)} non-finite value(s) from {self.config.path}: {', '.join(dropped[:5])}"
|
||||
)
|
||||
|
||||
row = {"step": step, "time": time.time(), **sanitized}
|
||||
if self.producer is not None:
|
||||
row["producer"] = self.producer
|
||||
self.file.write(json.dumps(row) + "\n")
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Append the cohort to its per-step episode file. ``all`` grows one
|
||||
episode at a time as they complete, ``effective`` one batch at a time on finalize,
|
||||
so an in-progress run can be inspected live. Episode-level failures are
|
||||
preserved even when no trace was produced."""
|
||||
|
||||
def write() -> None:
|
||||
path = self.output_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "ab") as f:
|
||||
for episode in episodes:
|
||||
f.write(orjson.dumps(episode.to_record(), default=str, option=opts))
|
||||
|
||||
# Record serialization is heavy pure-Python work; keep it off the event loop.
|
||||
# Awaited (not fire-and-forget) so appends to one file never interleave.
|
||||
await asyncio.to_thread(write)
|
||||
|
||||
async def finalize(self) -> None:
|
||||
self.logger.info(f"Finalized metrics at {self.path}")
|
||||
@@ -0,0 +1,3 @@
|
||||
from prime_rl.monitors.file.monitor import FileMonitor
|
||||
|
||||
__all__ = ["FileMonitor"]
|
||||
@@ -0,0 +1,108 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, TextIO
|
||||
|
||||
import orjson
|
||||
|
||||
from prime_rl.configs.monitors import FileMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
|
||||
from prime_rl.monitors.file.traces.index import index_row
|
||||
from prime_rl.monitors.file.traces.update import update_index_row
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
from prime_rl.utils.utils import sanitize
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
OPTS = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
|
||||
|
||||
class FileMonitor(Monitor):
|
||||
"""Logs metrics and episodes to local JSONL files."""
|
||||
|
||||
config: FileMonitorConfig
|
||||
file: TextIO
|
||||
|
||||
async def init(self, output_dir: Path, producer: str | None = None) -> None:
|
||||
self.output_dir = output_dir
|
||||
self.producer = producer
|
||||
index = get_index_path(get_trace_stream(output_dir))
|
||||
# a relaunch appends to the stream it finds, so the numbering carries on
|
||||
self._logged = sum(1 for _ in index.open("rb")) if index.is_file() else 0
|
||||
self.path = get_file_monitor_dir(output_dir) / self.config.path
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Line-buffered append so a concurrently-running dashboard can tail the file.
|
||||
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
|
||||
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
"""``step=None`` logs a time-keyed row (e.g. inference metrics, which are
|
||||
sampled on wall time rather than the training step)."""
|
||||
sanitized, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(
|
||||
f"Dropping {len(dropped)} non-finite value(s) from {self.config.path}: {', '.join(dropped[:5])}"
|
||||
)
|
||||
|
||||
row = {"step": step, "time": time.time(), **sanitized}
|
||||
if self.producer is not None:
|
||||
row["producer"] = self.producer
|
||||
self.file.write(json.dumps(row) + "\n")
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Append each episode to the trace stream as it completes — every episode is
|
||||
serialized exactly once, in arrival order, whatever its kind, so an in-progress
|
||||
run can be tailed. Episode-level failures are preserved even when no trace was
|
||||
produced. The shipped cohort writes no second copy: what it learns arrives as
|
||||
annotations that readers fold back onto the stream."""
|
||||
if subset == "effective":
|
||||
return
|
||||
|
||||
def write() -> None:
|
||||
path = get_trace_stream(self.output_dir)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# An index row goes out with every episode: summarising the record here,
|
||||
# while it is already in hand, saves every reader from parsing a stream
|
||||
# that outgrows memory long before the run does.
|
||||
with open(path, "ab") as f, open(get_index_path(path), "ab") as index:
|
||||
offset = f.tell()
|
||||
for episode in episodes:
|
||||
record = episode.to_record()
|
||||
line = orjson.dumps(record, default=str, option=OPTS)
|
||||
f.write(line)
|
||||
self._logged += 1
|
||||
index.write(orjson.dumps(index_row(self._logged, record, offset), default=str, option=OPTS))
|
||||
offset += len(line)
|
||||
|
||||
# Record serialization is heavy pure-Python work; keep it off the event loop.
|
||||
# Awaited (not fire-and-forget) so appends to one file never interleave.
|
||||
await asyncio.to_thread(write)
|
||||
|
||||
async def log_annotations(self, updates: list[dict[str, Any]]) -> None:
|
||||
"""Append trace updates to this producer's annotation file — one writer per
|
||||
file, so producers never interleave."""
|
||||
if not updates:
|
||||
return
|
||||
|
||||
def write() -> None:
|
||||
path = get_annotations_dir(self.output_dir) / f"{self.producer or 'unknown'}.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# the scalars go to a sibling index so a reader can answer "which cohort,
|
||||
# what credit" without touching the token streams
|
||||
with open(path, "ab") as f, open(get_index_path(path), "ab") as index:
|
||||
offset = f.tell()
|
||||
for update in updates:
|
||||
line = orjson.dumps(update, option=OPTS)
|
||||
f.write(line)
|
||||
index.write(orjson.dumps(update_index_row(update, offset), option=OPTS))
|
||||
offset += len(line)
|
||||
|
||||
await asyncio.to_thread(write)
|
||||
|
||||
async def finalize(self) -> None:
|
||||
self.logger.info(f"Finalized metrics at {self.path}")
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Where the file monitor puts the traces, and everything written about them.
|
||||
|
||||
The stream and its annotations live under one directory so nothing beside them has to
|
||||
be read as belonging to them, and every index is named for the stream it indexes and
|
||||
sits beside it.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
|
||||
|
||||
def get_trace_dir(output_dir: Path) -> Path:
|
||||
return get_file_monitor_dir(output_dir) / "traces"
|
||||
|
||||
|
||||
def get_trace_stream(output_dir: Path) -> Path:
|
||||
"""Every episode, appended as it arrives."""
|
||||
return get_trace_dir(output_dir) / "stream.jsonl"
|
||||
|
||||
|
||||
def get_annotations_dir(output_dir: Path) -> Path:
|
||||
"""One file per producer of trace updates: orch ship-time facts, trainer streams."""
|
||||
return get_trace_dir(output_dir) / "annotations"
|
||||
|
||||
|
||||
def get_index_path(path: Path) -> Path:
|
||||
"""A stream's index, beside it, so a reader pairs the two without knowing who
|
||||
wrote them."""
|
||||
return path.with_name(path.name.replace(".jsonl", ".index.jsonl"))
|
||||
|
||||
|
||||
__all__ = ["get_annotations_dir", "get_index_path", "get_trace_dir", "get_trace_stream"]
|
||||
@@ -0,0 +1,133 @@
|
||||
"""The episode index - one compact row per episode, so a reader never has to parse
|
||||
the stream to browse it.
|
||||
|
||||
The file monitor writes a row as each episode lands, when the record is already in
|
||||
hand and summarising it is nearly free, and records the byte offset it wrote the
|
||||
episode at so a reader can seek straight to one. A stream another producer wrote has
|
||||
no index, so its reader derives the same rows itself.
|
||||
"""
|
||||
|
||||
|
||||
def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
|
||||
"""Flatten a trace timing tree to phase -> seconds (same walk as the viewer)."""
|
||||
if isinstance(obj.get("duration"), (int, float)):
|
||||
out[prefix] = out.get(prefix, 0.0) + obj["duration"]
|
||||
elif isinstance(obj.get("start"), (int, float)) and isinstance(obj.get("end"), (int, float)):
|
||||
out[prefix] = out.get(prefix, 0.0) + (obj["end"] - obj["start"])
|
||||
for key, value in obj.items():
|
||||
if isinstance(value, dict):
|
||||
walk_timing(value, f"{prefix}/{key}" if prefix else key, out)
|
||||
|
||||
|
||||
def episode_kind(rec: dict) -> str:
|
||||
"""The kind of work an episode did. The file monitor stamps it as the episode
|
||||
lands; a stream written by another producer (a verifiers ``uv run eval`` run) is
|
||||
read off its run info instead."""
|
||||
for trace in rec.get("traces") or []:
|
||||
if (kind := (trace.get("info") or {}).get("kind")) in ("train", "eval"):
|
||||
return kind
|
||||
run = rec.get("run") or {}
|
||||
return (run.get("work") or {}).get("type") or run.get("type") or "eval"
|
||||
|
||||
|
||||
def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
"""One index row: what the table, the filters, the chart and the sort need.
|
||||
|
||||
``line`` numbers the episode within the stream from 1, so the last of n reads as
|
||||
n — it is what a reader sees and what addresses the episode."""
|
||||
rewards, advantages = [], []
|
||||
input_tokens = output_tokens = turns = branches = 0
|
||||
stop_condition = None
|
||||
reward_parts: dict[str, list[float]] = {}
|
||||
metric_parts: dict[str, list[float]] = {}
|
||||
timing: dict[str, float] = {}
|
||||
costs: list[float] = []
|
||||
for trace in rec.get("traces") or []:
|
||||
costs.extend(
|
||||
usage["cost"]
|
||||
for call in trace.get("calls") or []
|
||||
if isinstance(usage := call.get("usage") or {}, dict) and isinstance(usage.get("cost"), (int, float))
|
||||
)
|
||||
nodes = trace.get("nodes") or []
|
||||
parents = {node.get("parent") for node in nodes if "parent" in node}
|
||||
branches += max(0, len(nodes) - len(parents))
|
||||
if trace.get("rewards"): # skip reward-less seats (e.g. a judge) in the episode mean
|
||||
rewards.append(
|
||||
sum(
|
||||
(r.get("score") or 0) * (r.get("weight") if r.get("weight") is not None else 1)
|
||||
for r in trace["rewards"].values()
|
||||
if isinstance(r, dict)
|
||||
)
|
||||
)
|
||||
for name, r in (trace.get("rewards") or {}).items():
|
||||
if isinstance(r, dict) and isinstance(r.get("score"), (int, float)):
|
||||
reward_parts.setdefault(name, []).append(r["score"])
|
||||
for name, value in (trace.get("metrics") or {}).items():
|
||||
if isinstance(value, (int, float)):
|
||||
metric_parts.setdefault(name, []).append(value)
|
||||
if isinstance(trace.get("timing"), dict):
|
||||
walk_timing(trace["timing"], "", timing)
|
||||
advantage = (trace.get("info") or {}).get("advantage")
|
||||
if advantage is not None:
|
||||
advantages.append(advantage)
|
||||
for node in nodes:
|
||||
n_tokens = len(node.get("token_ids") or [])
|
||||
if node.get("sampled"):
|
||||
output_tokens += n_tokens
|
||||
else:
|
||||
input_tokens += n_tokens
|
||||
if (node.get("message") or {}).get("role") == "assistant":
|
||||
turns += 1
|
||||
stop_condition = trace.get("stop_condition", stop_condition)
|
||||
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
|
||||
for call in trace.get("calls") or []:
|
||||
usage = call.get("usage") or {}
|
||||
input_tokens += usage.get("prompt_tokens") or 0
|
||||
output_tokens += usage.get("completion_tokens") or 0
|
||||
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
|
||||
return {
|
||||
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
|
||||
"metrics": {name: sum(v) / len(v) for name, v in metric_parts.items()},
|
||||
"timing": timing,
|
||||
"cost": sum(costs) if costs else None,
|
||||
"line": line,
|
||||
"offset": offset,
|
||||
"id": rec.get("id"),
|
||||
"kind": episode_kind(rec),
|
||||
"trace_ids": [trace_id for trace in rec.get("traces") or [] if (trace_id := trace.get("id"))],
|
||||
"env": (rec.get("env") or {}).get("id") or (rec.get("env") or {}).get("name"),
|
||||
"group": (rec.get("group") or {}).get("id"),
|
||||
"ok": rec.get("ok"),
|
||||
"num_errors": len(rec.get("errors") or []),
|
||||
"reward": sum(rewards) / len(rewards) if rewards else None,
|
||||
"advantage": sum(advantages) / len(advantages) if advantages else None,
|
||||
"input_tokens": input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"turns": turns,
|
||||
"branches": branches,
|
||||
"stop_condition": stop_condition,
|
||||
# when the episode landed and how long it was alive: the stream's x axis,
|
||||
# and the one duration worth sorting a stream by
|
||||
"arrival": (first_info.get("arrival") or {}).get("time"),
|
||||
"duration": _episode_duration(first_info, timing),
|
||||
}
|
||||
|
||||
|
||||
def _episode_duration(info: dict, timing: dict[str, float]) -> float | None:
|
||||
"""Wall-clock seconds from dispatch to arrival, or the summed phases for a record
|
||||
that predates those stamps."""
|
||||
dispatched = (info.get("dispatch") or {}).get("time")
|
||||
arrived = (info.get("arrival") or {}).get("time")
|
||||
if isinstance(dispatched, (int, float)) and isinstance(arrived, (int, float)):
|
||||
return max(0.0, arrived - dispatched)
|
||||
phases = [value for key, value in timing.items() if "/" not in key]
|
||||
return sum(phases) if phases else None
|
||||
|
||||
|
||||
def index_row(line: int, rec: dict, offset: int) -> dict:
|
||||
"""The row the file monitor writes. The nested reward/metric/timing maps are left
|
||||
out: only the per-episode series view needs them, and they dominate the size."""
|
||||
row = summarize_episode(line, rec, offset)
|
||||
for key in ("rewards", "metrics", "timing"):
|
||||
row.pop(key, None)
|
||||
return row
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Trace updates — post-hoc facts about a completed trace, recorded beside it.
|
||||
|
||||
An episode is serialized once, when it arrives. Everything a consumer learns later
|
||||
is an update naming the trace: an ``info`` dict merged into the trace's own, plus
|
||||
per-token streams over a branch, full-length across the branch's token prefix (nulls
|
||||
mark unknown positions, so a stream never depends on the producer's loss mask).
|
||||
|
||||
Each producer appends its own file under the trace directory's ``annotations/``, so
|
||||
every file has exactly one writer. Readers fold the updates onto the arrival records
|
||||
in write order, newest wins.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
UPDATE_VERSION = 1
|
||||
|
||||
STREAM_FIELDS = ("advantages", "trainer_logprobs", "entropies")
|
||||
"""Per-token streams an update may carry, compacted onto node fields of the same name."""
|
||||
|
||||
|
||||
def update_index_row(update: dict[str, Any], offset: int) -> dict[str, Any]:
|
||||
"""An update's scalars plus where its record sits. The per-token streams stay in
|
||||
the annotation file: a reader browsing a run needs the scalars, and only the
|
||||
episode it opens needs the streams."""
|
||||
return {"trace_id": update.get("trace_id"), "offset": offset, "info": update.get("info") or {}}
|
||||
|
||||
|
||||
def make_update(
|
||||
trace_id: str,
|
||||
*,
|
||||
info: dict[str, Any] | None = None,
|
||||
branches: dict[int, dict[str, list]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""One update record. ``branches`` maps a branch index to its token streams."""
|
||||
return {
|
||||
"version": UPDATE_VERSION,
|
||||
"trace_id": trace_id,
|
||||
"info": info or {},
|
||||
"branches": [{"index": index, **streams} for index, streams in (branches or {}).items()],
|
||||
}
|
||||
|
||||
|
||||
def branch_node_paths(nodes: list[dict]) -> list[list[int]]:
|
||||
"""Root-to-leaf node indexes, one path per branch, in leaf order."""
|
||||
if not nodes:
|
||||
return []
|
||||
parents = {parent for node in nodes if isinstance((parent := node.get("parent")), int) and 0 <= parent < len(nodes)}
|
||||
paths = []
|
||||
for leaf in (index for index in range(len(nodes)) if index not in parents):
|
||||
path: list[int] = []
|
||||
seen: set[int] = set()
|
||||
node_index: int | None = leaf
|
||||
while isinstance(node_index, int) and 0 <= node_index < len(nodes) and node_index not in seen:
|
||||
seen.add(node_index)
|
||||
path.append(node_index)
|
||||
node_index = nodes[node_index].get("parent")
|
||||
paths.append(list(reversed(path)))
|
||||
return paths
|
||||
|
||||
|
||||
def _deep_merge(old: Any, new: Any) -> Any:
|
||||
if isinstance(old, dict) and isinstance(new, dict):
|
||||
return {**old, **{key: _deep_merge(old.get(key), value) for key, value in new.items()}}
|
||||
return new
|
||||
|
||||
|
||||
def fold_trace_updates(trace: dict, updates: list[dict]) -> int:
|
||||
"""Apply updates onto a raw trace record in write order, newest winning.
|
||||
|
||||
Merges each ``info`` and projects every branch stream onto the branch's nodes,
|
||||
compact over each node's mask like the node's own ``logprobs``. A node takes a
|
||||
stream only when it is fully covered with non-null values at every sampled
|
||||
position, so a truncated stream leaves the tail nodes untouched. Returns how many
|
||||
nodes carry trainer logprobs afterwards."""
|
||||
nodes = trace.get("nodes") or []
|
||||
paths = branch_node_paths(nodes)
|
||||
for update in updates:
|
||||
if update.get("info"):
|
||||
trace["info"] = _deep_merge(trace.get("info") or {}, update["info"])
|
||||
for branch in update.get("branches") or []:
|
||||
branch_index = branch.get("index")
|
||||
if not isinstance(branch_index, int) or not 0 <= branch_index < len(paths):
|
||||
continue
|
||||
for field in STREAM_FIELDS:
|
||||
stream = branch.get(field)
|
||||
if not stream:
|
||||
continue
|
||||
cursor = 0
|
||||
for node_index in paths[branch_index]:
|
||||
node = nodes[node_index]
|
||||
token_ids = node.get("token_ids") or []
|
||||
span = stream[cursor : cursor + len(token_ids)]
|
||||
cursor += len(token_ids)
|
||||
if len(span) < len(token_ids):
|
||||
break
|
||||
values = [v for v, sampled in zip(span, node.get("mask") or []) if sampled]
|
||||
if not values or any(v is None for v in values):
|
||||
continue
|
||||
node[field] = values
|
||||
return sum(1 for node in nodes if node.get("trainer_logprobs"))
|
||||
@@ -0,0 +1,49 @@
|
||||
"""What the orchestrator knows about an episode, recorded as it learns it.
|
||||
|
||||
An episode is serialized once, when it arrives, so a trace's later facts cannot be
|
||||
implied by where its record sits. Both events below are stamped explicitly: what the
|
||||
orchestrator knows at arrival goes onto the trace before it is logged, and what a batch
|
||||
adds when it takes the episode becomes an append-only update the reader folds back on.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.monitors.base import Kind
|
||||
from prime_rl.monitors.file.traces.update import make_update
|
||||
|
||||
|
||||
def stamp_arrival(episodes: list[vf.Episode], kind: Kind, step: int) -> None:
|
||||
"""Stamp what an episode's traces are known to have done as they land: the kind of
|
||||
work, the step that dispatched them, and the step they came back at."""
|
||||
now = time.time()
|
||||
for episode in episodes:
|
||||
work = getattr(episode.run, "work", None)
|
||||
for trace in episode.traces:
|
||||
trace.info["kind"] = kind
|
||||
if work is not None:
|
||||
trace.info["dispatch"] = {"step": work.step, "time": trace.timing.start}
|
||||
trace.info["arrival"] = {"step": step, "time": now}
|
||||
|
||||
|
||||
def stamp_batch(episodes: list[vf.Episode], step: int) -> list[dict[str, Any]]:
|
||||
"""The updates a batched cohort adds over its arrival records: membership, the step
|
||||
it ties to, the scalar advantage, and the per-token advantage streams."""
|
||||
now = time.time()
|
||||
updates = []
|
||||
for episode in episodes:
|
||||
for trace in episode.traces:
|
||||
info: dict[str, Any] = {"effective": True, "ship": {"step": step, "time": now}}
|
||||
if (advantage := trace.info.get("advantage")) is not None:
|
||||
info["advantage"] = advantage
|
||||
branches = {
|
||||
branch.index: {"advantages": advantages}
|
||||
for branch in trace.branches
|
||||
if (advantages := branch.advantages) is not None
|
||||
}
|
||||
updates.append(make_update(trace.id, info=info, branches=branches))
|
||||
return updates
|
||||
@@ -190,6 +190,7 @@ class Dispatcher:
|
||||
|
||||
self.inflight: dict[asyncio.Task, InflightEpisode] = {}
|
||||
self.groups: dict[uuid.UUID, GroupState] = {}
|
||||
self.source_indices_by_group: dict[str, int] = {}
|
||||
|
||||
# Bounded so the dispatcher backpressures on a slow sink (unbounded
|
||||
# when no hard ceiling is configured — the dynamic cap still bounds
|
||||
@@ -466,6 +467,8 @@ class Dispatcher:
|
||||
return False
|
||||
gid = uuid.uuid4()
|
||||
self.groups[gid] = fresh
|
||||
if fresh.source_index is not None:
|
||||
self.source_indices_by_group[str(gid)] = fresh.source_index
|
||||
return await self.schedule_group_episode(gid, fresh)
|
||||
|
||||
def next_fresh_group(self, kind: WorkKind, envs) -> GroupState | None:
|
||||
@@ -493,8 +496,12 @@ class Dispatcher:
|
||||
episodes_to_schedule=group_size,
|
||||
target_episodes=group_size,
|
||||
policy_version_at_start=self.policy.version,
|
||||
source_index=request.source_index,
|
||||
)
|
||||
|
||||
def pop_source_index(self, group_id: str) -> int | None:
|
||||
return self.source_indices_by_group.pop(group_id, None)
|
||||
|
||||
async def schedule_group_episode(self, group_id: uuid.UUID, group: GroupState) -> bool:
|
||||
"""Dispatch one ``run`` task for this group.
|
||||
|
||||
@@ -545,6 +552,7 @@ class Dispatcher:
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start,
|
||||
step=group.step,
|
||||
source_index=group.source_index,
|
||||
client_config=client,
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
@@ -710,6 +718,7 @@ class Dispatcher:
|
||||
|
||||
if claimed:
|
||||
await safe_cancel_all([task for task, _ in claimed])
|
||||
self.source_indices_by_group.pop(str(group_id), None)
|
||||
return cancelled
|
||||
|
||||
async def cancel_inflight_episodes(self) -> None:
|
||||
@@ -721,6 +730,7 @@ class Dispatcher:
|
||||
tasks = list(self.inflight.keys())
|
||||
self.inflight.clear()
|
||||
self.groups.clear()
|
||||
self.source_indices_by_group.clear()
|
||||
if tasks:
|
||||
await safe_cancel_all(tasks)
|
||||
|
||||
|
||||
@@ -131,6 +131,12 @@ class TrainEnv(Env):
|
||||
self.generation_source = generation_source
|
||||
self.algorithm = algorithm
|
||||
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
|
||||
# Truncated policy sampling must ship the sampling masks the trainer replays.
|
||||
self.requires_sampling_masks = (
|
||||
config.sampling.truncates_distribution()
|
||||
and config.algo is not None
|
||||
and config.algo.sampling.source == "policy"
|
||||
)
|
||||
|
||||
|
||||
class EvalEnv(Env):
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.metrics import EvalEpisodes
|
||||
@@ -12,6 +11,9 @@ from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancell
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
|
||||
class EvalSink:
|
||||
"""Collect completed evaluation episodes into per-environment epochs."""
|
||||
@@ -24,6 +26,7 @@ class EvalSink:
|
||||
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_batch_failures: dict[tuple[str, int], list[DispatchFailure]] = defaultdict(list)
|
||||
self.pending_batch_cancellations: dict[tuple[str, int], int] = defaultdict(int)
|
||||
self.expected_batch_sizes: dict[tuple[str, int], int] = {}
|
||||
|
||||
def add(self, episode: vf.Episode) -> EvalBatch | None:
|
||||
env_name = episode_env_name(episode)
|
||||
@@ -34,7 +37,7 @@ class EvalSink:
|
||||
group.append(episode)
|
||||
if self._group_size(group_id) >= self.group_size_for(env_name):
|
||||
self.process_group(group_id)
|
||||
if self._batch_size(bkey) >= self.batch_size_for(env_name):
|
||||
if self._batch_size(bkey) >= self.batch_size_for(env_name, eval_step):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
@@ -48,7 +51,7 @@ class EvalSink:
|
||||
self.pending_group_failures[group_id].append(failure)
|
||||
if self._group_size(group_id) >= self.group_size_for(failure.env_name):
|
||||
self.process_group(group_id)
|
||||
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name):
|
||||
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name, failure.step):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
@@ -61,7 +64,7 @@ class EvalSink:
|
||||
self.pending_group_cancellations[group_id] = cancellation
|
||||
if self._group_size(group_id) >= self.group_size_for(cancellation.env_name):
|
||||
self.process_group(group_id)
|
||||
if self._batch_size(bkey) >= self.batch_size_for(cancellation.env_name):
|
||||
if self._batch_size(bkey) >= self.batch_size_for(cancellation.env_name, cancellation.step):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
@@ -83,7 +86,14 @@ class EvalSink:
|
||||
def group_size_for(self, env_name: str) -> int:
|
||||
return self.eval_envs.get(env_name).config.group_size
|
||||
|
||||
def batch_size_for(self, env_name: str) -> int:
|
||||
def set_batch_size(self, env_name: str, step: int, size: int) -> None:
|
||||
self.expected_batch_sizes[(env_name, step)] = size
|
||||
|
||||
def batch_size_for(self, env_name: str, step: int | None = None) -> int:
|
||||
if step is not None:
|
||||
key = (env_name, step)
|
||||
if key in self.expected_batch_sizes:
|
||||
return self.expected_batch_sizes[key]
|
||||
env = self.eval_envs.get(env_name)
|
||||
return len(env.examples) * env.config.group_size
|
||||
|
||||
@@ -119,12 +129,19 @@ class EvalSink:
|
||||
env_name,
|
||||
eval_step,
|
||||
batch_counts.get((env_name, eval_step), 0),
|
||||
self.batch_size_for(env_name),
|
||||
self.batch_size_for(env_name, eval_step),
|
||||
buffered.get((env_name, eval_step), 0),
|
||||
)
|
||||
for env_name, eval_step in set(batch_counts) | set(buffered)
|
||||
]
|
||||
|
||||
def has_pending_group(self, group_id: str) -> bool:
|
||||
return bool(
|
||||
self.pending_groups.get(group_id)
|
||||
or self.pending_group_failures.get(group_id)
|
||||
or self.pending_group_cancellations.get(group_id)
|
||||
)
|
||||
|
||||
def process_group(self, group_id: str) -> None:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
failures = self.pending_group_failures.pop(group_id, [])
|
||||
@@ -164,6 +181,7 @@ class EvalSink:
|
||||
episodes = self.pending_batches.pop(key, [])
|
||||
failures = self.pending_batch_failures.pop(key, [])
|
||||
cancelled = self.pending_batch_cancellations.pop(key, 0)
|
||||
self.expected_batch_sizes.pop(key, None)
|
||||
return EvalBatch(
|
||||
env_name=env_name,
|
||||
step=step,
|
||||
|
||||
@@ -6,15 +6,18 @@ including startup. The dispatcher pulls via ``next_task()`` until
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from collections import Counter, deque
|
||||
from itertools import zip_longest
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
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
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import EvalConfig
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
|
||||
|
||||
class EvalSource:
|
||||
"""Finite-per-epoch source of eval examples."""
|
||||
@@ -36,6 +39,10 @@ class EvalSource:
|
||||
self.intervals[env.name] = env.config.interval
|
||||
|
||||
self.queue: deque[TaskRequest] = deque()
|
||||
self.cursor = 0
|
||||
self._next_index = 0
|
||||
self._completed: set[int] = set()
|
||||
self._triggered_task_counts: dict[tuple[str, int], int] = {}
|
||||
|
||||
# A fresh run evaluates the base policy. Resumed runs apply interval
|
||||
# rules to the loaded checkpoint and later policies.
|
||||
@@ -51,8 +58,9 @@ class EvalSource:
|
||||
return []
|
||||
fired: list[str] = []
|
||||
for name, interval in self.intervals.items():
|
||||
if is_first or force or step % interval == 0:
|
||||
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]:
|
||||
fired.append(name)
|
||||
queued_counts: Counter[str] = Counter()
|
||||
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
|
||||
# dispatcher rotates at example granularity. ``try_schedule``'s
|
||||
# continue-group branch still keeps each example's group_size
|
||||
@@ -62,8 +70,41 @@ class EvalSource:
|
||||
for env_name, task in zip(fired, round_tasks, strict=True):
|
||||
if task is None:
|
||||
continue
|
||||
self.queue.append(TaskRequest(env_name=env_name, task=task, step=step))
|
||||
return fired
|
||||
source_index = self._next_index
|
||||
self._next_index += 1
|
||||
if source_index < self.cursor:
|
||||
continue
|
||||
self.queue.append(TaskRequest(env_name=env_name, task=task, step=step, source_index=source_index))
|
||||
queued_counts[env_name] += 1
|
||||
for env_name, count in queued_counts.items():
|
||||
self._triggered_task_counts[(env_name, step)] = count
|
||||
return [name for name in fired if queued_counts[name]]
|
||||
|
||||
def triggered_task_count(self, env_name: str, step: int) -> int:
|
||||
return self._triggered_task_counts.get((env_name, step), 0)
|
||||
|
||||
def mark_completed(self, source_index: int) -> bool:
|
||||
"""Advance the durable cursor only across a fully completed prefix."""
|
||||
if source_index < self.cursor:
|
||||
return False
|
||||
self._completed.add(source_index)
|
||||
previous = self.cursor
|
||||
while self.cursor in self._completed:
|
||||
self._completed.remove(self.cursor)
|
||||
self.cursor += 1
|
||||
return self.cursor != previous
|
||||
|
||||
def state_dict(self) -> dict:
|
||||
return {"cursor": self.cursor}
|
||||
|
||||
def load_state_dict(self, state_dict: dict) -> None:
|
||||
if set(state_dict) != {"cursor"}:
|
||||
raise ValueError("Eval source checkpoint must contain only a cursor")
|
||||
cursor = state_dict["cursor"]
|
||||
if type(cursor) is not int or cursor < 0:
|
||||
raise ValueError(f"Eval source checkpoint cursor must be a non-negative integer, got {cursor!r}")
|
||||
self.cursor = cursor
|
||||
self._completed.clear()
|
||||
|
||||
def next_task(self) -> TaskRequest | None:
|
||||
"""Pop the next eval task, or ``None`` when the queue is empty."""
|
||||
|
||||
@@ -37,6 +37,7 @@ import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before tr
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.algo.routing import is_trainable
|
||||
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
@@ -559,6 +560,7 @@ class Orchestrator:
|
||||
raise ValueError("Orchestrated episode is missing training-run provenance")
|
||||
kind = episode.run.work.type
|
||||
step = episode.run.work.step if kind == "eval" else self.progress.step
|
||||
stamp_arrival([episode], kind, step)
|
||||
await monitors.log([episode], step, kind, "all")
|
||||
|
||||
if kind == "eval":
|
||||
@@ -649,9 +651,11 @@ class Orchestrator:
|
||||
await self.version_advanced.wait()
|
||||
self.wait_for_policy_time += time.perf_counter() - hold_start
|
||||
|
||||
# The effective (clean, trained-on) subset is logged at ship time; the full arrival
|
||||
# window already streamed into the ``all`` cohort on arrival.
|
||||
# The effective (clean, trained-on) subset is logged at ship time as annotation
|
||||
# records against each trace's arrival record - membership, advantages, the step
|
||||
# it shipped at - never a second episode copy.
|
||||
await monitors.log(effective.vf_episodes, step, "train", "effective")
|
||||
await monitors.log_annotations(stamp_batch(effective.vf_episodes, step))
|
||||
|
||||
pack_start_time = time.perf_counter()
|
||||
micro_batch_grid = await asyncio.to_thread(self.packer.pack, batch.samples)
|
||||
@@ -908,6 +912,7 @@ class Orchestrator:
|
||||
# ``env_name``); the full returned cohort already streamed into ``all`` on arrival.
|
||||
if batch.episodes.effective:
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
|
||||
policy_spans = [eval_work(episode).policy for episode in batch.episodes]
|
||||
if any(span is None for span in policy_spans):
|
||||
raise ValueError(f"Eval {batch.env_name} step {batch.step} is missing policy provenance")
|
||||
|
||||
@@ -277,6 +277,15 @@ class TrainSink:
|
||||
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
|
||||
for sample in samples:
|
||||
sample.temperatures = [temperature] * len(sample.token_ids)
|
||||
if env.requires_sampling_masks and sample.sampling_mask is None:
|
||||
# Rollout logprobs are mask-renormalized; training without the masks
|
||||
# silently biases every importance ratio.
|
||||
raise RuntimeError(
|
||||
f"env '{env_name}' samples with truncation (top_p/top_k) but its rollouts "
|
||||
"carry no sampling masks. Set `enable_return_sampling_mask = true` on "
|
||||
"the inference server config (the rl entrypoint does this automatically) - "
|
||||
"it requires vLLM's native sampling-mask capture (>= 0.28)."
|
||||
)
|
||||
stamp_loss_routing(sample, env.algorithm.action_loss_type)
|
||||
if samples:
|
||||
samples_by_trace[trace.id] = samples
|
||||
|
||||
@@ -21,7 +21,7 @@ import numpy as np
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts
|
||||
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts, SamplingMask
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -66,6 +66,28 @@ def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExp
|
||||
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
|
||||
|
||||
|
||||
def _encode_sampling_mask(mask: vf.SamplingMask | None, num_tokens: int) -> SamplingMask | None:
|
||||
"""Encode a branch sampling mask for a fixed token count.
|
||||
|
||||
The mask stores row sizes in `counts` and concatenates every row in `ids`.
|
||||
For example, `counts=[2, 1]` and `ids=[4, 7, 9]` become `counts=[2]` and
|
||||
`ids=[4, 7]` for one token. For three tokens, they become
|
||||
`counts=[2, 1, 0]` with unchanged ids. Zero-count rows disable replay.
|
||||
"""
|
||||
if mask is None:
|
||||
return None
|
||||
ids, counts = mask.ids, mask.counts
|
||||
if len(counts) > num_tokens:
|
||||
counts = counts[:num_tokens]
|
||||
ids = ids[: int(counts.sum())]
|
||||
elif len(counts) < num_tokens:
|
||||
counts = np.concatenate([counts, np.zeros(num_tokens - len(counts), dtype=np.int32)])
|
||||
return SamplingMask(
|
||||
ids=np.ascontiguousarray(ids, dtype=np.int32).tobytes(),
|
||||
counts=np.ascontiguousarray(counts, dtype=np.int32).tobytes(),
|
||||
)
|
||||
|
||||
|
||||
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
|
||||
"""Yield each branch that yields a training sample, with its trainable-token mask.
|
||||
|
||||
@@ -143,6 +165,9 @@ def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSam
|
||||
ce_weights=_loss_weights(branch, "ce", trained_loss_nodes["ce"]),
|
||||
ref_kl_weights=_loss_weights(branch, "ref_kl", trained_loss_nodes["ref_kl"]),
|
||||
advantages=branch.advantages,
|
||||
sampling_mask=_encode_sampling_mask(branch.sampling_mask, len(token_ids)),
|
||||
trace_id=trace.id,
|
||||
branch_index=branch.index,
|
||||
)
|
||||
)
|
||||
if not samples:
|
||||
|
||||
@@ -4,13 +4,13 @@ from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Literal, Protocol, TypeAlias
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias
|
||||
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.metrics import EvalEpisodes, TrainEpisodes
|
||||
|
||||
|
||||
@@ -68,7 +68,10 @@ class DispatchFailure:
|
||||
error: vf.Error
|
||||
|
||||
|
||||
DispatchResult: TypeAlias = vf.WireEpisode | DispatchFailure | GroupCancellation
|
||||
if TYPE_CHECKING:
|
||||
DispatchResult: TypeAlias = vf.WireEpisode | DispatchFailure | GroupCancellation
|
||||
else:
|
||||
DispatchResult: TypeAlias = Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -78,6 +81,7 @@ class TaskRequest:
|
||||
env_name: str
|
||||
task: vf.Task
|
||||
step: int
|
||||
source_index: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -90,6 +94,7 @@ class InflightEpisode:
|
||||
task: vf.Task
|
||||
policy_version: int
|
||||
step: int
|
||||
source_index: int | None = None
|
||||
client_config: vf.ClientConfig | None = None
|
||||
started_at: float = 0.0
|
||||
"""``time.monotonic()`` at dispatch; feeds episode-duration estimates."""
|
||||
@@ -108,6 +113,7 @@ class GroupState:
|
||||
target_episodes: int
|
||||
emitted: int = 0
|
||||
policy_version_at_start: int = 0
|
||||
source_index: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -6,7 +6,7 @@ from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
|
||||
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, SamplingMask, TrainingSample
|
||||
|
||||
# Backfill value per component weight stream when a packed sample doesn't
|
||||
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
|
||||
@@ -278,6 +278,31 @@ def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
|
||||
routed_experts.shape[0] += padding_size
|
||||
|
||||
|
||||
_SAMPLING_MASK_ITEMSIZE = np.dtype(np.int32).itemsize
|
||||
|
||||
|
||||
def _empty_sampling_mask(num_tokens: int) -> SamplingMask:
|
||||
return SamplingMask(ids=b"", counts=b"\0" * (num_tokens * _SAMPLING_MASK_ITEMSIZE))
|
||||
|
||||
|
||||
def _slice_sampling_mask(sampling_mask: SamplingMask, seq_len: int) -> SamplingMask:
|
||||
counts = np.frombuffer(sampling_mask.counts, dtype=np.int32)[:seq_len]
|
||||
return SamplingMask(
|
||||
ids=sampling_mask.ids[: int(counts.sum()) * _SAMPLING_MASK_ITEMSIZE],
|
||||
counts=counts.tobytes(),
|
||||
)
|
||||
|
||||
|
||||
def _pad_sampling_mask(micro_batch: MicroBatch, padding_size: int) -> None:
|
||||
"""Add zero-count mask rows for sequence-padding tokens.
|
||||
|
||||
Padding adds token positions but no eligible token ids, so only `counts` grows.
|
||||
"""
|
||||
sampling_mask = micro_batch.sampling_mask
|
||||
assert sampling_mask is not None
|
||||
sampling_mask.counts += b"\0" * (padding_size * _SAMPLING_MASK_ITEMSIZE)
|
||||
|
||||
|
||||
def _slice_encoded(tensor: EncodedTensor, n_rows: int) -> EncodedTensor:
|
||||
"""First `n_rows` rows of a dim-0-stacked encoded tensor (e.g. pixel_values, image_grid_thw)."""
|
||||
row = int(np.prod(tensor.shape[1:])) if len(tensor.shape) > 1 else 1
|
||||
@@ -383,6 +408,9 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
routed_experts = (
|
||||
_copy_routed_experts(training_example.routed_experts) if training_example.routed_experts is not None else None
|
||||
)
|
||||
# No copy needed: SamplingMask holds immutable bytes, and _pad_sampling_mask only
|
||||
# ever mutates _materialize_bin's own accumulator.
|
||||
sampling_mask = training_example.sampling_mask
|
||||
|
||||
if len(input_ids) > seq_len:
|
||||
# Multimodal: never split an image's placeholder block — cut to a whole-image boundary
|
||||
@@ -406,6 +434,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
ref_kl_weights = ref_kl_weights[:cut]
|
||||
if routed_experts is not None:
|
||||
routed_experts = _slice_routed_experts(routed_experts, cut)
|
||||
if sampling_mask is not None:
|
||||
sampling_mask = _slice_sampling_mask(sampling_mask, cut)
|
||||
if mm_token_type_ids is not None:
|
||||
mm_token_type_ids = mm_token_type_ids[:cut]
|
||||
env_names = env_names[:cut]
|
||||
@@ -436,6 +466,13 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
)
|
||||
assert len(routed_experts.data) == len(input_ids) * _routed_experts_row_size(routed_experts)
|
||||
|
||||
if sampling_mask is not None:
|
||||
mask_counts = np.frombuffer(sampling_mask.counts, dtype=np.int32)
|
||||
assert len(mask_counts) == len(input_ids), (
|
||||
f"sampling_mask counts: {len(mask_counts)}, input_ids: {len(input_ids)}"
|
||||
)
|
||||
assert len(sampling_mask.ids) == int(mask_counts.sum()) * _SAMPLING_MASK_ITEMSIZE
|
||||
|
||||
assert len(env_names) == len(input_ids), f"env_names: {len(env_names)}, input_ids: {len(input_ids)}"
|
||||
|
||||
return MicroBatch(
|
||||
@@ -448,6 +485,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
ref_logprobs=ref_logprobs,
|
||||
temperatures=temperatures,
|
||||
routed_experts=routed_experts,
|
||||
sampling_mask=sampling_mask,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=mm_kwargs,
|
||||
@@ -455,6 +493,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
ce_weights=ce_weights,
|
||||
ref_kl_weights=ref_kl_weights,
|
||||
seq_lens=[len(input_ids)],
|
||||
trace_ids=[training_example.trace_id or ""],
|
||||
branch_indices=[training_example.branch_index if training_example.branch_index is not None else -1],
|
||||
)
|
||||
|
||||
|
||||
@@ -541,6 +581,9 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
# A weight stream materializes as soon as one packed sample carries it; the
|
||||
# samples that lack it get the stream's identity fill (STREAM_FILL).
|
||||
has_stream = {name: any(getattr(s, name) is not None for s in bin_content.samples) for name in STREAM_FILL}
|
||||
# Sampling masks are per-token optional (unlike routed_experts): samples
|
||||
# without them get zero-count backfill instead of constraining packing.
|
||||
has_sampling_mask = any(sample.sampling_mask is not None for sample in bin_content.samples)
|
||||
|
||||
input_ids: list[int] = []
|
||||
loss_mask: list[bool] = []
|
||||
@@ -555,6 +598,9 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
|
||||
seq_lens: list[int] = []
|
||||
routed_experts: RoutedExperts | None = None
|
||||
sampling_mask: SamplingMask | None = SamplingMask(ids=b"", counts=b"") if has_sampling_mask else None
|
||||
trace_ids: list[str] = []
|
||||
branch_indices: list[int] = []
|
||||
|
||||
for sample in bin_content.samples:
|
||||
sample_len = len(sample.input_ids)
|
||||
@@ -592,6 +638,12 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
mm_kwargs[key].data += sample.mm_kwargs[key].data
|
||||
mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0]
|
||||
seq_lens.extend(sample.seq_lens)
|
||||
if sampling_mask is not None:
|
||||
sample_mask = sample.sampling_mask if sample.sampling_mask is not None else _empty_sampling_mask(sample_len)
|
||||
sampling_mask.ids += sample_mask.ids
|
||||
sampling_mask.counts += sample_mask.counts
|
||||
trace_ids.extend(sample.trace_ids or [""] * len(sample.sequence_lengths))
|
||||
branch_indices.extend(sample.branch_indices or [-1] * len(sample.sequence_lengths))
|
||||
|
||||
sequence_lengths = [len(sample.input_ids) for sample in bin_content.samples]
|
||||
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
|
||||
@@ -607,6 +659,7 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
ref_logprobs=ref_logprobs,
|
||||
temperatures=temperatures,
|
||||
routed_experts=routed_experts,
|
||||
sampling_mask=sampling_mask,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=mm_kwargs,
|
||||
@@ -614,6 +667,8 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
ce_weights=streams["ce_weights"],
|
||||
ref_kl_weights=streams["ref_kl_weights"],
|
||||
seq_lens=seq_lens,
|
||||
trace_ids=trace_ids,
|
||||
branch_indices=branch_indices,
|
||||
)
|
||||
|
||||
|
||||
@@ -724,7 +779,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
micro_batch.ref_logprobs.extend([0.0] * padding_size)
|
||||
# Padding is loss-masked, so no component trains it; fill every stream
|
||||
# with 0.0 (not the pack-boundary defaults) so a padded pure-ce batch
|
||||
# still reads as rl-empty in token export, which keys off nonzero weights.
|
||||
# still reads as rl-empty to consumers that key off nonzero weights
|
||||
# (e.g. the per-env mismatch metrics).
|
||||
for stream_name in STREAM_FILL:
|
||||
stream = getattr(micro_batch, stream_name)
|
||||
if stream is not None:
|
||||
@@ -733,6 +789,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
micro_batch.mm_token_type_ids.extend([0] * padding_size)
|
||||
if micro_batch.routed_experts is not None:
|
||||
_pad_routed_experts(micro_batch, padding_size)
|
||||
if micro_batch.sampling_mask is not None:
|
||||
_pad_sampling_mask(micro_batch, padding_size)
|
||||
micro_batch.env_names.extend([""] * padding_size)
|
||||
|
||||
return micro_batch
|
||||
@@ -764,11 +822,26 @@ def _assert_token_arrays_aligned(micro_batch: MicroBatch) -> None:
|
||||
assert sum(micro_batch.sequence_lengths) == num_tokens, (
|
||||
f"sequence_lengths sum {sum(micro_batch.sequence_lengths)} != {num_tokens} tokens"
|
||||
)
|
||||
num_sequences = len(micro_batch.sequence_lengths)
|
||||
for name in ("trace_ids", "branch_indices"):
|
||||
values = getattr(micro_batch, name)
|
||||
assert values is None or len(values) == num_sequences, (
|
||||
f"{name} misaligned after packing: {len(values)} != {num_sequences} sequences"
|
||||
)
|
||||
assert sum(micro_batch.seq_lens) == num_tokens, f"seq_lens sum {sum(micro_batch.seq_lens)} != {num_tokens} tokens"
|
||||
if micro_batch.routed_experts is not None:
|
||||
assert micro_batch.routed_experts.shape[0] == num_tokens, (
|
||||
f"routed_experts misaligned after packing: {micro_batch.routed_experts.shape[0]} != {num_tokens} tokens"
|
||||
)
|
||||
if micro_batch.sampling_mask is not None:
|
||||
mask_counts = np.frombuffer(micro_batch.sampling_mask.counts, dtype=np.int32)
|
||||
assert len(mask_counts) == num_tokens, (
|
||||
f"sampling_mask misaligned after packing: {len(mask_counts)} != {num_tokens} tokens"
|
||||
)
|
||||
assert len(micro_batch.sampling_mask.ids) == int(mask_counts.sum()) * _SAMPLING_MASK_ITEMSIZE, (
|
||||
f"sampling_mask ids/counts inconsistent after packing: "
|
||||
f"{len(micro_batch.sampling_mask.ids)} bytes != {int(mask_counts.sum())} ids"
|
||||
)
|
||||
|
||||
|
||||
def _make_dummy_batch(source: MicroBatch) -> MicroBatch:
|
||||
@@ -781,6 +854,11 @@ def _make_dummy_batch(source: MicroBatch) -> MicroBatch:
|
||||
dummy.rl_weights = None
|
||||
dummy.ce_weights = None
|
||||
dummy.ref_kl_weights = None
|
||||
# Fully loss-masked, so replaying sampling masks would be pure wasted work.
|
||||
dummy.sampling_mask = None
|
||||
# The copied identity would double-annotate the source's traces.
|
||||
dummy.trace_ids = None
|
||||
dummy.branch_indices = None
|
||||
return dummy
|
||||
|
||||
|
||||
|
||||
@@ -1328,6 +1328,7 @@ def forward(
|
||||
labels: Int[Tensor, "batch seq"] | None = None,
|
||||
temperature: Tensor | None = None,
|
||||
routed_experts: Int[Tensor, "batch seq layers topk"] | None = None,
|
||||
sampling_mask: Int[Tensor, "batch seq mask"] | None = None,
|
||||
# Generic multimodal kwargs (e.g. {"pixel_values": ...,
|
||||
# "image_grid_thw": ...} for Qwen3-VL; just {"pixel_values": ...}
|
||||
# for Gemma3). Passed straight through to ``model(**kwargs)`` so
|
||||
@@ -1345,6 +1346,11 @@ def forward(
|
||||
"temperature": temperature,
|
||||
}
|
||||
|
||||
# Sampling masks are consumed by the injected prime lm_head; HF
|
||||
# forwards don't know the kwarg, so only pass it when present.
|
||||
if sampling_mask is not None:
|
||||
kwargs["sampling_mask"] = sampling_mask
|
||||
|
||||
if mm_kwargs:
|
||||
# Forward the per-model multimodal tensors verbatim, plus the
|
||||
# renderer-supplied ``mm_token_type_ids`` (renderer owns the
|
||||
|
||||
@@ -44,6 +44,7 @@ class FusedOutputLinear(torch.nn.Linear):
|
||||
hidden_states: torch.Tensor,
|
||||
labels: torch.Tensor | None = None,
|
||||
temperature: Tensor | None = None,
|
||||
sampling_mask: Tensor | None = None,
|
||||
) -> PrimeLmOutput:
|
||||
assert labels is not None, "FusedOutputLinear requires labels for chunked logprob computation"
|
||||
assert temperature is not None, "FusedOutputLinear requires per-token temperatures"
|
||||
@@ -52,9 +53,11 @@ class FusedOutputLinear(torch.nn.Linear):
|
||||
hidden_states = hidden_states.reshape(b * s, h).contiguous()
|
||||
labels = labels.reshape(b * s).contiguous()
|
||||
inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N]
|
||||
if sampling_mask is not None:
|
||||
sampling_mask = sampling_mask.reshape(b * s, sampling_mask.shape[-1]).contiguous()
|
||||
|
||||
logprobs, entropy = _SequenceChunkedLogProbEntropyFn.apply(
|
||||
hidden_states, self.weight, labels, inv_t, self.chunk_size
|
||||
hidden_states, self.weight, labels, inv_t, self.chunk_size, sampling_mask
|
||||
)
|
||||
|
||||
logprobs = logprobs.reshape(b, s)
|
||||
@@ -67,9 +70,14 @@ class VanillaOutputLinear(torch.nn.Linear):
|
||||
super().__init__(in_features, out_features, bias=False)
|
||||
|
||||
def forward(
|
||||
self, hidden_states: torch.Tensor, labels: torch.Tensor | None = None, temperature: Tensor | None = None
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
labels: torch.Tensor | None = None,
|
||||
temperature: Tensor | None = None,
|
||||
sampling_mask: Tensor | None = None,
|
||||
) -> PrimeLmOutput:
|
||||
# VanillaOutputLinear just returns logits - temperature scaling is done externally in train.py
|
||||
# VanillaOutputLinear just returns logits. train.py applies temperature
|
||||
# scaling and sampling-mask replay.
|
||||
return PrimeLmOutput(logits=super().forward(hidden_states))
|
||||
|
||||
|
||||
@@ -86,6 +94,23 @@ def _online_logsumexp_and_weighted_update(
|
||||
return m_new, s_new, t_new
|
||||
|
||||
|
||||
def sampling_replay_mask(sampling_mask: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
|
||||
"""Positions replayable against their sampling mask: non-empty (-1 is padding)
|
||||
and containing the label (a label outside its mask means misaligned data —
|
||||
fall back to full-vocab rather than emit a corrupt logprob)."""
|
||||
return (sampling_mask >= 0).any(dim=-1) & (sampling_mask == labels.unsqueeze(-1)).any(dim=-1)
|
||||
|
||||
|
||||
def _sampling_mask_local_indices(
|
||||
mask_chunk: torch.Tensor, vocab_start: int, vocab_end: int
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Sampling-mask ids mapped into a vocab chunk as clamped local indices
|
||||
plus the in-chunk validity mask (-1 entries are padding)."""
|
||||
in_range = (mask_chunk >= vocab_start) & (mask_chunk < vocab_end)
|
||||
local = (mask_chunk - vocab_start).clamp(0, vocab_end - vocab_start - 1)
|
||||
return local, in_range
|
||||
|
||||
|
||||
class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward( # type: ignore[override]
|
||||
@@ -95,9 +120,15 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
labels: torch.Tensor, # [N]
|
||||
inv_temperature: torch.Tensor, # [N]
|
||||
chunk_size: int,
|
||||
sampling_mask: torch.Tensor | None = None, # [N, K] int32, -1-padded
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Returns per-token logprobs and entropy by chunking over flattened sequence tokens.
|
||||
|
||||
Positions with a usable ``sampling_mask`` (see ``sampling_replay_mask``) are
|
||||
renormalized over that mask: ``logprob = scaled_logits[label] -
|
||||
logsumexp(scaled_logits[mask])``. Other positions — and entropy, a
|
||||
full-distribution diagnostic — keep full-vocab normalization.
|
||||
"""
|
||||
assert hidden.dim() == 2, f"expected hidden [N,H], got {tuple(hidden.shape)}"
|
||||
assert weight.dim() == 2, f"expected weight [V,H], got {tuple(weight.shape)}"
|
||||
@@ -107,6 +138,10 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
assert hidden.shape[1] == weight.shape[1], "hidden/weight H mismatch"
|
||||
assert hidden.shape[0] == inv_temperature.shape[0], "hidden/inv_temperature N mismatch"
|
||||
assert chunk_size > 0
|
||||
if sampling_mask is not None:
|
||||
assert sampling_mask.dim() == 2 and sampling_mask.shape[0] == hidden.shape[0], (
|
||||
f"expected sampling_mask [N,K], got {tuple(sampling_mask.shape)}"
|
||||
)
|
||||
|
||||
device = hidden.device
|
||||
n = hidden.shape[0]
|
||||
@@ -115,6 +150,7 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
logprobs = torch.empty((n,), device=device, dtype=torch.float32)
|
||||
entropy = torch.empty((n,), device=device, dtype=torch.float32)
|
||||
logz = torch.empty((n,), device=device, dtype=torch.float32)
|
||||
replay = torch.zeros((n,), device=device, dtype=torch.bool) if sampling_mask is not None else None
|
||||
|
||||
for start in range(0, n, chunk_size):
|
||||
end = min(start + chunk_size, n)
|
||||
@@ -128,6 +164,13 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
t = torch.zeros((token_count,), device=device, dtype=torch.float32)
|
||||
target_logits = torch.zeros((token_count,), device=device, dtype=torch.float32)
|
||||
|
||||
mask_chunk = sampling_mask[start:end].to(torch.long) if sampling_mask is not None else None
|
||||
if mask_chunk is not None:
|
||||
replay_chunk = sampling_replay_mask(mask_chunk, labels_chunk)
|
||||
# Each mask id lives in exactly one vocab chunk; collect its logit
|
||||
# into a [tokens, K] buffer and logsumexp once after the loop.
|
||||
mask_logits = torch.full_like(mask_chunk, float("-inf"), dtype=torch.float32)
|
||||
|
||||
for vocab_start in range(0, vocab, vocab_chunk_size):
|
||||
vocab_end = min(vocab_start + vocab_chunk_size, vocab)
|
||||
weight_chunk = weight[vocab_start:vocab_end]
|
||||
@@ -136,21 +179,30 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
|
||||
m, s, t = _online_logsumexp_and_weighted_update(m, s, t, scaled_logits)
|
||||
|
||||
if mask_chunk is not None:
|
||||
mask_local, mask_in_range = _sampling_mask_local_indices(mask_chunk, vocab_start, vocab_end)
|
||||
mask_logits = torch.where(mask_in_range, scaled_logits.gather(1, mask_local), mask_logits)
|
||||
|
||||
# Branchless target extraction - we don't want to stall the GPU here (because: if torch.any()) calls bool(Tensor) calls Tensor.items() <- sync here we don't want
|
||||
in_range = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
|
||||
local_idx = (labels_chunk - vocab_start).clamp(0, vocab_end - vocab_start - 1).to(torch.int64)
|
||||
chunk_target = scaled_logits.gather(1, local_idx.unsqueeze(1)).squeeze(1)
|
||||
target_logits = torch.where(in_range, chunk_target, target_logits)
|
||||
|
||||
logz_chunk = m + torch.log(s)
|
||||
logz_full = m + torch.log(s)
|
||||
if mask_chunk is not None:
|
||||
logz_chunk = torch.where(replay_chunk, torch.logsumexp(mask_logits, dim=-1), logz_full)
|
||||
replay[start:end] = replay_chunk
|
||||
else:
|
||||
logz_chunk = logz_full
|
||||
logz[start:end] = logz_chunk
|
||||
logprobs[start:end] = target_logits - logz_chunk
|
||||
entropy[start:end] = logz_chunk - (t / s)
|
||||
entropy[start:end] = logz_full - (t / s)
|
||||
|
||||
ctx.set_materialize_grads(
|
||||
False
|
||||
) # Without materialized grads unused outputs get grad None instead of zeros and backward can reject them without a sync
|
||||
ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz)
|
||||
ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz, sampling_mask, replay)
|
||||
ctx.chunk_size = chunk_size
|
||||
|
||||
return logprobs, entropy
|
||||
@@ -161,7 +213,7 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
assert grad_entropy is None, "Backward through entropy is not implemented in FusedOutputLinear"
|
||||
assert grad_logprobs is not None, "FusedOutputLinear backward requires logprobs gradients"
|
||||
|
||||
hidden, weight, labels, inv_temperature, logz = ctx.saved_tensors
|
||||
hidden, weight, labels, inv_temperature, logz, sampling_mask, replay = ctx.saved_tensors
|
||||
chunk_size: int = ctx.chunk_size
|
||||
|
||||
n, _ = hidden.shape
|
||||
@@ -179,12 +231,24 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
grad_chunk = grad_logprobs[start:end].to(torch.float32)
|
||||
inv_t_chunk = inv_temperature[start:end].unsqueeze(-1)
|
||||
logz_chunk = logz[start:end]
|
||||
mask_chunk = sampling_mask[start:end].to(torch.long) if sampling_mask is not None else None
|
||||
replay_chunk = replay[start:end] if replay is not None else None
|
||||
|
||||
for vocab_start in range(0, vocab, vocab_chunk_size):
|
||||
vocab_end = min(vocab_start + vocab_chunk_size, vocab)
|
||||
weight_chunk = weight[vocab_start:vocab_end]
|
||||
logits_chunk = hidden_chunk @ weight_chunk.t()
|
||||
scaled_logits = logits_chunk.to(torch.float32) * inv_t_chunk
|
||||
|
||||
if mask_chunk is not None:
|
||||
# Replayed rows get softmax gradient only on mask ids. Set masked-out
|
||||
# logits to -inf before exp: a masked-out logit above the sampling-mask
|
||||
# logZ would overflow exp() to inf (and inf * 0 = NaN in the grads).
|
||||
local, in_range = _sampling_mask_local_indices(mask_chunk, vocab_start, vocab_end)
|
||||
mask_indicator = torch.zeros(scaled_logits.shape, dtype=torch.int8, device=scaled_logits.device)
|
||||
mask_indicator.scatter_add_(1, local, in_range.to(torch.int8))
|
||||
masked_out = replay_chunk.unsqueeze(-1) & (mask_indicator == 0)
|
||||
scaled_logits.masked_fill_(masked_out, float("-inf"))
|
||||
probs = torch.exp(scaled_logits - logz_chunk.unsqueeze(-1))
|
||||
|
||||
grad_logits = (-grad_chunk).unsqueeze(-1) * probs
|
||||
@@ -199,7 +263,7 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
if needs_weight:
|
||||
grad_weight[vocab_start:vocab_end].add_(grad_logits.to(weight.dtype).t() @ hidden_chunk)
|
||||
|
||||
return grad_hidden, grad_weight, None, None, None
|
||||
return grad_hidden, grad_weight, None, None, None, None
|
||||
|
||||
|
||||
def inject_prime_lm_head(
|
||||
@@ -262,6 +326,7 @@ def _patch_model_forward(model: nn.Module) -> None:
|
||||
labels: torch.Tensor | None = None,
|
||||
logits_to_keep: int = 0,
|
||||
temperature: torch.Tensor | None = None,
|
||||
sampling_mask: torch.Tensor | None = None,
|
||||
**kwargs: object,
|
||||
) -> PrimeLmOutput:
|
||||
# For VLM with images, don't create position_ids - let model compute MRoPE internally
|
||||
@@ -285,6 +350,7 @@ def _patch_model_forward(model: nn.Module) -> None:
|
||||
hidden_states[:, slice_indices, :],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
temperature=temperature[:, slice_indices] if temperature is not None else None,
|
||||
sampling_mask=sampling_mask[:, slice_indices] if sampling_mask is not None else None,
|
||||
)
|
||||
|
||||
# Bind the new forward to the model
|
||||
|
||||
@@ -23,9 +23,11 @@ class GemmaFusedOutputLinear(torch.nn.Linear):
|
||||
hidden_states: torch.Tensor,
|
||||
labels: torch.Tensor | None = None,
|
||||
temperature: Tensor | None = None,
|
||||
sampling_mask: Tensor | None = None,
|
||||
) -> PrimeLmOutput:
|
||||
assert labels is not None, "GemmaFusedOutputLinear requires labels for chunked logprob computation"
|
||||
assert temperature is not None, "GemmaFusedOutputLinear requires per-token temperatures"
|
||||
assert sampling_mask is None, "sampling-mask replay is not supported with Gemma softcapped lm_heads"
|
||||
|
||||
b, s, h = hidden_states.shape
|
||||
hidden_states = hidden_states.reshape(b * s, h).contiguous()
|
||||
@@ -47,7 +49,11 @@ class GemmaVanillaOutputLinear(torch.nn.Linear):
|
||||
self.softcap = softcap
|
||||
|
||||
def forward(
|
||||
self, hidden_states: torch.Tensor, labels: torch.Tensor | None = None, temperature: Tensor | None = None
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
labels: torch.Tensor | None = None,
|
||||
temperature: Tensor | None = None,
|
||||
sampling_mask: Tensor | None = None,
|
||||
) -> PrimeLmOutput:
|
||||
logits = super().forward(hidden_states)
|
||||
logits = self.softcap * torch.tanh(logits / self.softcap)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import asyncio
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.monitors.file.traces.update import make_update
|
||||
|
||||
|
||||
class AnnotationWriter:
|
||||
"""Collects the trainer's per-token streams (recomputed logprobs, entropies) during
|
||||
a step and logs them as trace updates — one record per trained sequence, keyed by
|
||||
``(trace_id, branch_index)``. Streams are full-length over the sample's token prefix
|
||||
so readers can fold them onto trace nodes without knowing the trainer's loss mask.
|
||||
|
||||
``export`` accumulates locally per micro batch; ``flush`` gathers every rank's
|
||||
records to rank 0, the only rank running monitors. CP ranks past the first
|
||||
accumulate nothing since they share their micro batches."""
|
||||
|
||||
def __init__(self, parallel_dims: Any, world: Any) -> None:
|
||||
self.world = world
|
||||
self.is_duplicate_rank = parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0
|
||||
self._pending: list[dict[str, Any]] = []
|
||||
|
||||
def export(self, micro_batch: Mapping[str, Any], model_output: Mapping[str, Tensor]) -> None:
|
||||
if self.is_duplicate_rank:
|
||||
return
|
||||
trace_ids = micro_batch["trace_ids"]
|
||||
branch_indices = micro_batch["branch_indices"]
|
||||
if not trace_ids or not branch_indices:
|
||||
return
|
||||
sequence_lengths = micro_batch["sequence_lengths"]
|
||||
loss_mask = [bool(v) for v in micro_batch["loss_mask"].detach().cpu().reshape(-1).tolist()]
|
||||
env_names = micro_batch["env_names"]
|
||||
trainer_logprobs = _tensor_to_floats(model_output["logprobs"])
|
||||
entropies = _tensor_to_floats(model_output["entropy"])
|
||||
|
||||
start = 0
|
||||
for trace_id, branch_index, length in zip(trace_ids, branch_indices, sequence_lengths):
|
||||
span_start, end = start, start + length
|
||||
start = end
|
||||
if not trace_id or branch_index < 0:
|
||||
continue
|
||||
# Trailing padding is appended to the last sample and folded into its length.
|
||||
while end > span_start and env_names[end - 1] == "" and not loss_mask[end - 1]:
|
||||
end -= 1
|
||||
if end <= span_start or not any(loss_mask[span_start:end]):
|
||||
continue
|
||||
logprob_span = trainer_logprobs[span_start:end]
|
||||
entropy_span = entropies[span_start:end]
|
||||
# After the right shift, a sample's first value crosses the packing boundary.
|
||||
logprob_span[0] = None
|
||||
entropy_span[0] = None
|
||||
self._pending.append(
|
||||
make_update(
|
||||
trace_id,
|
||||
branches={branch_index: {"trainer_logprobs": logprob_span, "entropies": entropy_span}},
|
||||
)
|
||||
)
|
||||
|
||||
def flush(self) -> None:
|
||||
"""Gather the step's records to rank 0 and log them; collective, so every rank
|
||||
must call it once per step."""
|
||||
records, self._pending = self._pending, []
|
||||
if dist.is_initialized() and self.world.world_size > 1:
|
||||
gathered: list[list[dict[str, Any]]] | None = None
|
||||
if self.world.rank == 0:
|
||||
gathered = [[] for _ in range(self.world.world_size)]
|
||||
dist.gather_object(records, gathered, dst=0)
|
||||
if gathered is None:
|
||||
return
|
||||
records = [record for rank_records in gathered for record in rank_records]
|
||||
asyncio.run(monitors.log_annotations(records))
|
||||
|
||||
|
||||
def _tensor_to_floats(tensor: Tensor) -> list[float | None]:
|
||||
values = tensor.detach().to(dtype=torch.float32, device="cpu").reshape(-1).tolist()
|
||||
return [float(value) if math.isfinite(value) else None for value in values]
|
||||
@@ -1,6 +1,7 @@
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from jaxtyping import Bool, Float, Int
|
||||
from torch import Tensor
|
||||
@@ -29,6 +30,11 @@ class TensorMicroBatch(TypedDict):
|
||||
env_names: list[str]
|
||||
sequence_lengths: list[int]
|
||||
|
||||
# Per-sequence branch identity, parallel to sequence_lengths; None on
|
||||
# synthetic data. "" / -1 mark an unknown sequence (e.g. a dummy batch).
|
||||
trace_ids: list[str] | None
|
||||
branch_indices: list[int] | None
|
||||
|
||||
# Batch level
|
||||
lora_num_tokens: Int[Tensor, "n_loras"]
|
||||
seq_lens: Int[Tensor, "segments"]
|
||||
@@ -36,6 +42,10 @@ class TensorMicroBatch(TypedDict):
|
||||
# MoE router replay
|
||||
routed_experts: Int[Tensor, "batch seq layers topk"] | None
|
||||
|
||||
# Sampling-mask token ids per position, padded with -1 to the micro batch's
|
||||
# maximum mask size. A row containing only -1 has no mask.
|
||||
sampling_mask: Int[Tensor, "batch seq mask"] | None
|
||||
|
||||
# Generic multimodal kwargs — flat dict matching the model's forward
|
||||
# signature (e.g. ``{"pixel_values": ..., "image_grid_thw": ...}`` for
|
||||
# Qwen3-VL; ``{"pixel_values": ...}`` for Gemma3-VL). The trainer
|
||||
@@ -118,10 +128,13 @@ class FakeDataLoader:
|
||||
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
|
||||
"env_names": ["fake"] * input_ids.shape[0],
|
||||
"sequence_lengths": sequence_lengths,
|
||||
"trace_ids": None,
|
||||
"branch_indices": None,
|
||||
"loss_mask": loss_mask.unsqueeze(0),
|
||||
"lora_num_tokens": torch.tensor([input_ids.shape[0]], dtype=torch.int32),
|
||||
"seq_lens": torch.tensor(sequence_lengths, dtype=torch.long),
|
||||
"routed_experts": None,
|
||||
"sampling_mask": None,
|
||||
"mm_kwargs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"rl_weights": None,
|
||||
@@ -147,10 +160,13 @@ class FakeDataLoader:
|
||||
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
|
||||
"env_names": ["fake"] * self.seq_len,
|
||||
"sequence_lengths": [self.seq_len],
|
||||
"trace_ids": None,
|
||||
"branch_indices": None,
|
||||
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
|
||||
"lora_num_tokens": torch.tensor([self.seq_len], dtype=torch.int32),
|
||||
"seq_lens": torch.tensor([self.seq_len], dtype=torch.long),
|
||||
"routed_experts": None,
|
||||
"sampling_mask": None,
|
||||
"mm_kwargs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"rl_weights": None,
|
||||
@@ -206,6 +222,16 @@ class DataLoader:
|
||||
.to(torch.int32)
|
||||
.unsqueeze(0)
|
||||
)
|
||||
sampling_mask = None
|
||||
packed_sampling_mask = micro_batch.sampling_mask
|
||||
if packed_sampling_mask is not None:
|
||||
counts = np.frombuffer(packed_sampling_mask.counts, dtype=np.int32)
|
||||
ids = np.frombuffer(packed_sampling_mask.ids, dtype=np.int32)
|
||||
# Boolean assignment fills row-major, matching the flat concat order.
|
||||
max_mask_size = max(int(counts.max()), 1) if counts.size else 1
|
||||
padded = np.full((len(counts), max_mask_size), -1, dtype=np.int32)
|
||||
padded[np.arange(max_mask_size)[None, :] < counts[:, None]] = ids
|
||||
sampling_mask = torch.from_numpy(padded).unsqueeze(0)
|
||||
return TensorMicroBatch(
|
||||
input_ids=torch.tensor(micro_batch.input_ids, dtype=torch.long).unsqueeze(0),
|
||||
position_ids=torch.tensor(micro_batch.position_ids, dtype=torch.long).unsqueeze(0),
|
||||
@@ -218,6 +244,8 @@ class DataLoader:
|
||||
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
|
||||
env_names=micro_batch.env_names,
|
||||
sequence_lengths=micro_batch.sequence_lengths,
|
||||
trace_ids=micro_batch.trace_ids,
|
||||
branch_indices=micro_batch.branch_indices,
|
||||
# Single adapter: every token in the batch belongs to it (padding included).
|
||||
lora_num_tokens=torch.tensor([len(micro_batch.input_ids)], dtype=torch.int32),
|
||||
seq_lens=torch.tensor(micro_batch.seq_lens, dtype=torch.long),
|
||||
@@ -226,6 +254,7 @@ class DataLoader:
|
||||
if micro_batch.mm_token_type_ids is not None
|
||||
else None,
|
||||
routed_experts=routed_experts,
|
||||
sampling_mask=sampling_mask,
|
||||
rl_weights=torch.tensor(micro_batch.rl_weights, dtype=torch.float).unsqueeze(0)
|
||||
if micro_batch.rl_weights is not None
|
||||
else None,
|
||||
|
||||
@@ -7,6 +7,7 @@ from jaxtyping import Bool, Float, Int, jaxtyped
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import sampling_replay_mask
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -54,6 +55,27 @@ def selective_log_softmax(
|
||||
return torch.gather(logprobs, dim=-1, index=index.unsqueeze(-1)).squeeze(-1)
|
||||
|
||||
|
||||
@jaxtyped(typechecker=typechecker)
|
||||
def selective_log_softmax_with_sampling_mask(
|
||||
logits: Float[Tensor, "batch seq vocab"],
|
||||
index: Int[Tensor, "batch seq"],
|
||||
sampling_mask: Int[Tensor, "batch seq mask"],
|
||||
) -> Float[Tensor, "batch seq"]:
|
||||
"""Per-token logprobs with sampling-mask replay: positions with a usable
|
||||
mask (see ``sampling_replay_mask``) get ``logits[index] -
|
||||
logsumexp(logits[mask])``, others full-vocab. Non-replayed rows are zeroed
|
||||
before the logsumexp so the unselected ``where`` branch can't emit NaN grads.
|
||||
"""
|
||||
full_logprobs = selective_log_softmax(logits, index)
|
||||
replay = sampling_replay_mask(sampling_mask, index)
|
||||
mask_logits = torch.gather(logits, -1, sampling_mask.clamp_min(0).long())
|
||||
mask_logits = torch.where(sampling_mask >= 0, mask_logits, float("-inf"))
|
||||
mask_logits = torch.where(replay.unsqueeze(-1), mask_logits, 0.0)
|
||||
logz_masked = torch.logsumexp(mask_logits, dim=-1)
|
||||
target_logits = torch.gather(logits, -1, index.unsqueeze(-1)).squeeze(-1)
|
||||
return torch.where(replay, target_logits - logz_masked, full_logprobs)
|
||||
|
||||
|
||||
@jaxtyped(typechecker=typechecker)
|
||||
@torch.compile(dynamic=True)
|
||||
def compute_entropy(shifted_logits: Float[Tensor, "batch seq vocab"]) -> Float[Tensor, "batch seq"]:
|
||||
@@ -63,14 +85,15 @@ def compute_entropy(shifted_logits: Float[Tensor, "batch seq vocab"]) -> Float[T
|
||||
return entropy
|
||||
|
||||
|
||||
def shift_tensor_left(t: Float[Tensor, "batch seq"]) -> Float[Tensor, "batch seq"]:
|
||||
"""Shifts the tensor one token to the left.
|
||||
def shift_tensor_left(t: Tensor, pad_value: float = 0.0) -> Tensor:
|
||||
"""Shifts the tensor one position to the left along dim 1.
|
||||
|
||||
Used to create labels from input_ids: labels[i] = input_ids[i+1].
|
||||
The last position is padded with 0 (a valid token index) since this value
|
||||
will be shifted off by shift_tensor_right and never used.
|
||||
Used to create labels from input_ids: labels[i] = input_ids[i+1]. The last
|
||||
position is padded with ``pad_value`` (0 is a valid token index but gets
|
||||
shifted off by shift_tensor_right and never used). Works for [batch, seq]
|
||||
labels and label-aligned [batch, seq, ...] fields like sampling_mask.
|
||||
"""
|
||||
return torch.cat([t[:, 1:], torch.full((t.shape[0], 1), 0, device=t.device, dtype=t.dtype)], dim=1)
|
||||
return torch.cat([t[:, 1:], torch.full_like(t[:, :1], pad_value)], dim=1)
|
||||
|
||||
|
||||
def shift_tensor_right(t: Float[Tensor, "batch seq"], pad_value: float | None = None) -> Float[Tensor, "batch seq"]:
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
import atexit
|
||||
import json
|
||||
import math
|
||||
from collections.abc import Mapping, Sequence
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import IPOLossConfig, TrainerConfig
|
||||
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
class DisabledTokenExporter:
|
||||
def export(self, *args: Any, **kwargs: Any) -> None:
|
||||
return
|
||||
|
||||
def mark_stable(self) -> None:
|
||||
return
|
||||
|
||||
def close(self) -> None:
|
||||
return
|
||||
|
||||
|
||||
class TokenExporter:
|
||||
def __init__(
|
||||
self,
|
||||
output_dir: Path,
|
||||
rank: int,
|
||||
) -> None:
|
||||
self.rank = rank
|
||||
self.output_dir = output_dir / "token_exports"
|
||||
self._closed = False
|
||||
self._initialized_files: set[tuple[int, int]] = set()
|
||||
self._sequences_by_file: dict[tuple[int, int], int] = {}
|
||||
self._pending_stable_dirs: set[Path] = set()
|
||||
atexit.register(self.close)
|
||||
|
||||
def export(
|
||||
self,
|
||||
step: int,
|
||||
micro_step: int,
|
||||
micro_batch: Mapping[str, Any],
|
||||
model_output: Mapping[str, Tensor],
|
||||
sequence_lengths: list[int],
|
||||
loss_config: Any,
|
||||
) -> None:
|
||||
columns = _export_columns(micro_batch, model_output, loss_config)
|
||||
_check_lengths(columns)
|
||||
file_key = (step, self.rank)
|
||||
|
||||
start = 0
|
||||
for micro_sequence_idx, length in enumerate(sequence_lengths):
|
||||
raw_end = start + length
|
||||
end = _trim_padding(columns, start, raw_end)
|
||||
if end > start and any(columns["loss_mask"][start:end]):
|
||||
self._write(
|
||||
{
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"step": step,
|
||||
"rank": self.rank,
|
||||
"micro_step": micro_step,
|
||||
"micro_sequence_idx": micro_sequence_idx,
|
||||
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
|
||||
"env_name": _first_non_empty(columns["env_names"][start:end]),
|
||||
**_slice_columns(columns, start, end),
|
||||
},
|
||||
step,
|
||||
)
|
||||
self._sequences_by_file[file_key] = self._sequences_by_file.get(file_key, 0) + 1
|
||||
start = raw_end
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
|
||||
def mark_stable(self) -> None:
|
||||
# The caller barriers first so a STABLE only lands after every rank flushed.
|
||||
while self._pending_stable_dirs:
|
||||
stable_dir = self._pending_stable_dirs.pop()
|
||||
(stable_dir / "STABLE").touch()
|
||||
|
||||
def _export_dir(self, step: int) -> Path:
|
||||
return self.output_dir / f"step_{step}"
|
||||
|
||||
def _export_file(self, step: int) -> Path:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
|
||||
step_dir = self._export_dir(step)
|
||||
try:
|
||||
step_dir.mkdir(parents=True, exist_ok=True)
|
||||
except FileExistsError:
|
||||
if not step_dir.is_dir():
|
||||
raise
|
||||
return step_dir / f"rank_{self.rank}.jsonl"
|
||||
|
||||
def _write(self, record: dict[str, Any], step: int) -> None:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
|
||||
file_key = (step, self.rank)
|
||||
mode = "a" if file_key in self._initialized_files else "w"
|
||||
export_file = self._export_file(step)
|
||||
with export_file.open(mode, encoding="utf-8") as file:
|
||||
file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
|
||||
self._initialized_files.add(file_key)
|
||||
self._pending_stable_dirs.add(export_file.parent)
|
||||
|
||||
|
||||
def setup_token_exporter(
|
||||
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
|
||||
) -> TokenExporter | DisabledTokenExporter:
|
||||
if not config.enable_token_export:
|
||||
return DisabledTokenExporter()
|
||||
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
|
||||
return DisabledTokenExporter()
|
||||
|
||||
exporter = TokenExporter(config.output_dir, world.rank)
|
||||
logger.info(f"Writing token exports under {exporter.output_dir}")
|
||||
return exporter
|
||||
|
||||
|
||||
def _export_columns(
|
||||
micro_batch: Mapping[str, Any], model_output: Mapping[str, Tensor], loss_config: Any
|
||||
) -> dict[str, list[Any]]:
|
||||
token_ids = _tensor_to_ints(micro_batch["input_ids"])
|
||||
seq_len = len(token_ids)
|
||||
trainer_logprobs = model_output["logprobs"]
|
||||
export_tensors = _compute_export_tensors(micro_batch, trainer_logprobs, loss_config)
|
||||
|
||||
return {
|
||||
"token_ids": token_ids,
|
||||
"position_ids": _tensor_to_ints(micro_batch["position_ids"]),
|
||||
"loss_mask": _tensor_to_bools(micro_batch["loss_mask"]),
|
||||
"advantages": _tensor_to_floats(micro_batch["advantages"]),
|
||||
"inference_logprobs": _tensor_to_floats(micro_batch["inference_logprobs"]),
|
||||
"trainer_logprobs": _tensor_to_floats(trainer_logprobs),
|
||||
"entropy": _tensor_to_floats(model_output["entropy"]),
|
||||
"mismatch_kl": _optional_tensor_to_floats(export_tensors["mismatch_kl"], seq_len),
|
||||
"log_importance_ratio": _optional_tensor_to_floats(export_tensors["log_importance_ratio"], seq_len),
|
||||
"importance_ratio": _optional_tensor_to_floats(export_tensors["importance_ratio"], seq_len),
|
||||
"prob_delta": _optional_tensor_to_floats(export_tensors["prob_delta"], seq_len),
|
||||
"is_masked": _optional_tensor_to_bools(export_tensors["is_masked"], seq_len),
|
||||
"is_masked_high": _optional_tensor_to_bools(export_tensors["is_masked_high"], seq_len),
|
||||
"is_masked_low": _optional_tensor_to_bools(export_tensors["is_masked_low"], seq_len),
|
||||
# Component weight streams; ``None`` columns mean the defaults (rl 1.0
|
||||
# on the loss mask, no ce/ref_kl component).
|
||||
"rl_weights": _optional_tensor_to_floats(micro_batch.get("rl_weights"), seq_len),
|
||||
"ce_weights": _optional_tensor_to_floats(micro_batch.get("ce_weights"), seq_len),
|
||||
"ref_kl_weights": _optional_tensor_to_floats(micro_batch.get("ref_kl_weights"), seq_len),
|
||||
"env_names": list(micro_batch["env_names"]),
|
||||
}
|
||||
|
||||
|
||||
def _compute_export_tensors(
|
||||
micro_batch: Mapping[str, Any], trainer_logprobs: Tensor, loss_config: Any
|
||||
) -> dict[str, Tensor | None]:
|
||||
fields: dict[str, Tensor | None] = {
|
||||
"log_importance_ratio": None,
|
||||
"importance_ratio": None,
|
||||
"mismatch_kl": None,
|
||||
"prob_delta": None,
|
||||
"is_masked": None,
|
||||
"is_masked_high": None,
|
||||
"is_masked_low": None,
|
||||
}
|
||||
# Ratio-based fields are meaningless when no token has sampling logprobs
|
||||
# (e.g. pure CE batches distilling frozen-model tokens): no rl member
|
||||
# (stream present but all-zero) and no ref_kl member.
|
||||
rl_weights = micro_batch.get("rl_weights")
|
||||
ref_kl_weights = micro_batch.get("ref_kl_weights")
|
||||
no_rl = rl_weights is not None and not bool((rl_weights != 0).any())
|
||||
no_ref_kl = ref_kl_weights is None or not bool((ref_kl_weights != 0).any())
|
||||
if no_rl and no_ref_kl:
|
||||
return fields
|
||||
|
||||
inference_logprobs = micro_batch["inference_logprobs"].to(trainer_logprobs.device)
|
||||
loss_mask = micro_batch["loss_mask"].to(trainer_logprobs.device)
|
||||
with torch.no_grad():
|
||||
log_ratio, ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(trainer_logprobs, inference_logprobs)
|
||||
prob_delta = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
|
||||
fields["log_importance_ratio"] = log_ratio
|
||||
fields["importance_ratio"] = ratio
|
||||
fields["mismatch_kl"] = mismatch_kl
|
||||
fields["prob_delta"] = prob_delta
|
||||
if isinstance(loss_config, IPOLossConfig):
|
||||
invalid_high = prob_delta > loss_config.eps
|
||||
invalid_low = prob_delta < -loss_config.eps
|
||||
fields["is_masked"] = loss_mask & (invalid_high | invalid_low)
|
||||
fields["is_masked_high"] = loss_mask & invalid_high
|
||||
fields["is_masked_low"] = loss_mask & invalid_low
|
||||
return fields
|
||||
|
||||
|
||||
def _tensor_to_ints(tensor: Tensor) -> list[int]:
|
||||
return [int(value) for value in tensor.detach().cpu().reshape(-1).tolist()]
|
||||
|
||||
|
||||
def _tensor_to_bools(tensor: Tensor) -> list[bool]:
|
||||
return [bool(value) for value in tensor.detach().cpu().reshape(-1).tolist()]
|
||||
|
||||
|
||||
def _tensor_to_floats(tensor: Tensor) -> list[float | None]:
|
||||
values = tensor.detach().to(dtype=torch.float32, device="cpu").reshape(-1).tolist()
|
||||
return [_json_float(value) for value in values]
|
||||
|
||||
|
||||
def _optional_tensor_to_floats(tensor: Tensor | None, seq_len: int) -> list[float | None]:
|
||||
if tensor is None:
|
||||
return [None] * seq_len
|
||||
return _tensor_to_floats(tensor)
|
||||
|
||||
|
||||
def _optional_tensor_to_bools(tensor: Tensor | None, seq_len: int) -> list[bool | None]:
|
||||
if tensor is None:
|
||||
return [None] * seq_len
|
||||
return _tensor_to_bools(tensor)
|
||||
|
||||
|
||||
def _check_lengths(columns: Mapping[str, Sequence[Any]]) -> None:
|
||||
lengths = {key: len(values) for key, values in columns.items()}
|
||||
if len(set(lengths.values())) != 1:
|
||||
raise ValueError(f"Token export fields must have aligned lengths, got {lengths}")
|
||||
|
||||
|
||||
def _slice_columns(columns: Mapping[str, Sequence[Any]], start: int, end: int) -> dict[str, list[Any]]:
|
||||
return {key: list(values[start:end]) for key, values in columns.items() if key != "env_names"}
|
||||
|
||||
|
||||
def _trim_padding(columns: Mapping[str, Sequence[Any]], start: int, end: int) -> int:
|
||||
env_names = columns["env_names"]
|
||||
loss_mask = columns["loss_mask"]
|
||||
while end > start and env_names[end - 1] == "" and not loss_mask[end - 1]:
|
||||
end -= 1
|
||||
return end
|
||||
|
||||
|
||||
def _json_float(value: float | None) -> float | None:
|
||||
if value is None:
|
||||
return None
|
||||
value = float(value)
|
||||
if not math.isfinite(value):
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _first_non_empty(values: Sequence[str]) -> str | None:
|
||||
for value in values:
|
||||
if value:
|
||||
return value
|
||||
return None
|
||||
@@ -31,11 +31,12 @@ from prime_rl.trainer.rl.loss import (
|
||||
compute_loss,
|
||||
compute_importance_ratio_and_mismatch_kl,
|
||||
selective_log_softmax,
|
||||
selective_log_softmax_with_sampling_mask,
|
||||
setup_rl_loss_fn,
|
||||
shift_tensor_left,
|
||||
shift_tensor_right,
|
||||
)
|
||||
from prime_rl.trainer.rl.token_export import setup_token_exporter
|
||||
from prime_rl.trainer.rl.annotations import AnnotationWriter
|
||||
from prime_rl.trainer.model import (
|
||||
forward,
|
||||
get_full_offload_dtype_policy,
|
||||
@@ -257,7 +258,7 @@ def train(config: TrainerConfig):
|
||||
)
|
||||
logger.debug(f"Initialized data loader in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
token_exporter = setup_token_exporter(config, parallel_dims, world, logger)
|
||||
annotation_writer = AnnotationWriter(parallel_dims, world)
|
||||
|
||||
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
|
||||
|
||||
@@ -377,6 +378,10 @@ def train(config: TrainerConfig):
|
||||
# we could've gotten routed experts from the inference server, but we didn't enable router replay
|
||||
routed_experts = None
|
||||
|
||||
sampling_mask = (
|
||||
micro_batch["sampling_mask"].to("cuda") if micro_batch["sampling_mask"] is not None else None
|
||||
)
|
||||
|
||||
# Multimodal kwargs are an opaque per-model dict (e.g.
|
||||
# {"pixel_values": ..., "image_grid_thw": ...} for Qwen3-VL,
|
||||
# just {"pixel_values": ...} for Gemma3-VL) — we move every
|
||||
@@ -397,6 +402,10 @@ def train(config: TrainerConfig):
|
||||
seq_lens = micro_batch["seq_lens"].to("cuda")
|
||||
|
||||
labels = shift_tensor_left(input_ids)
|
||||
if sampling_mask is not None:
|
||||
# Sampling masks ride at the sampled token's own position (like inference
|
||||
# logprobs); shift to align with the label each position predicts.
|
||||
sampling_mask = shift_tensor_left(sampling_mask, pad_value=-1)
|
||||
|
||||
seq_lens_are_pre_shard = False
|
||||
|
||||
@@ -417,6 +426,10 @@ def train(config: TrainerConfig):
|
||||
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
if routed_experts is not None and not defer_vlm_cp_to_model:
|
||||
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
if sampling_mask is not None:
|
||||
# The LM head consumes masks after any deferred VLM sharding, so
|
||||
# they must follow the label shard rather than the input shard.
|
||||
sampling_mask = shard_for_cp(sampling_mask, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
|
||||
if config.model.lora:
|
||||
lora_num_tokens = micro_batch["lora_num_tokens"].to("cuda")
|
||||
@@ -436,6 +449,12 @@ def train(config: TrainerConfig):
|
||||
if cp_enabled:
|
||||
temperatures = shard_for_cp(temperatures, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
|
||||
if sampling_mask is not None:
|
||||
assert sampling_mask.shape[:2] == labels.shape, (
|
||||
f"sampling_mask shape {tuple(sampling_mask.shape)} is not aligned with "
|
||||
f"labels shape {tuple(labels.shape)}"
|
||||
)
|
||||
|
||||
# Forward pass with per-token temperatures
|
||||
with maybe_record_function("forward"), maybe_activation_offloading(config.model.ac_offloading):
|
||||
out = forward(
|
||||
@@ -449,6 +468,7 @@ def train(config: TrainerConfig):
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
routed_experts=routed_experts,
|
||||
sampling_mask=sampling_mask,
|
||||
)
|
||||
|
||||
if out.get("logprobs") is None:
|
||||
@@ -457,7 +477,10 @@ def train(config: TrainerConfig):
|
||||
logits = out["logits"]
|
||||
# Per-token temperature scaling: temperatures is [batch, seq], logits is [batch, seq, vocab]
|
||||
scaled_logits = logits / temperatures.unsqueeze(-1)
|
||||
out["logprobs"] = selective_log_softmax(scaled_logits, labels)
|
||||
if sampling_mask is not None:
|
||||
out["logprobs"] = selective_log_softmax_with_sampling_mask(scaled_logits, labels, sampling_mask)
|
||||
else:
|
||||
out["logprobs"] = selective_log_softmax(scaled_logits, labels)
|
||||
out["entropy"] = compute_entropy(scaled_logits)
|
||||
# else: FusedOutputLinear was used - logprobs already computed with per-token temperatures
|
||||
|
||||
@@ -537,14 +560,7 @@ def train(config: TrainerConfig):
|
||||
for env_name, indices in mismatch_env_to_indices.items():
|
||||
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
|
||||
|
||||
token_exporter.export(
|
||||
progress.step,
|
||||
micro_step,
|
||||
micro_batch,
|
||||
out,
|
||||
sequence_lengths,
|
||||
config.loss,
|
||||
)
|
||||
annotation_writer.export(micro_batch, out)
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
load_balance_stats = get_load_balance_stats(model)
|
||||
@@ -566,9 +582,7 @@ def train(config: TrainerConfig):
|
||||
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
|
||||
logger.debug(micro_step_message)
|
||||
|
||||
if config.enable_token_export:
|
||||
dist.barrier()
|
||||
token_exporter.mark_stable()
|
||||
annotation_writer.flush()
|
||||
|
||||
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
|
||||
# across dp_cp so the final gradient is the true per-token mean over the global batch.
|
||||
@@ -731,8 +745,6 @@ def train(config: TrainerConfig):
|
||||
prof.export_chrome_trace(trace_file)
|
||||
logger.info(f"Saved trace to {trace_file}")
|
||||
|
||||
token_exporter.close()
|
||||
|
||||
# Write final checkpoint
|
||||
if config.ckpt is not None:
|
||||
logger.info(f"Saving final checkpoint at step {progress.step}")
|
||||
|
||||
@@ -9,6 +9,7 @@ from prime_rl.transports.batch.filesystem import (
|
||||
from prime_rl.transports.batch.types import (
|
||||
MicroBatch,
|
||||
RoutedExperts,
|
||||
SamplingMask,
|
||||
TrainingSample,
|
||||
)
|
||||
from prime_rl.transports.batch.zmq import (
|
||||
@@ -48,6 +49,7 @@ __all__ = [
|
||||
"BatchSender",
|
||||
"TrainingSample",
|
||||
"MicroBatch",
|
||||
"SamplingMask",
|
||||
"RoutedExperts",
|
||||
"setup_batch_sender",
|
||||
"setup_batch_receiver",
|
||||
|
||||
@@ -3,7 +3,7 @@ from pathlib import Path
|
||||
|
||||
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
|
||||
from prime_rl.transports.batch.types import MicroBatch
|
||||
from prime_rl.utils.pathing import get_rollout_dir, get_step_path, sync_wait_for_path
|
||||
from prime_rl.utils.pathing import get_batch_dir, get_step_path, sync_wait_for_path
|
||||
|
||||
|
||||
class FileSystemBatchSender(BatchSender):
|
||||
@@ -11,7 +11,7 @@ class FileSystemBatchSender(BatchSender):
|
||||
|
||||
def __init__(self, output_dir: Path, data_world_size: int, current_step: int = 0):
|
||||
super().__init__(output_dir, data_world_size)
|
||||
self.rollout_dir = get_rollout_dir(output_dir)
|
||||
self.batch_dir = get_batch_dir(output_dir)
|
||||
self.current_step = current_step
|
||||
|
||||
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
|
||||
@@ -21,7 +21,7 @@ class FileSystemBatchSender(BatchSender):
|
||||
for micro_batch_list in micro_batch_grid:
|
||||
assert len(micro_batch_list) == len(micro_batch_grid[0]), "All micro batch lists must have the same length"
|
||||
|
||||
step_path = get_step_path(self.rollout_dir, self.current_step)
|
||||
step_path = get_step_path(self.batch_dir, self.current_step)
|
||||
step_path.mkdir(parents=True, exist_ok=True)
|
||||
await asyncio.to_thread(self._encode_and_write, micro_batch_grid, step_path)
|
||||
self.current_step += 1
|
||||
@@ -40,11 +40,11 @@ class FileSystemBatchReceiver(BatchReceiver):
|
||||
|
||||
def __init__(self, output_dir: Path, data_rank: int, current_step: int = 0):
|
||||
super().__init__(output_dir, data_rank)
|
||||
self.rollout_dir = get_rollout_dir(output_dir)
|
||||
self.batch_dir = get_batch_dir(output_dir)
|
||||
self.current_step = current_step
|
||||
|
||||
def _get_micro_batch_path(self) -> Path:
|
||||
return get_step_path(self.rollout_dir, self.current_step) / f"rank_{self.data_rank}.bin"
|
||||
return get_step_path(self.batch_dir, self.current_step) / f"rank_{self.data_rank}.bin"
|
||||
|
||||
def wait(self) -> None:
|
||||
"""Wait for the micro batch file to appear on disk."""
|
||||
|
||||
@@ -18,6 +18,13 @@ class RoutedExperts(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tru
|
||||
dtype: str
|
||||
|
||||
|
||||
# Sampling masks for top-p/top-k replay: flat int32 token-id bytes plus an
|
||||
# int32 count per token position (0 = no mask); len(ids) == 4 * counts.sum().
|
||||
class SamplingMask(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
ids: bytes
|
||||
counts: bytes
|
||||
|
||||
|
||||
# Produced by the orchestrator's train sink; consumed in-process by
|
||||
# ``prepare_batch``, which packs samples into per-rank ``MicroBatch``es.
|
||||
class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
@@ -69,6 +76,16 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
|
||||
# samples without live rl member tokens (the trainer raises otherwise).
|
||||
advantages: list[float] | None = None
|
||||
|
||||
# Appended fields only: array_like structs encode positionally, so appending
|
||||
# keeps the wire layout of earlier fields stable across versions.
|
||||
sampling_mask: SamplingMask | None = None
|
||||
|
||||
# Identity of the branch this sample was built from, so the trainer can key
|
||||
# its per-token annotations back to the rollout trace. ``None`` on synthetic
|
||||
# samples (e.g. fake data).
|
||||
trace_id: str | None = None
|
||||
branch_index: int | None = None
|
||||
|
||||
|
||||
# Orchestrator -> Trainer
|
||||
class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
@@ -97,3 +114,12 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
rl_weights: list[float] | None = None
|
||||
ce_weights: list[float] | None = None
|
||||
ref_kl_weights: list[float] | None = None
|
||||
|
||||
# See TrainingSample.sampling_mask; appended for wire-layout stability.
|
||||
sampling_mask: SamplingMask | None = None
|
||||
|
||||
# Per-sequence branch identity, parallel to ``sequence_lengths`` (see
|
||||
# TrainingSample.trace_id). ``""`` / ``-1`` mark an unknown sequence
|
||||
# (e.g. a dummy micro batch). ``None`` when no packed sample carried one.
|
||||
trace_ids: list[str] | None = None
|
||||
branch_indices: list[int] | None = None
|
||||
|
||||
@@ -204,8 +204,14 @@ def get_ckpt_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "checkpoints"
|
||||
|
||||
|
||||
def get_rollout_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "rollouts"
|
||||
def get_batch_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "batches"
|
||||
|
||||
|
||||
def get_file_monitor_dir(output_dir: Path) -> Path:
|
||||
"""Everything the file monitor dumps locally: the metrics, and the traces with
|
||||
the annotations about them."""
|
||||
return output_dir / "monitors" / "file"
|
||||
|
||||
|
||||
def get_eval_dir(output_dir: Path) -> Path:
|
||||
@@ -305,12 +311,12 @@ def validate_run_dir(
|
||||
|
||||
|
||||
def clean_future_steps(output_dir: Path, resume_step: int) -> None:
|
||||
"""Remove stale rollouts past ``resume_step`` and broadcasts from it onward.
|
||||
"""Remove stale step artifacts past ``resume_step`` and broadcasts from it onward.
|
||||
|
||||
Pass ``resume_step=-1`` to wipe every step directory (fresh runs).
|
||||
"""
|
||||
cleanup_rules = [
|
||||
(get_rollout_dir(output_dir), lambda step: step > resume_step),
|
||||
(get_batch_dir(output_dir), lambda step: step > resume_step),
|
||||
(get_broadcast_dir(output_dir), lambda step: step >= resume_step),
|
||||
]
|
||||
|
||||
|
||||
@@ -19,11 +19,12 @@ from prime_rl.utils.logger import get_logger
|
||||
# ruff: noqa: F401
|
||||
from prime_rl.utils.pathing import (
|
||||
get_all_ckpt_steps,
|
||||
get_batch_dir,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_eval_dir,
|
||||
get_file_monitor_dir,
|
||||
get_log_dir,
|
||||
get_rollout_dir,
|
||||
get_step_path,
|
||||
resolve_latest_ckpt_step,
|
||||
sync_wait_for_path,
|
||||
|
||||
@@ -112,7 +112,7 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
|
||||
page.wait_for_timeout(1500)
|
||||
assert page.locator("#config-view .j-line").count() > 10, "resolved config tree did not render"
|
||||
|
||||
# traces: when the run saved rollouts, episodes must render and open
|
||||
# traces: when the run shipped a cohort, episodes must render and open
|
||||
rollout_steps = page.evaluate(
|
||||
f"""fetch('{base}/api/runs/{run_name}/rollouts').then(r => r.json()).then(d => d.steps.length)"""
|
||||
)
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import pickle
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from prime_rl.evals.ckpt import CheckpointManager
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
|
||||
|
||||
def _task(key: str) -> SimpleNamespace:
|
||||
return SimpleNamespace(key=key, hash=key)
|
||||
|
||||
|
||||
def _env(name: str, task_keys: list[str], *, interval: int = 1) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
name=name,
|
||||
examples=[_task(key) for key in task_keys],
|
||||
config=SimpleNamespace(interval=interval),
|
||||
)
|
||||
|
||||
|
||||
def _eval_config() -> SimpleNamespace:
|
||||
return SimpleNamespace(skip_first_step=False)
|
||||
|
||||
|
||||
def _queued_tasks(eval_source: EvalSource) -> list[tuple[str, str, int | None]]:
|
||||
return [(request.env_name, request.task.key, request.source_index) for request in eval_source.queue]
|
||||
|
||||
|
||||
def test_eval_source_cursor_advances_only_over_completed_prefix() -> None:
|
||||
eval_source = EvalSource(
|
||||
[_env("math", ["m0", "m1"]), _env("code", ["c0", "c1"])],
|
||||
_eval_config(),
|
||||
)
|
||||
|
||||
assert eval_source.trigger(0) == ["math", "code"]
|
||||
assert _queued_tasks(eval_source) == [
|
||||
("math", "m0", 0),
|
||||
("code", "c0", 1),
|
||||
("math", "m1", 2),
|
||||
("code", "c1", 3),
|
||||
]
|
||||
|
||||
assert eval_source.mark_completed(1) is False
|
||||
assert eval_source.cursor == 0
|
||||
|
||||
assert eval_source.mark_completed(3) is False
|
||||
assert eval_source.cursor == 0
|
||||
|
||||
assert eval_source.mark_completed(0) is True
|
||||
assert eval_source.cursor == 2
|
||||
|
||||
assert eval_source.mark_completed(2) is True
|
||||
assert eval_source.cursor == 4
|
||||
|
||||
|
||||
def test_eval_checkpoint_saves_only_cursor_and_resume_skips_completed_prefix(tmp_path) -> None:
|
||||
eval_envs = [_env("math", ["m0", "m1"]), _env("code", ["c0", "c1"])]
|
||||
eval_source = EvalSource(eval_envs, _eval_config())
|
||||
eval_source.load_state_dict({"cursor": 2})
|
||||
|
||||
assert eval_source.trigger(0) == ["math", "code"]
|
||||
assert _queued_tasks(eval_source) == [
|
||||
("math", "m1", 2),
|
||||
("code", "c1", 3),
|
||||
]
|
||||
assert eval_source.triggered_task_count("math", 0) == 1
|
||||
assert eval_source.triggered_task_count("code", 0) == 1
|
||||
|
||||
ckpt = CheckpointManager(tmp_path)
|
||||
ckpt.save(eval_source)
|
||||
|
||||
with (ckpt.get_ckpt_path(2) / "progress.pt").open("rb") as f:
|
||||
assert pickle.load(f) == {"cursor": 2}
|
||||
|
||||
assert ckpt.latest_step() == 2
|
||||
|
||||
restored_source = EvalSource(eval_envs, _eval_config())
|
||||
ckpt.load(2, restored_source)
|
||||
|
||||
assert restored_source.state_dict() == {"cursor": 2}
|
||||
|
||||
|
||||
def test_eval_checkpoint_rejects_step_cursor_mismatch(tmp_path) -> None:
|
||||
eval_source = EvalSource([_env("math", ["m0"])], _eval_config())
|
||||
eval_source.load_state_dict({"cursor": 1})
|
||||
|
||||
ckpt = CheckpointManager(tmp_path)
|
||||
ckpt.save(eval_source)
|
||||
|
||||
restored_source = EvalSource([_env("math", ["m0"])], _eval_config())
|
||||
with pytest.raises(ValueError, match="contains cursor 1, expected step 2"):
|
||||
ckpt.load(2, restored_source, path=ckpt.get_ckpt_path(1))
|
||||
@@ -129,6 +129,44 @@ def test_prepare_batch_balances_micro_batches_across_workers(
|
||||
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 0
|
||||
|
||||
|
||||
def test_prepare_batch_preserves_branch_identity(make_training_example):
|
||||
examples = []
|
||||
for i in range(5):
|
||||
example = make_training_example()
|
||||
example.trace_id = f"trace-{i}"
|
||||
example.branch_index = i
|
||||
examples.append(example)
|
||||
examples.append(make_training_example()) # no identity -> sentinels
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=4,
|
||||
num_train_workers=2,
|
||||
bin_cost=build_bin_cost(None),
|
||||
pad_to_multiple_of=8,
|
||||
)
|
||||
|
||||
seen: set[tuple[str, int]] = set()
|
||||
for batch in _flatten_batches(batches_per_gpu):
|
||||
if not _has_loss_tokens(batch):
|
||||
# Dummies are copies of real batches; identity must not survive the copy.
|
||||
assert batch.trace_ids is None and batch.branch_indices is None
|
||||
continue
|
||||
assert len(batch.trace_ids) == len(batch.branch_indices) == len(batch.sequence_lengths)
|
||||
seen.update(zip(batch.trace_ids, batch.branch_indices))
|
||||
assert seen == {(f"trace-{i}", i) for i in range(5)} | {("", -1)}
|
||||
|
||||
|
||||
def test_prepare_sample_truncation_keeps_identity():
|
||||
sample = make_sized_training_example(10)
|
||||
sample.trace_id = "trace-x"
|
||||
sample.branch_index = 2
|
||||
micro_batch = prepare_sample(sample, seq_len=4)
|
||||
assert len(micro_batch.input_ids) == 4
|
||||
assert micro_batch.trace_ids == ["trace-x"]
|
||||
assert micro_batch.branch_indices == [2]
|
||||
|
||||
|
||||
def test_randomized_packing_invariants():
|
||||
rng = np.random.default_rng(0)
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal
|
||||
|
||||
@@ -356,9 +357,52 @@ def test_env_algo_overrides_top_level():
|
||||
)
|
||||
|
||||
|
||||
def test_trainer_enable_token_export_cli_flag():
|
||||
assert not cli(TrainerConfig, args=[]).enable_token_export
|
||||
assert cli(TrainerConfig, args=["--enable-token-export"]).enable_token_export
|
||||
def test_policy_sources_accept_different_top_p_values():
|
||||
with pytest.warns(UserWarning, match="defaulting top_k"):
|
||||
config = OrchestratorConfig.model_validate(
|
||||
{
|
||||
"renderer": {"name": "qwen3"},
|
||||
"train": {
|
||||
"source": [
|
||||
{
|
||||
"name": "top-p-95",
|
||||
"env": {"taskset": {"id": "reverse-text"}},
|
||||
"sampling": {"top_p": 0.95},
|
||||
},
|
||||
{
|
||||
"name": "top-p-97",
|
||||
"env": {"taskset": {"id": "reverse-text"}},
|
||||
"sampling": {"top_p": 0.97},
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert [source.sampling.top_k for source in config.train.source] == [512, 512]
|
||||
|
||||
|
||||
def test_policy_sources_reject_mixed_top_k_capture():
|
||||
with pytest.warns(UserWarning, match="defaulting top_k"):
|
||||
with pytest.raises(ValidationError, match="cannot mix top_k > 0 and top_k = -1"):
|
||||
OrchestratorConfig.model_validate(
|
||||
{
|
||||
"renderer": {"name": "qwen3"},
|
||||
"train": {
|
||||
"source": [
|
||||
{
|
||||
"name": "truncated",
|
||||
"env": {"taskset": {"id": "reverse-text"}},
|
||||
"sampling": {"top_p": 0.95},
|
||||
},
|
||||
{
|
||||
"name": "untruncated",
|
||||
"env": {"taskset": {"id": "reverse-text"}},
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_single_node_auto_inference_ports_follow_server_port():
|
||||
@@ -827,3 +871,19 @@ def test_explicit_inference_parser_wins_over_auto():
|
||||
)
|
||||
assert config.inference is not None
|
||||
assert config.inference.vllm.tool_call_parser == "hermes"
|
||||
|
||||
|
||||
def test_combined_replay_uses_v2_runner(monkeypatch):
|
||||
from prime_rl.inference.server import setup_vllm_env
|
||||
|
||||
monkeypatch.delenv("VLLM_USE_V2_MODEL_RUNNER", raising=False)
|
||||
config = InferenceConfig(
|
||||
enable_return_sampling_mask=True,
|
||||
vllm={"enable_return_routed_experts": True},
|
||||
)
|
||||
|
||||
setup_vllm_env(config)
|
||||
|
||||
assert config.enable_return_sampling_mask is True
|
||||
assert config.vllm.enable_return_routed_experts is True
|
||||
assert os.environ["VLLM_USE_V2_MODEL_RUNNER"] == "1"
|
||||
|
||||
@@ -3,8 +3,8 @@ import pytest
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_dirs,
|
||||
get_batch_dir,
|
||||
get_broadcast_dir,
|
||||
get_rollout_dir,
|
||||
get_step_path,
|
||||
validate_run_dir,
|
||||
)
|
||||
@@ -103,17 +103,17 @@ def test_clean_outside_output_dir_raises(tmp_path):
|
||||
|
||||
|
||||
def test_clean_future_steps_rebuilds_resume_broadcast(tmp_path):
|
||||
rollout_dir = get_rollout_dir(tmp_path)
|
||||
batch_dir = get_batch_dir(tmp_path)
|
||||
broadcast_dir = get_broadcast_dir(tmp_path)
|
||||
for parent in (rollout_dir, broadcast_dir):
|
||||
for parent in (batch_dir, broadcast_dir):
|
||||
for step in (1, 2, 3):
|
||||
get_step_path(parent, step).mkdir(parents=True)
|
||||
|
||||
clean_future_steps(tmp_path, resume_step=2)
|
||||
|
||||
assert get_step_path(rollout_dir, 1).exists()
|
||||
assert get_step_path(rollout_dir, 2).exists()
|
||||
assert not get_step_path(rollout_dir, 3).exists()
|
||||
assert get_step_path(batch_dir, 1).exists()
|
||||
assert get_step_path(batch_dir, 2).exists()
|
||||
assert not get_step_path(batch_dir, 3).exists()
|
||||
assert get_step_path(broadcast_dir, 1).exists()
|
||||
assert not get_step_path(broadcast_dir, 2).exists()
|
||||
assert not get_step_path(broadcast_dir, 3).exists()
|
||||
|
||||
@@ -310,21 +310,20 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "anthropic"
|
||||
version = "0.104.1"
|
||||
version = "1.0.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio" },
|
||||
{ name = "distro" },
|
||||
{ name = "docstring-parser" },
|
||||
{ name = "httpx" },
|
||||
{ name = "httpx2" },
|
||||
{ name = "jiter" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/22/c7/7a655b948916f777354648ce979f68b94d5b8dbdb5f61fed1f37fad9378c/anthropic-0.104.1.tar.gz", hash = "sha256:17362b6c45f527afcc9b0fdf62011ffd359726ab2ebcb1978ea0cc41bd8d8d40", size = 850081, upload-time = "2026-05-22T15:36:57.432Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/25/aa/4978e58035bd6c638c7b483450a68b7ef2d732ab78885e27bb9db0cff1a2/anthropic-1.0.0.tar.gz", hash = "sha256:42be3c97604af7252c5898413aee076ace6c46e9bca0d0d90ceb77c7d3719027", size = 1077769, upload-time = "2026-08-20T19:59:00.565Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b8/12/d9ab42790494d7c428391a46cd28492395566a6a8ccb138d681978594455/anthropic-0.104.1-py3-none-any.whl", hash = "sha256:35c8cb456f5a4405aafe1f10f03f6fcc54fa51fa8ec01d655cc4b437d120e9b7", size = 832996, upload-time = "2026-05-22T15:36:59.519Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/5b/db4a854aebf5d33a5ab714c46af6eb85ee44f390ed29b7b325c00b9f11ed/anthropic-1.0.0-py3-none-any.whl", hash = "sha256:32dd52e9e1d774393b27182f451398ba4262287a4d0eab30887f89f1481b3ae4", size = 1171725, upload-time = "2026-08-20T19:58:58.725Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7677,7 +7676,6 @@ source = { editable = "deps/verifiers" }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "anthropic" },
|
||||
{ name = "datasets" },
|
||||
{ name = "gepa" },
|
||||
{ name = "httpx" },
|
||||
{ name = "loguru" },
|
||||
@@ -7696,7 +7694,6 @@ dependencies = [
|
||||
{ name = "tenacity" },
|
||||
{ name = "tomli-w" },
|
||||
{ name = "typing-extensions" },
|
||||
{ name = "uvloop", marker = "platform_python_implementation != 'PyPy'" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
@@ -7710,9 +7707,9 @@ ta = [
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "aiohttp", specifier = ">=3.14.0" },
|
||||
{ name = "anthropic", specifier = ">=0.78.0" },
|
||||
{ name = "datasets", specifier = ">=3.3.0,<6.0.0" },
|
||||
{ name = "aiohttp", specifier = ">=3.14.1" },
|
||||
{ name = "anthropic", specifier = ">=1.0.0" },
|
||||
{ name = "datasets", marker = "extra == 'lean'", specifier = ">=3.3.0,<6.0.0" },
|
||||
{ name = "gepa", specifier = ">=0.0.6" },
|
||||
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.21.0" },
|
||||
{ name = "httpx", specifier = ">=0.27.0" },
|
||||
@@ -7723,22 +7720,21 @@ requires-dist = [
|
||||
{ name = "msgpack", specifier = ">=1.1.2" },
|
||||
{ name = "nltk", marker = "extra == 'ta'", specifier = ">=3.9.2" },
|
||||
{ name = "numpy", specifier = ">=2.1.0" },
|
||||
{ name = "openai", specifier = ">=2.9.0" },
|
||||
{ name = "openai", specifier = ">=2.54.0,<3.0.0" },
|
||||
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
|
||||
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.39" },
|
||||
{ name = "prime-tunnel", specifier = ">=0.1.8" },
|
||||
{ name = "pydantic", specifier = ">=2.12.3" },
|
||||
{ name = "pyzmq", specifier = ">=27.1.0" },
|
||||
{ name = "renderers", extras = ["multimodal"], specifier = ">=0.1.11" },
|
||||
{ name = "renderers", extras = ["multimodal"], specifier = ">=0.1.12.dev2" },
|
||||
{ name = "rich", specifier = ">=11.0.0" },
|
||||
{ name = "tenacity", specifier = ">=8.5.0" },
|
||||
{ name = "textarena", marker = "extra == 'ta'", specifier = "==0.7.4" },
|
||||
{ name = "tomli-w", specifier = ">=1.0.0" },
|
||||
{ name = "typing-extensions", specifier = ">=4.12.2" },
|
||||
{ name = "uvloop", marker = "platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'", specifier = ">=0.21.0" },
|
||||
]
|
||||
provides-extras = ["harbor", "modal", "openenv", "ta"]
|
||||
provides-extras = ["harbor", "lean", "modal", "openenv", "ta"]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [
|
||||
|
||||
Reference in New Issue
Block a user