Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
66e1c2cb07 | ||
|
|
26af0c49e6 | ||
|
|
fc12ef2c66 | ||
|
|
95734aa1dd | ||
|
|
0c58f007bc | ||
|
|
d09bf96dbe | ||
|
|
05967ffcd2 | ||
|
|
21a4a32450 | ||
|
|
a070beecbd | ||
|
|
7da7c4d108 | ||
|
|
9e3be00b39 | ||
|
|
ef66401434 |
+14
-25
@@ -13,7 +13,7 @@ This page covers the math and the configurable algorithmic components: the algor
|
||||
- [Async / Off-Policy Training](#async--off-policy-training)
|
||||
- [Loss](#loss)
|
||||
- [Loss Components](#loss-components)
|
||||
- [Default RL Loss](#default-rl-loss)
|
||||
- [IPO Loss](#ipo-loss)
|
||||
- [Custom Loss](#custom-loss)
|
||||
- [Advantage](#advantage)
|
||||
- [Default Advantage](#default-advantage)
|
||||
@@ -184,47 +184,36 @@ $$
|
||||
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
|
||||
$$
|
||||
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
|
||||
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
|
||||
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
|
||||
|
||||
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
|
||||
|
||||
### Default RL Loss
|
||||
### IPO Loss
|
||||
|
||||
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
|
||||
The default RL loss is Importance Policy Optimization (IPO). It combines an importance-weighted policy-gradient term with a squared log-ratio KL regularizer. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
|
||||
|
||||
$$
|
||||
\mathcal{L}(\theta) = -\,\mathcal{J}_{\text{PG}}(\theta) \;+\; \tau_{KL}\,\mathcal{L}_{KL}(\theta)
|
||||
\mathcal{L}(\theta) = \frac{1}{N}\sum_t
|
||||
\left[
|
||||
-\mathbb{1}\!\left(\left|\pi(y_t)-\mu(y_t)\right| \le \epsilon\right)
|
||||
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}
|
||||
+ \tau_{KL}\log^2\!\left(\frac{\pi(y_t)}{\mu(y_t)}\right)
|
||||
\right].
|
||||
$$
|
||||
|
||||
where the policy-gradient term is
|
||||
$\mu$ is the policy that generated the rollout. $\pi$ is the current trainer policy. $\hat{A}_t$ is the token-level advantage. The trust region uses the sampled token probabilities, not their ratio.
|
||||
|
||||
$$
|
||||
\mathcal{J}_{\text{PG}}(\theta)
|
||||
= \frac{1}{\sum_{j,i} |y_i^{(j)}|}
|
||||
\sum_{j,i,t}
|
||||
\min\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}, \delta\right) \hat{A}^{(j)}_{i,t}
|
||||
$$
|
||||
|
||||
and the KL regularizer penalizes drift between trainer and inference policies via the squared log importance ratio:
|
||||
|
||||
$$
|
||||
\mathcal{L}_{KL}(\theta) = \frac{1}{\sum_{j,i} |y_i^{(j)}|}
|
||||
\sum_{j,i,t} \log^2\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}\right).
|
||||
$$
|
||||
|
||||
$\mu$ is the policy that generated the rollout (inference), $\pi$ is the current policy (trainer), $\hat{A}_{i,t}$ is the token-level advantage, $\delta$ is the importance-sampling clipping ratio, and $\tau_{KL}$ is the KL temperature. The `min` clamps the importance ratio from above so a stale rollout assigning very low probability to a high-reward token doesn't produce a runaway gradient.
|
||||
|
||||
The knobs (under `[trainer.loss]` with `type = "default"`):
|
||||
The knobs under `[trainer.loss]` are:
|
||||
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
|
||||
| `eps` | 0.1 | Maximum absolute probability change before a token is masked. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
|
||||
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
|
||||
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
|
||||
### Custom Loss
|
||||
|
||||
|
||||
@@ -247,8 +247,14 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
Then inspect the resolved config:
|
||||
|
||||
```bash
|
||||
ls /tmp/reverse-dry/check/configs/resolved/
|
||||
ls /tmp/reverse-dry/check/configs/latest/resolved/
|
||||
# rl.json trainer.json orchestrator.json inference.json
|
||||
```
|
||||
|
||||
Each per-process JSON reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/resolved/trainer.json`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
|
||||
Each per-process JSON contains the final, validated configuration that the run
|
||||
uses. This is also what each standalone process reads. For example, the trainer
|
||||
reads `configs/latest/resolved/trainer.json`.
|
||||
|
||||
`configs/latest/command.txt` records the shell-safe launch command and its CLI
|
||||
overrides. Each launch also remains under `configs/attempt_<n>/`. To compare
|
||||
configs, dry-run a known-good base and your overlay. Then diff the two attempts.
|
||||
|
||||
+20
-1
@@ -217,7 +217,8 @@ SFT multi-node:
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1 # required only for online evals
|
||||
gpus_per_node = 8
|
||||
```
|
||||
|
||||
@@ -230,6 +231,24 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
|
||||
|
||||
### NIXL weight broadcast
|
||||
|
||||
Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transfer. Before the first SLURM run, install the NIXL/UCX build and the ModelExpress service binaries on the shared filesystem:
|
||||
|
||||
```bash
|
||||
bash scripts/install_nixl_from_source.sh
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
|
||||
bash scripts/install_modelexpress.sh
|
||||
```
|
||||
|
||||
The generated job starts a job-scoped ModelExpress server and Redis backend on the trainer head node and passes that address to every component. To use an existing service, set `slurm.launch_modelexpress = false` and configure `weight_broadcast.host` and `weight_broadcast.port`.
|
||||
|
||||
The launcher requires the CUDA and InfiniBand transports from `third_party/ucx`. Each NIXL process selects the active InfiniBand port nearest its GPU; an explicitly configured `UCX_NET_DEVICES` takes precedence. Inference ranks start their pulls at different trainer ranks so concurrent workers distribute traffic across all available source rails.
|
||||
|
||||
ModelExpress exchanges peer metadata during startup. Weight updates reuse prepared NIXL requests, post every trainer-rank read in a transfer group concurrently, and use versioned NIXL notifications for source readiness and buffer credits.
|
||||
|
||||
By default, the trainer and inference worker each allocate one transfer arena. Set `weight_broadcast.overlap_transfer_and_replay = true` to allocate two arenas on both sides and replay one weight group while receiving the next. The additional arena is the size of the largest transfer group per GPU; allocation errors are reported instead of silently disabling overlap.
|
||||
|
||||
### Custom Templates
|
||||
|
||||
For unusual partitions, module loads, or environment setup, supply your own Jinja2 template:
|
||||
|
||||
+18
-10
@@ -81,7 +81,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
|
||||
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
|
||||
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
|
||||
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
|
||||
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/latest/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
|
||||
|
||||
### Algorithms
|
||||
|
||||
@@ -125,7 +125,7 @@ Pulled from the console logs and mirrored to W&B.
|
||||
|
||||
- `mismatch_kl/{all,env}/{mean,std,max}` — KL between trainer's current policy and the (older) inference policy that generated the rollouts. A sustained, growing mean is the early-warning sign for off-policy collapse.
|
||||
- `entropy/{all,env}/mean` — too low means mode-collapse; too high means the model isn't committing.
|
||||
- `masked_advantage_{positive,negative}/mean` — fraction of DPPO-masked tokens, split by sign.
|
||||
- `is_masked/mean` — fraction of tokens masked by the IPO trust region.
|
||||
- `optim/grad_norm` — spikes precede divergence; check the loss config or lower the LR.
|
||||
|
||||
**Performance** (trainer + orchestrator step independently):
|
||||
@@ -198,17 +198,17 @@ num_train_gpus = 1 # trainer
|
||||
num_infer_gpus = 1 # inference
|
||||
```
|
||||
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
|
||||
#### Multi-Node (Decoupled Trainer and Inference Pool)
|
||||
#### Multi-Node Trainer and Inference Pool
|
||||
|
||||
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
|
||||
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and evals process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2 # trainer job
|
||||
num_infer_nodes = 1 # eval job (inference pool + evals)
|
||||
num_train_nodes = 2 # trainer nodes
|
||||
num_infer_nodes = 1 # inference pool + evals
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
@@ -217,7 +217,7 @@ tensor_parallel_size = 8
|
||||
job_name = "my-run"
|
||||
```
|
||||
|
||||
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
|
||||
The shared script passes the trainer rank-0 hostname directly to the evals process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, evals never sees a final broadcast, so the job remains active until walltime. Trainer and evals log to one shared W&B run. The trainer creates it, and evals finalizes it.
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
@@ -313,6 +313,13 @@ The exported directory loads directly into `uv run inference --vllm.model <dir>`
|
||||
|
||||
## Observability
|
||||
|
||||
### Config Files
|
||||
|
||||
Each launch writes its command, input TOML, and resolved JSON files to
|
||||
`<run_dir>/configs/attempt_<n>/`. Resumed runs keep the earlier configs.
|
||||
`command.txt` uses shell-safe quoting.
|
||||
`configs/latest` points to the current attempt.
|
||||
|
||||
### Log Files
|
||||
|
||||
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
|
||||
@@ -321,6 +328,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
|
||||
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
|
||||
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
|
||||
├── orchestrator.log # single instance, single file
|
||||
├── evals.log # SFT online-eval process
|
||||
├── inference.log # symlink → inference/node_0.log on multi-node
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node trainer stdout (multi-node only)
|
||||
@@ -331,12 +339,12 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
|
||||
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
|
||||
```
|
||||
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
|
||||
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
|
||||
|
||||
```bash
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,inference}.log
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,evals,inference}.log
|
||||
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
|
||||
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
```
|
||||
|
||||
@@ -27,6 +27,11 @@ class EvalsEvalConfig(EvalConfig):
|
||||
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
|
||||
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
|
||||
|
||||
cancel_on_new_checkpoint: bool = True
|
||||
"""For online evals, cancel unfinished episodes when a newer trainer checkpoint is ready.
|
||||
Disable to finish every triggered eval epoch before loading later weights. The trainer can
|
||||
idle while it waits for slow evals."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
|
||||
@@ -408,6 +408,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
|
||||
@@ -158,6 +158,9 @@ class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
@@ -490,7 +493,10 @@ class RLConfig(BaseConfig):
|
||||
trainer_config_type = TrainerNCCLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
|
||||
else:
|
||||
transport_config = dict(session_id=self.weight_broadcast.session_id)
|
||||
transport_config = dict(
|
||||
session_id=self.weight_broadcast.session_id,
|
||||
overlap_transfer_and_replay=self.weight_broadcast.overlap_transfer_and_replay,
|
||||
)
|
||||
trainer_config_type = TrainerNIXLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNIXLWeightBroadcastConfig
|
||||
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
|
||||
|
||||
@@ -175,9 +175,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Training nodes."""
|
||||
|
||||
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
|
||||
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
|
||||
from the trainer job. The eval job can outlive the trainer job while it evaluates
|
||||
the final weight broadcast."""
|
||||
"""Inference nodes for online evals (alias: ``num_eval_nodes``). These nodes share
|
||||
one SLURM allocation with the trainer nodes."""
|
||||
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
@@ -394,18 +393,18 @@ class SFTConfig(BaseConfig):
|
||||
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
|
||||
|
||||
if self.deployment.type == "multi_node":
|
||||
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
|
||||
# inference pool (one engine per DP rank behind a router) plus the evals process.
|
||||
# Dedicated nodes in the SFT allocation run the inference pool, router,
|
||||
# env servers, and evals process.
|
||||
if self.inference is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an [inference] block - the launcher submits "
|
||||
"a dedicated SLURM job running the inference pool and the evals process."
|
||||
"Multi-node online evals require an [inference] block - dedicated nodes in the "
|
||||
"SFT allocation run the inference pool and evals process."
|
||||
)
|
||||
if self.deployment.num_infer_nodes < 1:
|
||||
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
|
||||
if self.inference.router is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an inference router - the eval job starts one "
|
||||
"Multi-node online evals require an inference router - the launcher starts one "
|
||||
"router in front of the per-rank engines. Remove inference.router = 'None'."
|
||||
)
|
||||
if self.inference.vllm.model != self.model.name:
|
||||
@@ -426,10 +425,10 @@ class SFTConfig(BaseConfig):
|
||||
if self.max_steps is None:
|
||||
warnings.warn(
|
||||
"Online evals without max_steps: the evals process never sees a final checkpoint, "
|
||||
"so the eval SLURM job holds its allocation until its walltime.",
|
||||
"so the SFT SLURM job holds its allocation until its walltime.",
|
||||
stacklevel=2,
|
||||
)
|
||||
# The client is wired at runtime by the eval sbatch script (the router and
|
||||
# The client is wired at runtime by the SFT sbatch script (the router and
|
||||
# per-rank admin URLs are only known once SLURM assigns hosts).
|
||||
return self
|
||||
|
||||
|
||||
@@ -106,6 +106,9 @@ class SlurmConfig(BaseConfig):
|
||||
pre_run_command: str | None = None
|
||||
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
|
||||
|
||||
launch_modelexpress: bool = True
|
||||
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
|
||||
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
|
||||
|
||||
|
||||
@@ -492,26 +492,10 @@ class CheckpointConfig(BaseConfig):
|
||||
"""Skip loading the optimizer state from checkpoint."""
|
||||
|
||||
|
||||
class DefaultLossConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
dppo_mask_low: float = Field(0.2, ge=0)
|
||||
"""Lower DPPO masking threshold."""
|
||||
|
||||
dppo_mask_high: float = Field(0.2, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(1e-3, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IPOLossConfig(BaseConfig):
|
||||
type: Literal["ipo"] = "ipo"
|
||||
ipo_threshold: float = Field(0.1, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
eps: float = Field(0.1, ge=0)
|
||||
"""Maximum absolute probability change before a token is masked."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
@@ -530,7 +514,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -581,6 +565,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two staging arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
@@ -595,7 +582,7 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
data: DataLoaderConfig = DataLoaderConfig()
|
||||
|
||||
loss: LossConfig = DefaultLossConfig()
|
||||
loss: LossConfig = IPOLossConfig()
|
||||
"""Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this."""
|
||||
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
"""Export a verifiers v1 eval run (traces.jsonl) as an SFT dataset for `uv run sft`.
|
||||
|
||||
Reads a finished run's saved traces and reshapes them into the dataset shape the SFT trainer
|
||||
consumes directly (see `prime_rl.trainer.sft.data`): a `messages` column (OpenAI chat wire
|
||||
shape) plus a `tools` column (the tools the model was shown, from `Trace.tools`,
|
||||
JSON-encoded — heterogeneous JSON-schema dicts don't fit a fixed Arrow schema). One row per
|
||||
branch: a linear rollout contributes one sample, a compacted/subagent rollout one per branch
|
||||
(one training sample is built per branch).
|
||||
|
||||
Selection: generation-errored traces (`stop_condition == "error"`) always drop — a broken
|
||||
transcript is not a sample. A scoring-only error keeps the generation outcome as its stop
|
||||
condition and a complete conversation, so it stays; its reward may be partial/zero, which
|
||||
`--min-reward` handles.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python scripts/export_sft.py <run-dir> [--min-reward 1.0] [--drop-truncated]
|
||||
[-o OUT_DIR] [--push HF_REPO_ID]
|
||||
|
||||
Writes `<run-dir>/sft/train.parquet` by default — point the trainer at it with
|
||||
`--data.name <run-dir>/sft`. Requires a verifiers release carrying `Trace.tools`
|
||||
(PrimeIntellect-ai/verifiers#1963).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from datasets import Dataset
|
||||
from verifiers.v1 import Trace, WireTrace
|
||||
from verifiers.v1.dialects.chat import message_to_wire
|
||||
|
||||
|
||||
def sft_rows(trace: Trace) -> list[dict]:
|
||||
"""A trace's SFT rows — one per branch: the branch's conversation as OpenAI chat wire
|
||||
dicts plus the trace's advertised tools, JSON-encoded."""
|
||||
tools = json.dumps([t.model_dump(mode="json", exclude_none=True) for t in trace.tools or []])
|
||||
return [
|
||||
{
|
||||
"messages": [message_to_wire(m) for m in branch.messages],
|
||||
"tools": tools,
|
||||
}
|
||||
for branch in trace.branches
|
||||
if branch.messages
|
||||
]
|
||||
|
||||
|
||||
def keep(trace: Trace, min_reward: float | None, drop_truncated: bool) -> bool:
|
||||
"""Whether a trace is worth training on (see module docstring for the error semantics)."""
|
||||
if trace.stop_condition == "error":
|
||||
return False
|
||||
if drop_truncated and trace.is_truncated:
|
||||
return False
|
||||
return min_reward is None or trace.reward >= min_reward
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("run_dir", type=Path, help="the eval run dir (holds traces.jsonl)")
|
||||
parser.add_argument("--min-reward", type=float, default=None, help="keep traces with reward >= this")
|
||||
parser.add_argument("--drop-truncated", action="store_true", help="drop budget-cut traces")
|
||||
parser.add_argument("-o", "--output-dir", type=Path, default=None, help="default: <run-dir>/sft")
|
||||
parser.add_argument("--push", default=None, help="HF repo id to push to instead of writing parquet")
|
||||
args = parser.parse_args()
|
||||
|
||||
traces_path = args.run_dir / "traces.jsonl"
|
||||
if not traces_path.exists():
|
||||
raise SystemExit(f"no traces.jsonl in {args.run_dir}")
|
||||
|
||||
total, rows = 0, []
|
||||
with traces_path.open(encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if not line.strip():
|
||||
continue
|
||||
total += 1
|
||||
trace = WireTrace.model_validate(json.loads(line))
|
||||
if keep(trace, args.min_reward, args.drop_truncated):
|
||||
rows.extend(sft_rows(trace))
|
||||
print(f"export-sft: {total} trace(s) -> {len(rows)} row(s)")
|
||||
if not rows:
|
||||
raise SystemExit("export-sft: no rows to export after selection")
|
||||
|
||||
dataset = Dataset.from_list(rows)
|
||||
if args.push:
|
||||
dataset.push_to_hub(args.push)
|
||||
print(f"export-sft: pushed to {args.push}")
|
||||
return
|
||||
out = args.output_dir or args.run_dir / "sft"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
dataset.to_parquet(str(out / "train.parquet"))
|
||||
print(f"export-sft: wrote {out / 'train.parquet'} -> train with --data.name {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+60
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the ModelExpress metadata server and Redis backend used by SLURM RL jobs.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
MODELEXPRESS_REPOSITORY="https://github.com/ai-dynamo/modelexpress.git"
|
||||
MODELEXPRESS_REF="v0.3.0"
|
||||
REDIS_VERSION="7.4.2"
|
||||
REDIS_SHA256="4ddebbf09061cbb589011786febdb34f29767dd7f89dbe712d2b68e808af6a1f"
|
||||
|
||||
if [[ $# -gt 0 ]]; then
|
||||
echo "This installer does not accept arguments" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BIN_DIR="$PROJECT_DIR/third_party/modelexpress/bin"
|
||||
mkdir -p "$BIN_DIR"
|
||||
|
||||
if [[ -x "$BIN_DIR/modelexpress-server" ]] \
|
||||
&& "$BIN_DIR/modelexpress-server" --version 2>/dev/null | grep -q "${MODELEXPRESS_REF#v}"; then
|
||||
echo "modelexpress-server $MODELEXPRESS_REF already installed at $BIN_DIR"
|
||||
else
|
||||
command -v cargo >/dev/null || {
|
||||
echo "cargo not found; install Rust 1.90 or newer before running this script" >&2
|
||||
exit 1
|
||||
}
|
||||
command -v protoc >/dev/null || {
|
||||
echo "protoc not found; install Protocol Buffers before running this script" >&2
|
||||
exit 1
|
||||
}
|
||||
BUILD_DIR=$(mktemp -d)
|
||||
trap 'rm -rf "$BUILD_DIR"' EXIT
|
||||
git clone --depth 1 --branch "$MODELEXPRESS_REF" "$MODELEXPRESS_REPOSITORY" "$BUILD_DIR/modelexpress"
|
||||
(
|
||||
cd "$BUILD_DIR/modelexpress"
|
||||
cargo build --release --bin modelexpress-server
|
||||
)
|
||||
cp "$BUILD_DIR/modelexpress/target/release/modelexpress-server" "$BIN_DIR/"
|
||||
fi
|
||||
|
||||
if [[ -x "$BIN_DIR/redis-server" ]] \
|
||||
&& "$BIN_DIR/redis-server" --version | grep -q "v=$REDIS_VERSION"; then
|
||||
echo "redis-server $REDIS_VERSION already installed at $BIN_DIR"
|
||||
else
|
||||
BUILD_DIR="${BUILD_DIR:-$(mktemp -d)}"
|
||||
trap 'rm -rf "$BUILD_DIR"' EXIT
|
||||
REDIS_ARCHIVE="$BUILD_DIR/redis-${REDIS_VERSION}.tar.gz"
|
||||
curl --fail --location --silent --show-error \
|
||||
--output "$REDIS_ARCHIVE" \
|
||||
"https://download.redis.io/releases/redis-${REDIS_VERSION}.tar.gz"
|
||||
echo "$REDIS_SHA256 $REDIS_ARCHIVE" | sha256sum --check
|
||||
tar -xzf "$REDIS_ARCHIVE" -C "$BUILD_DIR"
|
||||
make -C "$BUILD_DIR/redis-${REDIS_VERSION}" -j redis-server MALLOC=libc
|
||||
cp "$BUILD_DIR/redis-${REDIS_VERSION}/src/redis-server" "$BIN_DIR/"
|
||||
fi
|
||||
|
||||
echo "Installed ModelExpress server dependencies in $BIN_DIR"
|
||||
@@ -25,9 +25,13 @@ Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max
|
||||
|
||||
```bash
|
||||
uv run rl --help # all fields and defaults
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved configs (JSON) to /tmp/x/check/configs
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved JSON to /tmp/x/check/configs/latest
|
||||
```
|
||||
|
||||
Each attempt also writes `configs/attempt_<n>/command.txt`. It records the
|
||||
shell-safe launch command, including CLI overrides. `configs/latest` points to
|
||||
the current attempt.
|
||||
|
||||
## Validators
|
||||
|
||||
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, remove the old spelling: no `validation_alias`, no auto-translating `mode="before"` validator. The old key then fails as an unknown key, which is the signal. An alias that stays forever is worse than a break — it never gets retired, and a key whose *meaning* changed silently misconfigures the run.
|
||||
@@ -69,6 +73,8 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
|
||||
|
||||
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
|
||||
|
||||
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
|
||||
|
||||
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
|
||||
|
||||
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
|
||||
|
||||
@@ -11,6 +11,10 @@ dirs — safe against live runs — and installs anywhere (cluster head node,
|
||||
laptop against a mounted outputs dir): GPU dependencies live behind the
|
||||
`gpu` extra.
|
||||
|
||||
The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
|
||||
to inspect the immutable config or log files from an earlier launch. The Config
|
||||
view shows a copyable launch command above the launch TOML or resolved JSON.
|
||||
|
||||
Every dashboard instance serves the dirs it was started with **plus** every dir
|
||||
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
|
||||
live). Launchers (`rl`, `sft`) register their output dir on every
|
||||
|
||||
@@ -9,7 +9,7 @@ description: Monitor an ongoing prime-rl training run — find the output direct
|
||||
|
||||
### On launch
|
||||
|
||||
1. Find the run dir and read the resolved configs at `{run_dir}/configs/resolved/` (start with `rl.json`, or `orchestrator.json` on local runs). The launch TOML is copied verbatim to `{run_dir}/configs/rl.toml`. The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
|
||||
1. Find the run dir and read the resolved configs at `{run_dir}/configs/latest/resolved/` (start with `rl.json`, or `orchestrator.json` on local runs). Read the launch command from `{run_dir}/configs/latest/command.txt`. The launch TOML is copied verbatim to `{run_dir}/configs/latest/rl.toml`. The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
|
||||
2. Confirm all processes are alive and the run is making progress.
|
||||
3. Write the initial summary into `{run_dir}/STATUS.md`.
|
||||
|
||||
@@ -48,7 +48,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
|
||||
|
||||
### Where to find things
|
||||
|
||||
- `{run_dir}/configs/` — the launch TOML copied verbatim (`rl.toml`/`sft.toml`), plus `resolved/` with the per-component resolved configs, written as JSON so explicit None settings round-trip.
|
||||
- `{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).
|
||||
|
||||
@@ -56,7 +56,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
|
||||
|
||||
`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`), the resolved config
|
||||
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.
|
||||
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
|
||||
@@ -82,7 +82,7 @@ Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`
|
||||
{run_dir}/logs/latest/
|
||||
├── trainer.log # rank 0 stdout
|
||||
├── orchestrator.log # orchestrator stdout
|
||||
├── evals.log # SFT online-eval evals stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evals.log)
|
||||
├── evals.log # SFT online-eval evals stdout
|
||||
├── inference.log # vLLM stdout
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
@@ -135,7 +135,7 @@ All metrics print to the console log (and W&B when configured).
|
||||
|--------|-------------|
|
||||
| `mismatch_kl/{all,env}/{mean,std,max}` | KL between trainer and (old) inference policy over trainable tokens |
|
||||
| `entropy/{all,env}/{mean,std,max}` | policy entropy over trainable tokens |
|
||||
| `masked_advantage_{positive,negative}/mean` | fraction of DPPO-masked tokens with +/- advantage |
|
||||
| `is_masked/mean` | fraction of tokens masked by the IPO trust region |
|
||||
| `optim/grad_norm` | spikes may precede divergence |
|
||||
|
||||
**Performance** — trainer and orchestrator step independently, so comparing step times shows who's waiting on whom.
|
||||
|
||||
@@ -7,7 +7,7 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
|
||||
|
||||
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
|
||||
|
||||
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory.
|
||||
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory. Every launch writes configs and `command.txt` under `configs/attempt_<n>/`. `configs/latest` points to the current attempt. The command uses shell-safe quoting.
|
||||
|
||||
## Run directories
|
||||
|
||||
@@ -46,6 +46,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
|
||||
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`.
|
||||
- NIXL on SLURM: install NIXL and ModelExpress with the provided scripts. The job starts ModelExpress and Redis unless `slurm.launch_modelexpress = false`.
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
|
||||
@@ -69,6 +70,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
|
||||
- Config: `SFTConfig` (`packages/prime-rl-configs/src/prime_rl/configs/sft.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/sft.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Multi-node online evals use one SLURM job with `num_train_nodes + num_infer_nodes` nodes. The generated `launcher/sft.sbatch` assigns inference nodes first, then trainer nodes.
|
||||
|
||||
## `inference` — vLLM server
|
||||
|
||||
@@ -95,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. 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. 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,14 +124,14 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
|
||||
- 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`.
|
||||
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
|
||||
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
|
||||
|
||||
## Exporting checkpoints
|
||||
|
||||
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
|
||||
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/latest/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
|
||||
|
||||
## Summary
|
||||
|
||||
|
||||
@@ -3,12 +3,18 @@
|
||||
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
|
||||
directories (metrics, resolved configs, rollout traces, cited reports,
|
||||
component logs) at
|
||||
http://localhost:7788. Needs the `dashboard` extra. Every instance also serves
|
||||
http://localhost:7788. The trace viewer includes transcript and synchronized
|
||||
agent timeline views; timeline activities open the corresponding transcript
|
||||
call. Needs the `dashboard` extra. Every instance also serves
|
||||
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
|
||||
(one dashboard per host per user); `--isolated` serves only the given dirs and
|
||||
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
|
||||
kill/restart commands, and the local view-command/report contract.
|
||||
|
||||
The Config and Logs views keep each launch attempt available. The Config view
|
||||
shows a copyable command above the launch TOML or resolved JSON. Both views
|
||||
open at `latest (attempt <n>)` and let you select an earlier attempt.
|
||||
|
||||
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
|
||||
cluster head node, a laptop against a mounted outputs dir:
|
||||
|
||||
|
||||
@@ -208,10 +208,27 @@ def model_name(config: dict) -> str | None:
|
||||
return model if isinstance(model, str) else (model or {}).get("name")
|
||||
|
||||
|
||||
def resolved_config_dir(run_dir: Path) -> Path:
|
||||
"""Where the resolved JSON dumps live: `configs/resolved/`, or `configs/` on
|
||||
runs from before the launch-TOML split."""
|
||||
def config_attempt_numbers(run_dir: Path) -> list[int]:
|
||||
return [n for n, _ in numbered_dirs(run_dir / "configs", "attempt_")]
|
||||
|
||||
|
||||
def config_attempt_dir(run_dir: Path, attempt: str = "latest") -> tuple[Path, int | None]:
|
||||
"""Return one config attempt root, with a fallback for legacy run layouts."""
|
||||
configs = run_dir / "configs"
|
||||
attempts = config_attempt_numbers(run_dir)
|
||||
if not attempts:
|
||||
return configs, None
|
||||
if attempt == "latest":
|
||||
latest = (configs / "latest").resolve()
|
||||
attempt_num = int(latest.name.removeprefix("attempt_")) if latest.is_dir() else attempts[-1]
|
||||
else:
|
||||
attempt_num = int(attempt)
|
||||
return configs / f"attempt_{attempt_num}", attempt_num
|
||||
|
||||
|
||||
def resolved_config_dir(run_dir: Path, attempt: str = "latest") -> Path:
|
||||
"""Return resolved JSON dumps for one attempt or a legacy run."""
|
||||
configs, _ = config_attempt_dir(run_dir, attempt)
|
||||
resolved = configs / "resolved"
|
||||
return resolved if resolved.is_dir() else configs
|
||||
|
||||
@@ -278,6 +295,7 @@ def run_meta(run_dir: Path) -> dict:
|
||||
"type": run_type,
|
||||
"model": model_name(config),
|
||||
"dataset": (config.get("data") or {}).get("name"),
|
||||
"has_validation": run_type == "sft" and config.get("val") is not None,
|
||||
"env": ((config.get("env") or {}).get("taskset") or {}).get("id"),
|
||||
"total_episodes": (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None,
|
||||
"max_steps": config.get("max_steps"),
|
||||
@@ -365,7 +383,7 @@ def list_logfiles(run: str, attempt: str = "latest") -> dict:
|
||||
for path in sorted(attempt_dir.rglob("*.log")):
|
||||
component, label = log_component(path.relative_to(attempt_dir))
|
||||
add(path, component, label)
|
||||
# The evals process writes its env-server logs outside attempt_N (logs/envs/eval/*.log).
|
||||
# Include unscoped env logs from runs created before attempt-scoped eval logging.
|
||||
for path in sorted((run_dir / "logs" / "envs").rglob("*.log")):
|
||||
add(path, f"env:{path.stem}", f"{path.stem} (evals)")
|
||||
return {"attempt": attempt_num, "attempts": attempts, "files": files}
|
||||
@@ -407,26 +425,29 @@ def config_rank(name: str) -> tuple[int, str]:
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/configs")
|
||||
def list_configs(run: str) -> dict:
|
||||
def list_configs(run: str, attempt: str = "latest") -> dict:
|
||||
"""Two views of a run's config: each launch TOML (verbatim, as the run was
|
||||
started) and one "resolved" document concatenating every resolved JSON dump."""
|
||||
run_dir = get_run_dir(run)
|
||||
configs_dir = run_dir / "configs"
|
||||
configs_dir, attempt_num = config_attempt_dir(run_dir, attempt)
|
||||
files = sorted((p.name for p in configs_dir.glob("*.toml")), key=config_rank) if configs_dir.is_dir() else []
|
||||
if any(resolved_config_dir(run_dir).rglob("*.json")):
|
||||
if any(resolved_config_dir(run_dir, attempt).rglob("*.json")):
|
||||
files.append("resolved")
|
||||
return {"files": files}
|
||||
if (configs_dir / "command.txt").is_file():
|
||||
files.append("command.txt")
|
||||
return {"attempt": attempt_num, "attempts": config_attempt_numbers(run_dir), "files": files}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/config")
|
||||
def read_config(run: str, file: str) -> dict:
|
||||
def read_config(run: str, file: str, attempt: str = "latest") -> dict:
|
||||
run_dir = get_run_dir(run)
|
||||
if file == "resolved":
|
||||
base = resolved_config_dir(run_dir)
|
||||
base = resolved_config_dir(run_dir, attempt)
|
||||
names = sorted((str(p.relative_to(base).with_suffix("")) for p in base.rglob("*.json")), key=config_rank)
|
||||
doc = {name: read_json(base / f"{name}.json") for name in names}
|
||||
return {"file": file, "content": orjson.dumps(doc).decode()}
|
||||
path = safe_child(run_dir / "configs", file, suffix=".toml")
|
||||
configs_dir, _ = config_attempt_dir(run_dir, attempt)
|
||||
path = safe_child(configs_dir, file, suffix=".txt" if file == "command.txt" else ".toml")
|
||||
return {"file": file, "content": path.read_text()}
|
||||
|
||||
|
||||
@@ -781,6 +802,306 @@ def traces_path(run: str, step: int, kind: str, subset: str) -> Path:
|
||||
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())
|
||||
|
||||
|
||||
def message_text(message: dict) -> str:
|
||||
content = message.get("content")
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
return "".join(part.get("text", "") if isinstance(part, dict) else str(part) for part in content)
|
||||
return "" if content is None else str(content)
|
||||
|
||||
|
||||
def timeline_status(trace: dict) -> str:
|
||||
if not trace.get("is_completed"):
|
||||
return "running"
|
||||
if not trace.get("ok") and (trace.get("errors") or trace.get("stop_condition") == "error"):
|
||||
return "failed"
|
||||
return "completed"
|
||||
|
||||
|
||||
def timeline_reward(trace: dict) -> float | None:
|
||||
rewards = [reward for reward in (trace.get("rewards") or {}).values() if isinstance(reward, dict)]
|
||||
if not rewards:
|
||||
return None
|
||||
return sum(
|
||||
(reward.get("score") or 0) * (reward.get("weight") if reward.get("weight") is not None else 1)
|
||||
for reward in rewards
|
||||
)
|
||||
|
||||
|
||||
def trace_branch_paths(nodes: list[dict]) -> list[list[int]]:
|
||||
"""Return VF-native root-to-leaf branches in leaf-index 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 = []
|
||||
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
|
||||
|
||||
|
||||
def token_usage(usage: dict) -> tuple[int | None, int | None, int | None]:
|
||||
prompt_tokens = usage.get("prompt_tokens")
|
||||
output_tokens = usage.get("completion_tokens")
|
||||
if "cached_input_tokens" in usage:
|
||||
return prompt_tokens, usage.get("cached_input_tokens"), output_tokens
|
||||
cached_tokens = (usage.get("prompt_tokens_details") or {}).get("cached_tokens")
|
||||
input_tokens = (
|
||||
max(0, prompt_tokens - cached_tokens) if prompt_tokens is not None and cached_tokens else prompt_tokens
|
||||
)
|
||||
return input_tokens, cached_tokens, output_tokens
|
||||
|
||||
|
||||
def activity_spans(
|
||||
trace: dict,
|
||||
node_indexes: set[int],
|
||||
*,
|
||||
include_unlinked: bool = False,
|
||||
shared_node_indexes: set[int] | None = None,
|
||||
) -> list[dict]:
|
||||
nodes = trace.get("nodes") or []
|
||||
spans = []
|
||||
for call_index, call in enumerate(trace.get("calls") or []):
|
||||
node_index = call.get("node")
|
||||
if node_index is None:
|
||||
if not include_unlinked:
|
||||
continue
|
||||
node = {}
|
||||
elif node_index not in node_indexes:
|
||||
continue
|
||||
else:
|
||||
node = nodes[node_index]
|
||||
call_time = call.get("time") or {}
|
||||
started = call_time.get("start")
|
||||
ended = call_time.get("end")
|
||||
usage = call.get("usage") or {}
|
||||
input_tokens, cached_tokens, output_tokens = token_usage(usage)
|
||||
reasoning_tokens = usage.get("reasoning_tokens")
|
||||
if reasoning_tokens is None:
|
||||
reasoning_tokens = (usage.get("completion_tokens_details") or {}).get("reasoning_tokens")
|
||||
text = " ".join(message_text(node.get("message") or {}).split())
|
||||
spans.append(
|
||||
{
|
||||
"kind": "model_call",
|
||||
"label": f"turn {len(spans) + 1}",
|
||||
"track": "activity",
|
||||
"call_index": call_index,
|
||||
"node_index": node_index,
|
||||
"shared": node_index in shared_node_indexes if shared_node_indexes is not None else False,
|
||||
"started_at": started,
|
||||
"ended_at": ended,
|
||||
"status": "completed" if ended is not None or trace.get("is_completed") else "running",
|
||||
"snippet": text[:240],
|
||||
"input_tokens": input_tokens,
|
||||
"cached_tokens": cached_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"cost": usage.get("cost"),
|
||||
}
|
||||
)
|
||||
return sorted(spans, key=lambda span: span["started_at"] if span["started_at"] is not None else float("inf"))
|
||||
|
||||
|
||||
def lifecycle_spans(trace: dict) -> list[dict]:
|
||||
timing = trace.get("timing") or {}
|
||||
spans = []
|
||||
for kind, label in (
|
||||
("boot", "boot"),
|
||||
("setup", "setup"),
|
||||
("agent", "agent"),
|
||||
("finalize", "finalize"),
|
||||
("scoring", "scoring"),
|
||||
):
|
||||
span = timing.get(kind) or {}
|
||||
if not span.get("start"):
|
||||
continue
|
||||
spans.append(
|
||||
{
|
||||
"kind": kind,
|
||||
"label": label,
|
||||
"track": "lifecycle",
|
||||
"started_at": span["start"],
|
||||
"ended_at": span.get("end") or None,
|
||||
"status": "completed" if span.get("end") or trace.get("is_completed") else "running",
|
||||
}
|
||||
)
|
||||
return spans
|
||||
|
||||
|
||||
def timeline_lane(
|
||||
trace: dict,
|
||||
trace_index: int,
|
||||
*,
|
||||
label: str,
|
||||
depth: int,
|
||||
branch: bool,
|
||||
lifecycle: list[dict],
|
||||
activities: list[dict],
|
||||
started_at: float | None = None,
|
||||
) -> dict:
|
||||
spans = lifecycle + activities
|
||||
starts = [span["started_at"] for span in spans if span.get("started_at") is not None]
|
||||
ends = [span["ended_at"] for span in spans if span.get("ended_at") is not None]
|
||||
started = started_at if started_at is not None else min(starts or ends, default=None)
|
||||
status = (
|
||||
("completed" if all(span["status"] == "completed" for span in lifecycle + activities) else "running")
|
||||
if branch
|
||||
else timeline_status(trace)
|
||||
)
|
||||
ended = max(ends, default=None) if status != "running" else None
|
||||
agent = trace.get("agent") or {}
|
||||
config = agent.get("config") or {}
|
||||
client = config.get("client") or {}
|
||||
|
||||
def total(field: str) -> int | float | None:
|
||||
values = [span[field] for span in activities if isinstance(span.get(field), (int, float))]
|
||||
return sum(values) if values else None
|
||||
|
||||
input_tokens = total("input_tokens")
|
||||
cached_tokens = total("cached_tokens")
|
||||
output_tokens = total("output_tokens")
|
||||
reasoning_tokens = total("reasoning_tokens")
|
||||
total_input_tokens = input_tokens + (cached_tokens or 0) if input_tokens is not None else None
|
||||
total_tokens = (
|
||||
total_input_tokens + output_tokens if total_input_tokens is not None and output_tokens is not None else None
|
||||
)
|
||||
context_lengths = [
|
||||
(span.get("input_tokens") or 0) + (span.get("cached_tokens") or 0)
|
||||
for span in activities
|
||||
if span.get("input_tokens") is not None
|
||||
]
|
||||
return {
|
||||
"trace_index": trace_index,
|
||||
"label": label,
|
||||
"model": config.get("model") or client.get("renderer_model_name") or "",
|
||||
"depth": depth,
|
||||
"started_at": started,
|
||||
"ended_at": ended,
|
||||
"status": status,
|
||||
"outcome": status if branch else (trace.get("stop_condition") or status),
|
||||
"reward": timeline_reward(trace),
|
||||
"usage": {
|
||||
"model_calls": len(activities),
|
||||
"input_tokens": input_tokens,
|
||||
"cached_tokens": cached_tokens,
|
||||
"total_input_tokens": total_input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"max_context_tokens": max(context_lengths, default=None),
|
||||
"total_tokens": total_tokens,
|
||||
"cost": total("cost"),
|
||||
},
|
||||
"spans": spans,
|
||||
}
|
||||
|
||||
|
||||
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)
|
||||
node_branch_counts: dict[int, int] = {}
|
||||
for path in branch_paths:
|
||||
for node_index in path:
|
||||
node_branch_counts[node_index] = node_branch_counts.get(node_index, 0) + 1
|
||||
role = (trace.get("agent") or {}).get("name") or "agent"
|
||||
parent = timeline_lane(
|
||||
trace,
|
||||
trace_index,
|
||||
label=role,
|
||||
depth=0,
|
||||
branch=False,
|
||||
lifecycle=lifecycle_spans(trace),
|
||||
activities=activity_spans(trace, set(), include_unlinked=True),
|
||||
started_at=(trace.get("timing") or {}).get("start"),
|
||||
)
|
||||
branches = []
|
||||
for branch_index, path in enumerate(branch_paths):
|
||||
node_indexes = set(path)
|
||||
shared_node_indexes = {node_index for node_index in path if node_branch_counts.get(node_index, 0) > 1}
|
||||
unique_node_indexes = node_indexes - shared_node_indexes
|
||||
activities = activity_spans(
|
||||
trace,
|
||||
node_indexes,
|
||||
shared_node_indexes=shared_node_indexes,
|
||||
)
|
||||
path_timestamps = [
|
||||
nodes[node_index].get("timestamp")
|
||||
for node_index in path
|
||||
if nodes[node_index].get("timestamp") is not None
|
||||
]
|
||||
unique_timestamps = [
|
||||
nodes[node_index].get("timestamp")
|
||||
for node_index in unique_node_indexes
|
||||
if nodes[node_index].get("timestamp") is not None
|
||||
]
|
||||
activity_starts = [span["started_at"] for span in activities if span["started_at"] is not None]
|
||||
unique_activity_starts = [
|
||||
span["started_at"] for span in activities if not span["shared"] and span["started_at"] is not None
|
||||
]
|
||||
branch_start = min(activity_starts or path_timestamps, default=None)
|
||||
sort_start = min(
|
||||
unique_activity_starts or unique_timestamps or activity_starts or path_timestamps, default=None
|
||||
)
|
||||
branch_end = max(
|
||||
[span["ended_at"] for span in activities if span.get("ended_at") is not None] + path_timestamps,
|
||||
default=None,
|
||||
)
|
||||
branch_completed = bool(trace.get("is_completed"))
|
||||
label = f"branch {branch_index}"
|
||||
branch_lifecycle = (
|
||||
[
|
||||
{
|
||||
"kind": "agent",
|
||||
"label": label,
|
||||
"track": "lifecycle",
|
||||
"started_at": branch_start,
|
||||
"ended_at": branch_end if branch_completed else None,
|
||||
"status": "completed" if branch_completed else "running",
|
||||
"node_index": path[-1],
|
||||
}
|
||||
]
|
||||
if branch_start is not None
|
||||
else []
|
||||
)
|
||||
branches.append(
|
||||
(
|
||||
sort_start,
|
||||
branch_index,
|
||||
timeline_lane(
|
||||
trace,
|
||||
trace_index,
|
||||
label=label,
|
||||
depth=1,
|
||||
branch=True,
|
||||
lifecycle=branch_lifecycle,
|
||||
activities=activities,
|
||||
),
|
||||
)
|
||||
)
|
||||
branches.sort(key=lambda item: (item[0] if item[0] is not None else float("inf"), item[1]))
|
||||
lane_groups.append((parent, [lane for _, _, lane in branches]))
|
||||
lane_groups.sort(key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf"))
|
||||
lanes = [lane for parent, children in lane_groups for lane in (parent, *children)]
|
||||
return {"lanes": lanes}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts")
|
||||
def list_rollouts(run: str) -> dict:
|
||||
return {"steps": rollout_steps(get_run_dir(run))}
|
||||
@@ -1147,6 +1468,11 @@ 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))
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------- static
|
||||
|
||||
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
|
||||
@@ -31,7 +31,10 @@ const state = {
|
||||
paneOrder: prefs.paneOrder ?? {},
|
||||
},
|
||||
compare: { runs: [], data: new Map() },
|
||||
config: { loaded: false, files: [], file: null, fmt: "toml", cache: new Map() },
|
||||
config: {
|
||||
loaded: false, attempt: "latest", latestAttempt: null, attempts: [],
|
||||
files: [], file: null, fmt: "toml", commandText: "", cache: new Map(),
|
||||
},
|
||||
logs: {
|
||||
loaded: false, attempt: "latest", attempts: [], files: [], paneFile: {},
|
||||
components: prefs.logComponents ? new Set(prefs.logComponents) : null,
|
||||
@@ -188,8 +191,14 @@ async function selectRun(name, deferTab = false) {
|
||||
evalEtag: null, evalCount: 0, evalCost: null,
|
||||
};
|
||||
if (state.meta?.type === "eval") fetchEvalSeries(); // populates the overview cost early
|
||||
state.config = { loaded: false, files: [], file: null, fmt: state.config.fmt, cache: new Map() };
|
||||
state.logs = { ...state.logs, loaded: false, attempt: "latest", files: [], paneFile: {}, maximized: null, buffers: new Map() };
|
||||
state.config = {
|
||||
loaded: false, attempt: "latest", latestAttempt: null, attempts: [],
|
||||
files: [], file: null, fmt: state.config.fmt, commandText: "", cache: new Map(),
|
||||
};
|
||||
state.logs = {
|
||||
...state.logs, loaded: false, attempt: "latest", latestAttempt: null,
|
||||
files: [], paneFile: {}, maximized: null, buffers: new Map(),
|
||||
};
|
||||
state.traces = {
|
||||
...state.traces,
|
||||
loaded: false, fetching: false, steps: [], step: null, env: "", episodes: [], etag: null,
|
||||
@@ -567,6 +576,7 @@ function buildSections(meta) {
|
||||
{ regex: `eval/${envPattern}/effective/[^/]+/avg@.*` },
|
||||
{ regex: `eval/${envPattern}/effective/[^/]+/reward/mean`, split: true },
|
||||
{ regex: `eval/${envPattern}/all/[^/]+/reward/mean`, split: true },
|
||||
{ regex: `eval/${envPattern}/all/cancelled/mean` },
|
||||
...COMMON_METRICS.map((m) => ({ regex: `eval/${envPattern}/${m}` })),
|
||||
...COMMON_REGEXES.map((r) => ({ regex: `eval/${envPattern}/${r}` })),
|
||||
],
|
||||
@@ -574,7 +584,10 @@ function buildSections(meta) {
|
||||
const sections = [];
|
||||
const evalEnvs = meta.eval_envs || [];
|
||||
if (meta.type === "sft") {
|
||||
sections.push({ name: "train", panels: SFT_TRAIN_METRICS.map((m) => ({ metric: m })) });
|
||||
const trainMetrics = meta.has_validation
|
||||
? SFT_TRAIN_METRICS
|
||||
: SFT_TRAIN_METRICS.filter((m) => !m.startsWith("val/"));
|
||||
sections.push({ name: "train", panels: trainMetrics.map((m) => ({ metric: m })) });
|
||||
if (evalEnvs.length) sections.push(...evalEnvs.map((e) => evalSection(`eval/${e}`, escRe(e), true)));
|
||||
else sections.push(evalSection("eval", ".*"));
|
||||
sections.push({ name: "stability", panels: SFT_STABILITY_METRICS.map((m) => ({ metric: m })) });
|
||||
@@ -681,6 +694,15 @@ function groupColors(groups) {
|
||||
return groups.length > 1 ? groups.map((_, i) => PALETTE[i % PALETTE.length]) : [SINGLE_SERIES];
|
||||
}
|
||||
|
||||
function singletonPoints(series, color) {
|
||||
return {
|
||||
show: () => series.points.size === 1,
|
||||
size: 6,
|
||||
width: 0,
|
||||
fill: color,
|
||||
};
|
||||
}
|
||||
|
||||
/* flatten groups into uPlot series defs + data columns + tooltip meta */
|
||||
function buildChartLayout(entry, timeAxis) {
|
||||
const groups = panelGroups(entry.series);
|
||||
@@ -705,7 +727,7 @@ function buildChartLayout(entry, timeAxis) {
|
||||
width: 1.25,
|
||||
dash: si > 0 ? [6, 4] : undefined,
|
||||
spanGaps: true,
|
||||
points: { show: false },
|
||||
points: singletonPoints(strand.main, color),
|
||||
});
|
||||
const m = { label: labels[mainIdx] || "value", stat: statOf(strand.main.key) ?? "value", color, dataIdx: cols.length };
|
||||
meta.push(m);
|
||||
@@ -714,7 +736,14 @@ function buildChartLayout(entry, timeAxis) {
|
||||
const bandIdx = {};
|
||||
for (const s of aux) {
|
||||
cols.push({ s, role: "aux" });
|
||||
uSeries.push({ stroke: hexToRgba(color, 0.55), width: 1, dash: [3, 3], spanGaps: true, points: { show: false } });
|
||||
const auxColor = hexToRgba(color, 0.55);
|
||||
uSeries.push({
|
||||
stroke: auxColor,
|
||||
width: 1,
|
||||
dash: [3, 3],
|
||||
spanGaps: true,
|
||||
points: singletonPoints(s, auxColor),
|
||||
});
|
||||
if (s === strand.lo) bandIdx.lo = cols.length;
|
||||
if (s === strand.hi) bandIdx.hi = cols.length;
|
||||
}
|
||||
@@ -1198,19 +1227,23 @@ async function initMetrics() {
|
||||
/* ----------------------------------------------------------------- config */
|
||||
|
||||
|
||||
/* both views are fetched once per run, so the TOML/JSON toggle never waits on
|
||||
the network */
|
||||
/* config artifacts are fetched once per attempt, so format changes never wait
|
||||
on the network */
|
||||
async function fetchConfigText(file) {
|
||||
const cache = state.config.cache;
|
||||
if (cache.has(file)) return cache.get(file);
|
||||
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/config?file=${encodeURIComponent(file)}`);
|
||||
const key = `${state.config.attempt}:${file}`;
|
||||
if (cache.has(key)) return cache.get(key);
|
||||
const data = await api(
|
||||
`/api/runs/${encodeURIComponent(state.run)}/config?file=${encodeURIComponent(file)}` +
|
||||
`&attempt=${encodeURIComponent(state.config.attempt)}`
|
||||
);
|
||||
let text = data.content;
|
||||
try {
|
||||
text = JSON.stringify(JSON.parse(text), null, 2);
|
||||
} catch {
|
||||
/* show raw content if not valid JSON */
|
||||
}
|
||||
cache.set(file, text);
|
||||
cache.set(key, text);
|
||||
return text;
|
||||
}
|
||||
|
||||
@@ -1325,6 +1358,10 @@ function applyConfigSearch() {
|
||||
} catch {
|
||||
re = new RegExp(escRe(query), "gi");
|
||||
}
|
||||
const test = (line) => {
|
||||
re.lastIndex = 0;
|
||||
return re.test(line);
|
||||
};
|
||||
const noHits = () => {
|
||||
view.innerHTML = emptyState("no hits", "nothing in this config matches the filter");
|
||||
hitsEl.textContent = "no hits";
|
||||
@@ -1337,10 +1374,6 @@ function applyConfigSearch() {
|
||||
// TOML (launch config): a matching line keeps itself (plus its [section]
|
||||
// header for context); a matching [section] header keeps the whole section
|
||||
const lines = (state.config.text ?? "").split("\n");
|
||||
const test = (line) => {
|
||||
re.lastIndex = 0;
|
||||
return re.test(line);
|
||||
};
|
||||
const kept = [];
|
||||
let header = null;
|
||||
let headerKept = false;
|
||||
@@ -1399,10 +1432,12 @@ function applyConfigSearch() {
|
||||
view.querySelector("mark.hit")?.scrollIntoView({ block: "center" });
|
||||
}
|
||||
|
||||
/* TOML = the launch config as it was passed, JSON = the concatenated resolved dumps */
|
||||
/* TOML = launch config, JSON = resolved dumps */
|
||||
function configFileFor(fmt) {
|
||||
const files = state.config.files || [];
|
||||
return fmt === "toml" ? files.find((f) => f.endsWith(".toml")) : files.find((f) => f === "resolved");
|
||||
if (fmt === "toml") return files.find((f) => f.endsWith(".toml"));
|
||||
if (fmt === "json") return files.find((f) => f === "resolved");
|
||||
return files.find((f) => f === "command.txt");
|
||||
}
|
||||
|
||||
function renderConfigFormat() {
|
||||
@@ -1412,21 +1447,55 @@ function renderConfigFormat() {
|
||||
}
|
||||
}
|
||||
|
||||
async function initConfig() {
|
||||
state.config.loaded = true;
|
||||
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/configs`);
|
||||
function renderConfigAttempts() {
|
||||
const config = state.config;
|
||||
const latest = config.latestAttempt == null ? "latest" : `latest (attempt ${config.latestAttempt})`;
|
||||
$("#config-attempt-select").innerHTML =
|
||||
`<option value="latest" ${config.attempt === "latest" ? "selected" : ""}>${latest}</option>` +
|
||||
config.attempts
|
||||
.map((a) => `<option value="${a}" ${String(a) === String(config.attempt) ? "selected" : ""}>attempt ${a}</option>`)
|
||||
.join("");
|
||||
syncDressedSelects();
|
||||
}
|
||||
|
||||
function renderConfigCommand() {
|
||||
const command = state.config.commandText.trimEnd();
|
||||
$("#config-command").classList.toggle("empty", !command);
|
||||
$("#config-command-text").textContent = command || "command unavailable for this attempt";
|
||||
$("#config-command-copy").disabled = !command;
|
||||
}
|
||||
|
||||
async function loadConfigAttempt() {
|
||||
const data = await api(
|
||||
`/api/runs/${encodeURIComponent(state.run)}/configs?attempt=${encodeURIComponent(state.config.attempt)}`
|
||||
);
|
||||
state.config.latestAttempt = state.config.attempt === "latest" ? data.attempt : state.config.latestAttempt;
|
||||
state.config.attempts = data.attempts;
|
||||
state.config.files = data.files;
|
||||
if (!data.files.length) {
|
||||
renderConfigAttempts();
|
||||
const commandFile = configFileFor("command");
|
||||
state.config.commandText = commandFile ? await fetchConfigText(commandFile) : "";
|
||||
renderConfigCommand();
|
||||
if (!configFileFor("toml") && !configFileFor("json")) {
|
||||
renderConfigFormat();
|
||||
$("#config-view").innerHTML = emptyState("no configs", "this run has no configs/ directory");
|
||||
$("#config-view").innerHTML = emptyState("no configs", "this attempt has no config files");
|
||||
return;
|
||||
}
|
||||
if (!configFileFor(state.config.fmt)) state.config.fmt = configFileFor("toml") ? "toml" : "json";
|
||||
if (!configFileFor(state.config.fmt)) {
|
||||
state.config.fmt = ["toml", "json"].find((fmt) => configFileFor(fmt));
|
||||
}
|
||||
state.config.file = configFileFor(state.config.fmt);
|
||||
renderConfigFormat();
|
||||
await loadConfig();
|
||||
const other = configFileFor(state.config.fmt === "toml" ? "json" : "toml");
|
||||
if (other) fetchConfigText(other); // warm the other side of the toggle
|
||||
for (const fmt of ["toml", "json"]) {
|
||||
const file = configFileFor(fmt);
|
||||
if (file && file !== state.config.file) fetchConfigText(file);
|
||||
}
|
||||
}
|
||||
|
||||
async function initConfig() {
|
||||
state.config.loaded = true;
|
||||
await loadConfigAttempt();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- logs */
|
||||
@@ -1559,9 +1628,12 @@ function dressLogPaneSelects() {
|
||||
|
||||
function renderLogPanes() {
|
||||
const logs = state.logs;
|
||||
$("#attempt-select").innerHTML = logs.attempts
|
||||
.map((a) => `<option value="${a}" ${String(a) === String(logs.attempt) ? "selected" : ""}>attempt ${a}</option>`)
|
||||
.join("");
|
||||
const latest = logs.latestAttempt == null ? "latest" : `latest (attempt ${logs.latestAttempt})`;
|
||||
$("#attempt-select").innerHTML =
|
||||
`<option value="latest" ${logs.attempt === "latest" ? "selected" : ""}>${latest}</option>` +
|
||||
logs.attempts
|
||||
.map((a) => `<option value="${a}" ${String(a) === String(logs.attempt) ? "selected" : ""}>attempt ${a}</option>`)
|
||||
.join("");
|
||||
renderLogCompMenu();
|
||||
const container = $("#log-panes");
|
||||
container.innerHTML = "";
|
||||
@@ -1736,7 +1808,7 @@ async function loadLogfiles() {
|
||||
const logs = state.logs;
|
||||
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/logfiles?attempt=${logs.attempt}`);
|
||||
logs.attempts = data.attempts;
|
||||
logs.attempt = data.attempt;
|
||||
if (logs.attempt === "latest") logs.latestAttempt = data.attempt;
|
||||
logs.files = data.files;
|
||||
renderLogPanes();
|
||||
dressLogPaneSelects();
|
||||
@@ -1962,6 +2034,10 @@ let currentTraceIdx = 0;
|
||||
let currentBranchIdx = 0;
|
||||
let episodeOpenVersion = 0;
|
||||
let episodeEnrichmentVersion = 0;
|
||||
let currentTimeline = null;
|
||||
let traceView = prefs.traceView === "timeline" ? "timeline" : "transcript";
|
||||
let pendingTimelineNode = null;
|
||||
let pendingTimelineCall = null;
|
||||
|
||||
const COPY_SVG =
|
||||
`<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">` +
|
||||
@@ -2075,6 +2151,20 @@ function fetchEpisode(line, withTokens, withRendered = false) {
|
||||
return api(`/api/runs/${encodeURIComponent(state.run)}/rollouts/${traces.step}/${traces.kind}/${traces.subset}/${line}${qs}`);
|
||||
}
|
||||
|
||||
function fetchEpisodeTimeline(line) {
|
||||
const traces = state.traces;
|
||||
return api(`/api/runs/${encodeURIComponent(state.run)}/rollouts/${traces.step}/${traces.kind}/${traces.subset}/${line}/timeline`);
|
||||
}
|
||||
|
||||
async function ensureTimeline() {
|
||||
if (currentTimeline || currentLine == null) return;
|
||||
const line = currentLine;
|
||||
const requestVersion = episodeOpenVersion;
|
||||
const timeline = await fetchEpisodeTimeline(line);
|
||||
if (line !== currentLine || requestVersion !== episodeOpenVersion) return;
|
||||
currentTimeline = timeline;
|
||||
}
|
||||
|
||||
/* token strings multiply the payload of a big episode, so they are fetched only
|
||||
for token signals or the rendered-token view — the plain view ships the raw record */
|
||||
async function ensureTokens() {
|
||||
@@ -2103,7 +2193,11 @@ async function openEpisode(line, target = {}) {
|
||||
renderModalStep();
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
|
||||
$("#tm-timeline").innerHTML = `<div class="chart-empty">loading timeline…</div>`;
|
||||
$("#tm-meta").innerHTML = "";
|
||||
currentTimeline = null;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = null;
|
||||
const withTokens = !!$("#token-signal").value;
|
||||
const withRendered = state.traces.viewMode === "rendered";
|
||||
const episode = await fetchEpisode(line, withTokens, withRendered);
|
||||
@@ -2113,6 +2207,7 @@ async function openEpisode(line, target = {}) {
|
||||
currentEpisode = episode;
|
||||
currentTraceIdx = target.trace ?? 0;
|
||||
currentBranchIdx = target.branch ?? 0;
|
||||
if (traceView === "timeline") await ensureTimeline();
|
||||
renderEpisode();
|
||||
await ensureTokens();
|
||||
if (line === currentLine && requestVersion === episodeOpenVersion) renderEpisode();
|
||||
@@ -2125,6 +2220,9 @@ function closeDrawer() {
|
||||
$("#drawer-backdrop").hidden = true;
|
||||
$("#tm-back").hidden = true;
|
||||
currentEpisode = null;
|
||||
currentTimeline = null;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = null;
|
||||
currentLine = null;
|
||||
pendingHighlight = null;
|
||||
}
|
||||
@@ -2367,6 +2465,22 @@ function errorBannersHtml(errors) {
|
||||
);
|
||||
}
|
||||
|
||||
function normalizedCallUsage(usage = {}) {
|
||||
let input = usage.prompt_tokens;
|
||||
let cached = usage.cached_input_tokens;
|
||||
if (cached == null) {
|
||||
cached = usage.prompt_tokens_details?.cached_tokens;
|
||||
if (input != null && cached) input = Math.max(0, input - cached);
|
||||
}
|
||||
return {
|
||||
input,
|
||||
cached,
|
||||
output: usage.completion_tokens,
|
||||
reasoning: usage.reasoning_tokens ?? usage.completion_tokens_details?.reasoning_tokens,
|
||||
cost: usage.cost,
|
||||
};
|
||||
}
|
||||
|
||||
function renderMessages(ep, trace, branches) {
|
||||
const container = $("#tm-messages");
|
||||
entriesObserver?.disconnect();
|
||||
@@ -2387,7 +2501,22 @@ function renderMessages(ep, trace, branches) {
|
||||
let maxAbsAdv = 0;
|
||||
for (const node of trace.nodes || [])
|
||||
for (const a of node.advantages || []) maxAbsAdv = Math.max(maxAbsAdv, Math.abs(a));
|
||||
const callsByNode = new Map((trace.calls || []).map((c) => [c.node, c]));
|
||||
const indexedCalls = (trace.calls || []).map((call, index) => ({ call, index }));
|
||||
const callsByNode = new Map();
|
||||
for (const item of indexedCalls) {
|
||||
const calls = callsByNode.get(item.call.node) || [];
|
||||
calls.push(item);
|
||||
callsByNode.set(item.call.node, calls);
|
||||
}
|
||||
const callChipHtml = ({ call, index }) => {
|
||||
const fields = [`call ${index + 1}`];
|
||||
if (call.finish_reason) fields.push(call.finish_reason);
|
||||
const { input, cached, output } = normalizedCallUsage(call.usage);
|
||||
if (input != null) fields.push(`${fmtCompact(input)} in`);
|
||||
if (cached != null) fields.push(`${fmtCompact(cached)} cache`);
|
||||
if (output != null) fields.push(`${fmtCompact(output)} out`);
|
||||
return `<span class="chip" data-call-index="${index}">${esc(fields.join(" · "))}</span>`;
|
||||
};
|
||||
// agent highlights (sticky until the next view command or drawer close)
|
||||
const hl =
|
||||
pendingHighlight &&
|
||||
@@ -2407,14 +2536,12 @@ function renderMessages(ep, trace, branches) {
|
||||
const entryHtml = (idx, i) => {
|
||||
const node = trace.nodes[idx];
|
||||
const role = node.message?.role ?? "?";
|
||||
const call = callsByNode.get(idx);
|
||||
const marks = hlByNode.get(idx) || [];
|
||||
const chips = [];
|
||||
if (concatenated && node.parent != null && node.parent !== idx - 1) chips.push(`↳ branches from ${node.parent + 1}`);
|
||||
if (node.sampled) chips.push("sampled");
|
||||
if (call?.finish_reason) chips.push(call.finish_reason);
|
||||
if (call?.usage) chips.push(`${call.usage.prompt_tokens ?? "?"}→${call.usage.completion_tokens ?? "?"} tok`);
|
||||
else if (node.token_ids?.length) chips.push(`${node.token_ids.length} tok`);
|
||||
const nodeCalls = callsByNode.get(idx) || [];
|
||||
if (!nodeCalls.length && node.token_ids?.length) chips.push(`${node.token_ids.length} tok`);
|
||||
const text = messageText(node.message);
|
||||
const contentMarks = marks.filter((h) => !h.field || h.field === "content");
|
||||
const contentMarked = contentMarks.some((h) => h.quote && findQuote(text, h.quote, h.prefix, h.suffix));
|
||||
@@ -2431,11 +2558,12 @@ function renderMessages(ep, trace, branches) {
|
||||
if (reasoning) subs.push(reasoningBlock(reasoning, reasoningMarks));
|
||||
const toolCalls = (node.message?.tool_calls || []).map(toolCallHtml);
|
||||
const messageHtml =
|
||||
`<details class="entry ${esc(role)}${marked ? " hl-entry" : ""}"${role === "system" && !marked ? "" : " open"}>` +
|
||||
`<details class="entry ${esc(role)}${marked ? " hl-entry" : ""}" data-node="${idx}"${role === "system" && !marked ? "" : " open"}>` +
|
||||
`<summary><span class="entry-num">${String(i + 1).padStart(2, "0")}</span>` +
|
||||
`<span class="entry-role">${esc(role)}</span>` +
|
||||
`<span class="entry-preview">${preview(text, 180)}</span>` +
|
||||
chips.map((c) => `<span class="chip">${esc(c)}</span>`).join("") +
|
||||
nodeCalls.map(callChipHtml).join("") +
|
||||
`<button class="icon-btn" data-copy="${idx}" title="copy message">${COPY_SVG}</button>` +
|
||||
`<span class="entry-chev">›</span></summary>` +
|
||||
subs.join("") +
|
||||
@@ -2449,11 +2577,23 @@ function renderMessages(ep, trace, branches) {
|
||||
// first chunk forces enough entries into the DOM to scroll to
|
||||
const CHUNK = 30;
|
||||
const lastMark = Math.max(-1, ...[...hlByNode.keys()].map((n) => path.indexOf(n)));
|
||||
let rendered = Math.min(path.length, Math.max(CHUNK, lastMark + 3));
|
||||
const targetPosition = pendingTimelineNode == null ? -1 : path.indexOf(pendingTimelineNode);
|
||||
let rendered = Math.min(path.length, Math.max(CHUNK, lastMark + 3, targetPosition + 1));
|
||||
const unlinkedCallsHtml = indexedCalls
|
||||
.filter(({ call }) => !Number.isInteger(call.node) || call.node < 0 || call.node >= (trace.nodes || []).length)
|
||||
.map(
|
||||
(item) =>
|
||||
`<details class="entry model-call" data-call-index="${item.index}" open>` +
|
||||
`<summary><span class="entry-num">C${String(item.index + 1).padStart(2, "0")}</span>` +
|
||||
`<span class="entry-role">model call</span><span class="entry-preview">${esc(item.call.model || "unlinked call")}</span>` +
|
||||
`${callChipHtml(item)}<span class="entry-chev">›</span></summary></details>`,
|
||||
)
|
||||
.join("");
|
||||
container.innerHTML =
|
||||
(systemPosition === -1 ? toolsHtml : "") +
|
||||
path.slice(0, rendered).map(entryHtml).join("") +
|
||||
(rendered < path.length ? `<div id="tm-more" class="chart-empty">scroll for ${path.length - rendered} more entries</div>` : "") +
|
||||
unlinkedCallsHtml +
|
||||
errorsHtml;
|
||||
if (hl && !hl.scrolled) {
|
||||
const first = container.querySelector(".hl-entry");
|
||||
@@ -2537,28 +2677,35 @@ function renderMeta(ep, trace, branches) {
|
||||
parts.push(metaRow("branches", branches.length));
|
||||
parts.push(metaRow("tool calls", nodes.reduce((acc, n) => acc + (n.message?.tool_calls?.length || 0), 0)));
|
||||
|
||||
const usage = { input: 0, output: 0, reasoning: 0, cached: 0 };
|
||||
let hasUsage = false;
|
||||
const usage = { input: null, output: null, reasoning: null, cached: null, maxContext: null, cost: null };
|
||||
const addUsage = (field, value) => {
|
||||
if (value != null) usage[field] = (usage[field] ?? 0) + value;
|
||||
};
|
||||
for (const call of trace.calls || []) {
|
||||
const u = call.usage || {};
|
||||
if (u.prompt_tokens != null || u.completion_tokens != null) hasUsage = true;
|
||||
usage.input += u.prompt_tokens ?? 0;
|
||||
usage.output += u.completion_tokens ?? 0;
|
||||
usage.reasoning += u.completion_tokens_details?.reasoning_tokens ?? 0;
|
||||
usage.cached += u.prompt_tokens_details?.cached_tokens ?? 0;
|
||||
const current = normalizedCallUsage(call.usage);
|
||||
addUsage("input", current.input);
|
||||
addUsage("cached", current.cached);
|
||||
addUsage("output", current.output);
|
||||
addUsage("reasoning", current.reasoning);
|
||||
addUsage("cost", current.cost);
|
||||
if (current.input != null) {
|
||||
const context = current.input + (current.cached ?? 0);
|
||||
usage.maxContext = Math.max(usage.maxContext ?? 0, context);
|
||||
}
|
||||
}
|
||||
const totalInput = usage.input == null ? null : usage.input + (usage.cached ?? 0);
|
||||
const totalTokens = totalInput == null || usage.output == null ? null : totalInput + usage.output;
|
||||
const hasUsage = usage.input != null || usage.cached != null || usage.output != null;
|
||||
if (hasUsage) {
|
||||
parts.push(`<div class="meta-sec">usage</div>`);
|
||||
parts.push(metaRow("input tokens", fmtCompact(usage.input)));
|
||||
parts.push(metaRow("output tokens", fmtCompact(usage.output)));
|
||||
if (usage.reasoning) parts.push(metaRow("reasoning tokens", fmtCompact(usage.reasoning)));
|
||||
if (usage.cached) parts.push(metaRow("cached tokens", fmtCompact(usage.cached)));
|
||||
// API-priced runs report per-call cost; local deployments usually don't
|
||||
const traceCost = (t) => (t.calls || []).reduce((acc, c) => acc + (c.usage?.cost ?? 0), 0);
|
||||
const allTraces = ep.traces || [];
|
||||
if (allTraces.some((t) => (t.calls || []).some((c) => c.usage?.cost != null)))
|
||||
parts.push(metaRow("cost", fmtCost(allTraces.reduce((acc, t) => acc + traceCost(t), 0))));
|
||||
parts.push(metaRow("total tokens", fmtCompact(usage.input + usage.output)));
|
||||
if (usage.input != null) parts.push(metaRow("input tokens", fmtCompact(usage.input)));
|
||||
if (usage.cached != null) parts.push(metaRow("cached input", fmtCompact(usage.cached)));
|
||||
if (totalInput != null) parts.push(metaRow("total input", fmtCompact(totalInput)));
|
||||
if (usage.output != null) parts.push(metaRow("output tokens", fmtCompact(usage.output)));
|
||||
if (usage.reasoning != null) parts.push(metaRow("reasoning tokens", fmtCompact(usage.reasoning)));
|
||||
if (usage.maxContext != null) parts.push(metaRow("max context length", fmtCompact(usage.maxContext)));
|
||||
if (usage.cost != null) parts.push(metaRow("cost", fmtCost(usage.cost)));
|
||||
if (totalTokens != null) parts.push(metaRow("total tokens", fmtCompact(totalTokens)));
|
||||
}
|
||||
|
||||
parts.push(`<div class="meta-sec">state</div>`);
|
||||
@@ -2598,6 +2745,122 @@ function renderMeta(ep, trace, branches) {
|
||||
$("#tm-meta").innerHTML = parts.join("");
|
||||
}
|
||||
|
||||
function timelineClock(ts) {
|
||||
if (ts == null) return "—";
|
||||
return new Date(ts * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
||||
}
|
||||
|
||||
function timelineTipAttr(payload) {
|
||||
return ` data-timeline-tip="${esc(JSON.stringify(payload))}"`;
|
||||
}
|
||||
|
||||
function appendTimelineUsage(rows, usage, aggregate = false) {
|
||||
if (!usage) return;
|
||||
if (aggregate && usage.model_calls != null) rows.push(["model calls", fmtNum(usage.model_calls)]);
|
||||
if (usage.input_tokens != null) rows.push(["input tokens", fmtCompact(usage.input_tokens)]);
|
||||
if (usage.cached_tokens != null) rows.push(["cached input", fmtCompact(usage.cached_tokens)]);
|
||||
if (usage.total_input_tokens != null) rows.push(["total input", fmtCompact(usage.total_input_tokens)]);
|
||||
if (usage.output_tokens != null) rows.push(["output tokens", fmtCompact(usage.output_tokens)]);
|
||||
if (usage.reasoning_tokens != null) rows.push(["reasoning tokens", fmtCompact(usage.reasoning_tokens)]);
|
||||
if (usage.max_context_tokens != null) rows.push(["max context length", fmtCompact(usage.max_context_tokens)]);
|
||||
if (usage.total_tokens != null) rows.push(["total tokens", fmtCompact(usage.total_tokens)]);
|
||||
if (usage.cost != null) rows.push(["cost", fmtCost(usage.cost)]);
|
||||
}
|
||||
|
||||
function timelineSpanHtml(lane, span, start, total) {
|
||||
const partial = span.started_at == null || span.ended_at == null;
|
||||
const left = span.started_at == null ? 0 : Math.max(0, Math.min(100, ((span.started_at - start) / total) * 100));
|
||||
const width = partial ? 0.35 : Math.max(0.35, Math.min(100 - left, ((span.ended_at - span.started_at) / total) * 100));
|
||||
const rows = [
|
||||
["start", span.started_at == null ? "unknown" : timelineClock(span.started_at)],
|
||||
["end", span.ended_at == null ? (span.status === "running" ? "open" : "unknown") : timelineClock(span.ended_at)],
|
||||
["duration", partial ? "—" : fmtDuration(span.ended_at - span.started_at)],
|
||||
];
|
||||
if (span.track === "activity") {
|
||||
if (span.shared) rows.push(["branch role", "shared prefix"]);
|
||||
const totalInput = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
appendTimelineUsage(rows, {
|
||||
input_tokens: span.input_tokens,
|
||||
cached_tokens: span.cached_tokens,
|
||||
total_input_tokens: totalInput,
|
||||
output_tokens: span.output_tokens,
|
||||
reasoning_tokens: span.reasoning_tokens,
|
||||
max_context_tokens: totalInput,
|
||||
total_tokens: totalInput == null || span.output_tokens == null ? null : totalInput + span.output_tokens,
|
||||
cost: span.cost,
|
||||
});
|
||||
} else {
|
||||
appendTimelineUsage(rows, lane.usage, true);
|
||||
}
|
||||
const tip = timelineTipAttr({
|
||||
kind: span.track === "activity" ? "activity" : "lifecycle",
|
||||
title: `${lane.label} — ${span.label}`,
|
||||
snippet: span.snippet || "",
|
||||
rows,
|
||||
hint: span.track === "activity" ? "Click to open this call in the transcript." : "Click to open this trace transcript.",
|
||||
});
|
||||
const node = span.node_index == null ? "" : ` data-tl-node="${span.node_index}"`;
|
||||
const call = span.call_index == null ? "" : ` data-tl-call="${span.call_index}"`;
|
||||
return (
|
||||
`<button class="tl-span ${esc(span.track)} ${esc(span.kind)} ${span.shared ? "shared" : ""} ${span.status === "running" ? "running" : ""} ${partial ? "untimed" : ""}"` +
|
||||
` style="left:${left.toFixed(3)}%;width:${width.toFixed(3)}%" data-tl-trace="${lane.trace_index}"${node}${call}${tip}></button>`
|
||||
);
|
||||
}
|
||||
|
||||
function timelineLaneHtml(lane, start, total) {
|
||||
const grids = [25, 50, 75].map((left) => `<i class="tl-gridline" style="left:${left}%"></i>`).join("");
|
||||
const spans = (lane.spans || []).map((span) => timelineSpanHtml(lane, span, start, total)).join("");
|
||||
const duration = lane.started_at == null || lane.ended_at == null ? "—" : fmtDuration(lane.ended_at - lane.started_at);
|
||||
const ended = lane.ended_at == null ? (lane.status === "running" ? "open" : "unknown") : timelineClock(lane.ended_at);
|
||||
const model = lane.model
|
||||
? `<div class="tl-label-meta" title="${esc(lane.model)}">${esc(lane.model)}</div>`
|
||||
: "";
|
||||
return (
|
||||
`<div class="tl-lane" data-tl-trace="${lane.trace_index}">` +
|
||||
`<div class="tl-label" style="padding-left:${10 + (lane.depth || 0) * 18}px">` +
|
||||
`${lane.depth ? '<span class="tl-tree">└</span>' : ""}<span class="tl-dot" style="background:${PALETTE[lane.trace_index % PALETTE.length]}"></span>` +
|
||||
`<span class="tl-label-copy"><div class="tl-label-name" title="${esc(lane.label)}">${esc(lane.label)}</div>` +
|
||||
`${model}</span></div>` +
|
||||
`<div class="tl-track">${grids}${spans}</div>` +
|
||||
`<div class="tl-time"><span>${duration}</span><span class="muted">${ended}</span></div>` +
|
||||
`<div class="tl-outcome"><span class="tl-state ${esc(lane.status)}">${esc(lane.outcome || lane.status)}</span>` +
|
||||
`${lane.reward == null ? "" : `<span class="tl-reward">reward ${fmtReward(lane.reward)}</span>`}</div></div>`
|
||||
);
|
||||
}
|
||||
|
||||
function renderTimeline() {
|
||||
const target = $("#tm-timeline");
|
||||
const timeline = currentTimeline;
|
||||
if (!timeline) {
|
||||
target.innerHTML = `<div class="chart-empty">loading timeline…</div>`;
|
||||
return;
|
||||
}
|
||||
if (!(timeline.lanes || []).length) {
|
||||
target.innerHTML = emptyState("no timeline", "this episode carries no agent traces");
|
||||
return;
|
||||
}
|
||||
const starts = timeline.lanes.map((lane) => lane.started_at).filter((value) => value != null);
|
||||
const ends = timeline.lanes.map((lane) => lane.ended_at ?? lane.started_at).filter((value) => value != null);
|
||||
const start = starts.length ? Math.min(...starts) : 0;
|
||||
const end = ends.length ? Math.max(...ends) : start + 1;
|
||||
const total = Math.max(1, end - start);
|
||||
const axis = [0, 0.25, 0.5, 0.75, 1]
|
||||
.map((fraction) => `<span style="left:${fraction * 100}%">${fraction ? fmtDuration(total * fraction) : "0"}</span>`)
|
||||
.join("");
|
||||
target.innerHTML =
|
||||
`<div class="tl-shell"><div class="tl-head"><span>branches</span><div class="tl-axis">${axis}</div><span>duration / end</span><span>state / outcome</span></div>` +
|
||||
timeline.lanes.map((lane) => timelineLaneHtml(lane, start, total)).join("") +
|
||||
`</div>`;
|
||||
}
|
||||
|
||||
async function setTraceView(view) {
|
||||
traceView = view;
|
||||
setActive("#tm-view", "view", view);
|
||||
if (view === "timeline") await ensureTimeline();
|
||||
renderEpisode();
|
||||
savePrefs();
|
||||
}
|
||||
|
||||
function renderEpisode() {
|
||||
const ep = currentEpisode;
|
||||
if (!ep) return;
|
||||
@@ -2608,14 +2871,10 @@ function renderEpisode() {
|
||||
if (currentBranchIdx >= branches.length) currentBranchIdx = 0;
|
||||
const traceTabs = $("#tm-trace-tabs");
|
||||
traceTabs.hidden = traces.length <= 1;
|
||||
// multi-agent episodes: label each trace by its agent name (seat), index only
|
||||
// as a tiebreak when names repeat or are missing
|
||||
const names = traces.map((t) => t.agent?.name);
|
||||
const label = (i) => (names[i] && names.indexOf(names[i]) === names.lastIndexOf(names[i]) ? names[i] : `${names[i] ?? "trace"} ${i}`);
|
||||
traceTabs.innerHTML =
|
||||
traces.length > 1
|
||||
? traces
|
||||
.map((_, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(label(i))}</button>`)
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.join("")
|
||||
: "";
|
||||
const branchTabs = $("#tm-branch-tabs");
|
||||
@@ -2627,10 +2886,18 @@ function renderEpisode() {
|
||||
.join("") +
|
||||
`<button data-branch="-1" class="${currentBranchIdx === -1 ? "active" : ""}" title="all branches concatenated top to bottom">all</button>`
|
||||
: "";
|
||||
$("#tm-tabs-row").hidden = traceTabs.hidden && branchTabs.hidden;
|
||||
setActive("#trace-view-mode", "mode", state.traces.viewMode);
|
||||
renderRolloutList();
|
||||
renderMessages(ep, trace, branches);
|
||||
const timeline = traceView === "timeline";
|
||||
$("#tm-tabs-row").hidden = timeline || (traceTabs.hidden && branchTabs.hidden);
|
||||
$("#tm-messages").hidden = timeline;
|
||||
$("#tm-timeline").hidden = !timeline;
|
||||
$("#token-signal").closest(".dd-select").hidden = timeline;
|
||||
$("#tm-collapse").hidden = timeline;
|
||||
$("#tm-expand").hidden = timeline;
|
||||
setActive("#tm-view", "view", traceView);
|
||||
if (timeline) renderTimeline();
|
||||
else renderMessages(ep, trace, branches);
|
||||
renderMeta(ep, trace, branches);
|
||||
}
|
||||
|
||||
@@ -3318,6 +3585,10 @@ $("#config-format").addEventListener("click", (e) => {
|
||||
renderConfigFormat();
|
||||
loadConfig();
|
||||
});
|
||||
$("#config-command-copy").addEventListener("click", (e) => {
|
||||
const command = state.config.commandText.trimEnd();
|
||||
if (command) copyText(command, e.currentTarget);
|
||||
});
|
||||
$("#config-search").addEventListener(
|
||||
"input",
|
||||
debounce(() => {
|
||||
@@ -3421,6 +3692,11 @@ $("#attempt-select").addEventListener("change", async (e) => {
|
||||
await loadLogfiles();
|
||||
await pollLogs();
|
||||
});
|
||||
$("#config-attempt-select").addEventListener("change", async (e) => {
|
||||
state.config.attempt = e.target.value;
|
||||
state.config.file = null;
|
||||
await loadConfigAttempt();
|
||||
});
|
||||
$("#log-panes").addEventListener("change", async (e) => {
|
||||
const select = e.target.closest(".lp-file");
|
||||
if (!select) return;
|
||||
@@ -3654,6 +3930,75 @@ $("#trace-view-mode").addEventListener("click", async (e) => {
|
||||
renderEpisode();
|
||||
savePrefs();
|
||||
});
|
||||
$("#tm-view").addEventListener("click", (e) => {
|
||||
const button = e.target.closest("[data-view]");
|
||||
if (button && button.dataset.view !== traceView) setTraceView(button.dataset.view);
|
||||
});
|
||||
$("#tm-timeline").addEventListener("click", async (e) => {
|
||||
const target = e.target.closest("[data-tl-trace]");
|
||||
if (!target) return;
|
||||
e.stopPropagation();
|
||||
currentTraceIdx = +target.dataset.tlTrace;
|
||||
const node = target.dataset.tlNode == null ? null : +target.dataset.tlNode;
|
||||
const call = target.dataset.tlCall == null ? null : +target.dataset.tlCall;
|
||||
if (node != null) {
|
||||
const trace = currentEpisode?.traces?.[currentTraceIdx];
|
||||
const branches = trace ? traceBranches(trace) : [];
|
||||
const branch = branches.findIndex((path) => path.includes(node));
|
||||
currentBranchIdx = branch >= 0 ? branch : -1;
|
||||
pendingTimelineNode = node;
|
||||
pendingTimelineCall = call;
|
||||
state.traces.viewMode = "messages";
|
||||
} else {
|
||||
currentBranchIdx = 0;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = call;
|
||||
if (call != null) state.traces.viewMode = "messages";
|
||||
}
|
||||
await setTraceView("transcript");
|
||||
requestAnimationFrame(() => {
|
||||
const entry =
|
||||
pendingTimelineCall == null
|
||||
? pendingTimelineNode == null
|
||||
? null
|
||||
: $(`#tm-messages [data-node="${pendingTimelineNode}"]`)
|
||||
: $(`#tm-messages [data-call-index="${pendingTimelineCall}"]`);
|
||||
entry?.scrollIntoView({ block: "center" });
|
||||
const details = entry?.closest("details");
|
||||
if (details) details.open = true;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = null;
|
||||
});
|
||||
});
|
||||
const timelineTip = document.createElement("div");
|
||||
timelineTip.className = "tl-tooltip";
|
||||
timelineTip.hidden = true;
|
||||
document.body.appendChild(timelineTip);
|
||||
function moveTimelineTip(e) {
|
||||
const gap = 12;
|
||||
const left = Math.min(e.clientX + gap, window.innerWidth - timelineTip.offsetWidth - 8);
|
||||
const top = Math.min(e.clientY + gap, window.innerHeight - timelineTip.offsetHeight - 8);
|
||||
timelineTip.style.left = `${Math.max(8, left)}px`;
|
||||
timelineTip.style.top = `${Math.max(8, top)}px`;
|
||||
}
|
||||
$("#tm-timeline").addEventListener("mouseover", (e) => {
|
||||
const target = e.target.closest("[data-timeline-tip]");
|
||||
if (!target) return;
|
||||
const payload = JSON.parse(target.dataset.timelineTip);
|
||||
timelineTip.innerHTML =
|
||||
`<div class="tl-tooltip-kind">${esc(payload.kind)}</div><div class="tl-tooltip-title">${esc(payload.title)}</div>` +
|
||||
`${payload.snippet ? `<div class="tl-tooltip-snippet">${esc(payload.snippet)}</div>` : ""}` +
|
||||
`<dl>${payload.rows.map(([key, value]) => `<dt>${esc(key)}</dt><dd>${esc(value)}</dd>`).join("")}</dl>` +
|
||||
`<div class="tl-tooltip-hint">${esc(payload.hint)}</div>`;
|
||||
timelineTip.hidden = false;
|
||||
moveTimelineTip(e);
|
||||
});
|
||||
$("#tm-timeline").addEventListener("mousemove", (e) => {
|
||||
if (!timelineTip.hidden) moveTimelineTip(e);
|
||||
});
|
||||
$("#tm-timeline").addEventListener("mouseout", (e) => {
|
||||
if (e.target.closest("[data-timeline-tip]") && !e.relatedTarget?.closest?.("[data-timeline-tip]")) timelineTip.hidden = true;
|
||||
});
|
||||
$("#tm-trace-tabs").addEventListener("click", (e) => {
|
||||
const btn = e.target.closest("[data-trace]");
|
||||
if (btn) { currentTraceIdx = +btn.dataset.trace; currentBranchIdx = 0; renderEpisode(); }
|
||||
@@ -3734,6 +4079,7 @@ function savePrefs() {
|
||||
traceErrorsOnly: state.traces.errorsOnly,
|
||||
traceSort: `${state.traces.sort}:${state.traces.order}`,
|
||||
traceViewMode: state.traces.viewMode,
|
||||
traceView,
|
||||
logView: state.logs.view,
|
||||
logComponents: state.logs.components ? [...state.logs.components] : null,
|
||||
logLevel: state.logs.level,
|
||||
@@ -3800,7 +4146,7 @@ document.addEventListener("visibilitychange", () => {
|
||||
$("#config-search").value = prefs.configSearch ?? "";
|
||||
$("#token-signal").value = prefs.tokenSignal === "rendered" ? "" : (prefs.tokenSignal ?? "");
|
||||
$("#follow-toggle").checked = state.follow;
|
||||
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#tm-env", "#tm-sort", "#attempt-select", "#token-signal", "#report-select"])
|
||||
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#tm-env", "#tm-sort", "#config-attempt-select", "#attempt-select", "#token-signal", "#report-select"])
|
||||
dressSelect($(sel));
|
||||
syncTraceFilterControls();
|
||||
setActive("#metrics-mode", "mode", state.metrics.mode);
|
||||
|
||||
@@ -55,6 +55,8 @@
|
||||
|
||||
<section id="tab-config" hidden>
|
||||
<div class="controls">
|
||||
<label class="t-label">attempt</label>
|
||||
<select id="config-attempt-select"></select>
|
||||
<div class="seg" id="config-format">
|
||||
<button data-fmt="toml">TOML</button>
|
||||
<button data-fmt="json">JSON</button>
|
||||
@@ -62,6 +64,16 @@
|
||||
<input id="config-search" class="search" type="search" placeholder="regex search, e.g. lora|lr">
|
||||
<span id="config-hits" class="muted"></span>
|
||||
</div>
|
||||
<div id="config-command">
|
||||
<div class="config-command-head">
|
||||
<span class="t-label">command</span>
|
||||
<button id="config-command-copy" class="btn" type="button">copy</button>
|
||||
</div>
|
||||
<div class="config-command-body">
|
||||
<span class="config-command-prompt" aria-hidden="true">$</span>
|
||||
<code id="config-command-text"></code>
|
||||
</div>
|
||||
</div>
|
||||
<pre id="config-view"></pre>
|
||||
</section>
|
||||
|
||||
@@ -203,6 +215,10 @@
|
||||
<div class="tm-head">
|
||||
<span class="tm-title">Trace Viewer</span>
|
||||
<button id="tm-back" class="btn" hidden title="back to the report">← report</button>
|
||||
<div class="seg" id="tm-view">
|
||||
<button data-view="transcript" class="active">Transcript</button>
|
||||
<button data-view="timeline">Timeline</button>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" id="trace-view-mode">
|
||||
<button data-mode="messages" class="active">Messages</button>
|
||||
@@ -224,6 +240,7 @@
|
||||
<div id="tm-branch-tabs" class="seg" hidden></div>
|
||||
</div>
|
||||
<div id="tm-messages"></div>
|
||||
<div id="tm-timeline" hidden></div>
|
||||
</section>
|
||||
<aside id="tm-right">
|
||||
<div class="tm-head"><span class="tm-title">Overview</span></div>
|
||||
|
||||
@@ -448,6 +448,34 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
body.resizing { user-select: none; }
|
||||
|
||||
/* ---------------------------------------------------------------- config */
|
||||
#config-command {
|
||||
background: #0b0b0b;
|
||||
border: 1px solid var(--grey-3);
|
||||
color: var(--grey-6);
|
||||
}
|
||||
.config-command-head {
|
||||
min-height: 30px;
|
||||
padding: 4px 6px 4px 12px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
background: var(--grey-2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
#config-command-copy { height: 22px; }
|
||||
#config-command-copy.copied { color: var(--accent); border-color: var(--accent); }
|
||||
#config-command-copy:disabled { opacity: 0.35; cursor: default; }
|
||||
.config-command-body {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 13px 14px;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.config-command-prompt { color: var(--accent); user-select: none; }
|
||||
#config-command-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
#config-command.empty #config-command-text { color: var(--grey-4); }
|
||||
#config-view {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
@@ -643,6 +671,12 @@ mark.hit {
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
min-height: 48px;
|
||||
}
|
||||
.tm-tabs-row {
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.tm-title { font-size: 12px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
|
||||
#tm-left { border-right: 1px solid var(--hairline); display: flex; flex-direction: column; min-height: 0; }
|
||||
#tm-left .search { margin: 10px 14px 6px; }
|
||||
@@ -686,9 +720,78 @@ mark.hit {
|
||||
#tm-main { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
|
||||
#tm-messages { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
|
||||
#tm-messages > * { flex-shrink: 0; }
|
||||
#tm-timeline { flex: 1; min-height: 0; overflow: auto; padding: 14px 16px 24px; }
|
||||
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
|
||||
#tm-meta { padding: 12px 14px; }
|
||||
|
||||
/* episode timeline: lifecycle spans above exact model-call activity */
|
||||
.tl-shell { min-width: 780px; border: 1px solid var(--hairline); }
|
||||
.tl-head, .tl-lane {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(160px, 220px) minmax(390px, 1fr) 105px 150px;
|
||||
}
|
||||
.tl-head {
|
||||
min-height: 42px;
|
||||
align-items: end;
|
||||
color: var(--grey-4);
|
||||
font-size: 9px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
border-bottom: 1px solid var(--grey-3);
|
||||
}
|
||||
.tl-head > span { padding: 8px 10px; }
|
||||
.tl-axis { position: relative; align-self: stretch; min-width: 0; }
|
||||
.tl-axis span { position: absolute; bottom: 8px; transform: translateX(-50%); white-space: nowrap; }
|
||||
.tl-axis span:first-child { transform: none; }
|
||||
.tl-axis span:last-child { transform: translateX(-100%); }
|
||||
.tl-lane { min-height: 66px; border-bottom: 1px solid var(--hairline-faint); cursor: pointer; }
|
||||
.tl-lane:last-child { border-bottom: 0; }
|
||||
.tl-lane:hover { background: rgba(255, 255, 255, 0.025); }
|
||||
.tl-label, .tl-time, .tl-outcome { padding: 11px 10px; min-width: 0; }
|
||||
.tl-label { display: flex; align-items: flex-start; gap: 8px; }
|
||||
.tl-tree { color: var(--grey-3); flex-shrink: 0; }
|
||||
.tl-dot { width: 6px; height: 6px; margin-top: 5px; background: var(--chart-2); flex-shrink: 0; }
|
||||
.tl-label-copy { min-width: 0; }
|
||||
.tl-label-name { color: var(--grey-6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tl-label-meta { color: var(--grey-4); font-size: 9.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tl-track { position: relative; height: 42px; margin: 11px 0; border: 1px solid var(--hairline); overflow: hidden; }
|
||||
.tl-gridline { position: absolute; top: 0; bottom: 0; border-left: 1px solid var(--hairline-faint); pointer-events: none; }
|
||||
.tl-span { position: absolute; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
|
||||
.tl-span.lifecycle { top: 7px; height: 13px; opacity: 0.78; }
|
||||
.tl-span.activity { top: 28px; height: 6px; background: var(--grey-4); }
|
||||
.tl-span.activity.shared { opacity: 0.28; }
|
||||
.tl-span.untimed { border-left: 3px double var(--grey-6); }
|
||||
.tl-span:hover, .tl-span:focus-visible { opacity: 1; outline: 1px solid var(--grey-6); outline-offset: 1px; }
|
||||
.tl-span.boot, .tl-span.setup { background: var(--grey-4); }
|
||||
.tl-span.agent { background: var(--chart-2); }
|
||||
.tl-span.finalize { background: var(--chart-1); }
|
||||
.tl-span.scoring { background: var(--chart-3); }
|
||||
.tl-span.running { border-right: 2px solid var(--accent); }
|
||||
.tl-time { color: var(--grey-5); font-size: 11px; }
|
||||
.tl-time .muted { display: block; font-size: 9.5px; }
|
||||
.tl-outcome { display: flex; flex-direction: column; align-items: flex-start; gap: 5px; font-size: 9.5px; }
|
||||
.tl-state, .tl-reward { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
|
||||
.tl-state.completed { color: var(--positive); }
|
||||
.tl-state.failed { color: var(--negative); }
|
||||
.tl-state.running { color: var(--infra); }
|
||||
.tl-reward { color: var(--chart-3); }
|
||||
.tl-tooltip {
|
||||
position: fixed;
|
||||
z-index: 60;
|
||||
width: min(390px, calc(100vw - 24px));
|
||||
padding: 12px 14px;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
pointer-events: none;
|
||||
}
|
||||
.tl-tooltip-kind { color: var(--accent); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
.tl-tooltip-title { color: var(--grey-6); font-size: 12px; margin: 3px 0 8px; }
|
||||
.tl-tooltip-snippet { color: var(--grey-5); font-size: 11px; margin-bottom: 9px; white-space: normal; }
|
||||
.tl-tooltip dl { display: grid; grid-template-columns: auto 1fr; gap: 2px 16px; margin: 0; font-size: 10.5px; }
|
||||
.tl-tooltip dt { color: var(--grey-4); }
|
||||
.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; }
|
||||
.trace-error-banner {
|
||||
border: 1px solid var(--negative);
|
||||
|
||||
@@ -6,18 +6,25 @@ lives in ``prime_rl.evals.evals``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Evals")
|
||||
config = cli(EvalsConfig)
|
||||
from prime_rl.utils.pathing import write_launch_toml
|
||||
from prime_rl.utils.pathing import prepare_attempt_dirs, write_launch_artifacts
|
||||
|
||||
write_launch_toml(config.output_dir, "evals")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
|
||||
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
|
||||
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
|
||||
os.environ["PRL_LOG_DIR"] = str(log_dir)
|
||||
write_launch_artifacts(config_dir, "evals")
|
||||
(config_dir / "evals.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
|
||||
from prime_rl.evals.evals import run_evals
|
||||
|
||||
asyncio.run(run_evals(config))
|
||||
|
||||
@@ -12,10 +12,10 @@ from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
format_log_message,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -57,7 +57,7 @@ def write_config(
|
||||
return config_path
|
||||
|
||||
|
||||
def write_slurm_script(config: InferenceConfig, config_path: Path, script_path: Path) -> None:
|
||||
def write_slurm_script(config: InferenceConfig, config_path: Path, log_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
@@ -76,6 +76,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
template_vars = dict(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.output_dir,
|
||||
launcher_log_dir=get_launcher_log_dir(config.output_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
@@ -133,17 +135,17 @@ def inference_slurm(config: InferenceConfig):
|
||||
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.output_dir)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
|
||||
write_launch_artifacts(config_dir, "inference")
|
||||
is_multi_node = config.deployment.type in ("multi_node", "disaggregated")
|
||||
exclude = {"deployment", "slurm", "dry_run"} if is_multi_node else {"slurm", "dry_run"}
|
||||
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
write_slurm_script(config, config_path, log_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
log_dir = latest_log_dir(config.output_dir)
|
||||
num_nodes = getattr(config.deployment, "num_nodes", 1)
|
||||
log_message = format_log_message(log_dir=log_dir, inference=True, job_log=True, num_infer_nodes=num_nodes)
|
||||
|
||||
|
||||
@@ -20,16 +20,14 @@ from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_toml,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -123,8 +121,8 @@ def rl_local(config: RLConfig):
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "rl")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "rl")
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
@@ -179,9 +177,6 @@ def rl_local(config: RLConfig):
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
|
||||
# Per-attempt log dir: a resume never overwrites an earlier attempt's logs
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
|
||||
# Start processes
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
@@ -420,7 +415,7 @@ def rl_local(config: RLConfig):
|
||||
raise
|
||||
|
||||
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) -> None:
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
@@ -459,10 +454,27 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
|
||||
nixl_broadcast = (
|
||||
config.weight_broadcast
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nixl"
|
||||
else None
|
||||
)
|
||||
launch_modelexpress = nixl_broadcast is not None and config.slurm.launch_modelexpress
|
||||
modelexpress_vars = {
|
||||
"use_nixl_broadcast": nixl_broadcast is not None,
|
||||
"launch_modelexpress": launch_modelexpress,
|
||||
"modelexpress_host": nixl_broadcast.host if nixl_broadcast is not None else "",
|
||||
"modelexpress_port": nixl_broadcast.port if nixl_broadcast is not None else 0,
|
||||
"modelexpress_redis_port": 6380 if nixl_broadcast is not None and nixl_broadcast.port == 6379 else 6379,
|
||||
}
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
**modelexpress_vars,
|
||||
config_path=config_dir / RL_CONFIG,
|
||||
config_dir=config_dir,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
@@ -476,6 +488,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
is_disaggregated=True,
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
@@ -512,6 +525,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
**modelexpress_vars,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
@@ -519,6 +533,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
is_disaggregated=False,
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
@@ -551,6 +566,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
inference_env_vars=inference_env_vars,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
**modelexpress_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -565,9 +581,8 @@ def rl_slurm(config: RLConfig):
|
||||
config.log.level or os.environ.get("PRIME_LOG_LEVEL", "info"), json_logging=config.log.json_logging
|
||||
)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "rl")
|
||||
log_dir = latest_log_dir(config.run_dir)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "rl")
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
|
||||
@@ -604,7 +619,7 @@ def rl_slurm(config: RLConfig):
|
||||
)
|
||||
|
||||
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
write_slurm_script(config, config_dir, log_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
if config.dry_run:
|
||||
|
||||
+72
-143
@@ -17,18 +17,15 @@ from prime_rl.utils.config import cli, dump_resolved_config, find_package_resour
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
get_log_dir,
|
||||
latest_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_toml,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -43,8 +40,6 @@ from prime_rl.utils.process import (
|
||||
|
||||
SFT_CONFIG = "sft.json"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
EVAL_SBATCH = "eval.sbatch"
|
||||
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
|
||||
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
EVALS_CONFIG = "evals.json"
|
||||
@@ -144,14 +139,20 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
|
||||
json.dump(env_server_dict, f, indent=2)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path, prl_run_id: str | None = None) -> None:
|
||||
def write_slurm_script(
|
||||
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
|
||||
) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
|
||||
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
|
||||
template_dirs = [config.slurm.template_path.parent]
|
||||
bundled_templates = find_package_resource("templates")
|
||||
if bundled_templates is not None:
|
||||
template_dirs.append(bundled_templates)
|
||||
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
trainer_env_vars = {
|
||||
@@ -164,29 +165,62 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
online_eval = config.eval is not None
|
||||
eval_vars = {}
|
||||
if online_eval:
|
||||
assert config.inference is not None
|
||||
inference_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
}
|
||||
eval_vars = {
|
||||
"router": config.inference.router,
|
||||
"router_port": config.inference.server.port,
|
||||
"backend_port": config.inference.backend_port,
|
||||
"data_parallel_rpc_port": config.inference.vllm.data_parallel_rpc_port,
|
||||
"dp_per_node": config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
"enable_expert_parallel": config.inference.vllm.enable_expert_parallel,
|
||||
"inference_env_vars": inference_env_vars,
|
||||
"evals_env_vars": {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
},
|
||||
"eval_env_names": [source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
}
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_train_nodes,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
online_eval=online_eval,
|
||||
use_nccl_broadcast=(
|
||||
config.eval is not None
|
||||
and config.weight_broadcast is not None
|
||||
and config.weight_broadcast.type == "nccl"
|
||||
),
|
||||
**eval_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -194,172 +228,66 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
|
||||
"""Write the SLURM script for the decoupled online-eval job (inference pool +
|
||||
env servers + evals) to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
assert config.deployment.type == "multi_node"
|
||||
assert config.inference is not None
|
||||
|
||||
# The eval template is bundled next to the trainer templates; a custom
|
||||
# slurm.template_path directory takes precedence so both can be overridden.
|
||||
template_dirs = [config.slurm.template_path.parent]
|
||||
bundled_templates = find_package_resource("templates")
|
||||
if bundled_templates is not None:
|
||||
template_dirs.append(bundled_templates)
|
||||
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
|
||||
template = env.get_template(EVAL_TEMPLATE)
|
||||
|
||||
inference_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
}
|
||||
evals_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
|
||||
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.router,
|
||||
router_port=config.inference.server.port,
|
||||
backend_port=config.inference.backend_port,
|
||||
data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port,
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
|
||||
inference_env_vars=inference_env_vars,
|
||||
evals_env_vars=evals_env_vars,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def sft_slurm(config: SFTConfig):
|
||||
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
|
||||
trainer and the eval deployment (inference pool + evals) are two independent
|
||||
SLURM jobs. The trainer publishes its rank-0 hostname through the shared run
|
||||
directory so the eval deployment can join its NCCL weight-broadcast group."""
|
||||
"""Run SFT training and its online-eval deployment in one SLURM allocation."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
decoupled_eval = config.deployment.type == "multi_node" and config.eval is not None
|
||||
online_eval = config.deployment.type == "multi_node" and config.eval is not None
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "sft")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run", "clean"}
|
||||
if config.deployment.type == "multi_node"
|
||||
else {"slurm", "dry_run", "clean"}
|
||||
)
|
||||
if decoupled_eval:
|
||||
if online_eval:
|
||||
# The trainer job only needs [eval] for the weight-broadcast cadence; the
|
||||
# inference pool lives in the eval job.
|
||||
# inference pool runs on its dedicated nodes in the same allocation.
|
||||
exclude = exclude | {"inference"}
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
# Trainer and evals processes log to a single shared W&B run across both jobs,
|
||||
# keyed by the launcher's run id.
|
||||
# Trainer and evals processes log to a single shared W&B run.
|
||||
prl_run_id: str | None = None
|
||||
if decoupled_eval and config.monitors.wandb is not None:
|
||||
if online_eval and config.monitors.wandb is not None:
|
||||
prl_run_id = os.environ["PRL_RUN_ID"]
|
||||
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
# The trainer job is submitted first and the eval job depends on it having started:
|
||||
# the trainer creates the shared W&B run, and the evals process's joiner init only
|
||||
# retries for a bounded window — starting the evals process while the trainer job pends
|
||||
# would crash it at wandb init.
|
||||
script_paths = [script_path]
|
||||
if decoupled_eval:
|
||||
if online_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
eval_script_path = launcher_dir / EVAL_SBATCH
|
||||
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
|
||||
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
|
||||
script_paths = [script_path, eval_script_path]
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
|
||||
log_message = format_log_message(
|
||||
log_dir=latest_log_dir(config.run_dir),
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
num_train_nodes=num_nodes,
|
||||
evals=online_eval,
|
||||
inference=online_eval,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)] if online_eval else None,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
)
|
||||
if decoupled_eval:
|
||||
# The eval job logs at stable (non-attempt) paths under the run dir.
|
||||
log_message += "\n" + format_log_message(
|
||||
log_dir=get_log_dir(config.run_dir),
|
||||
evals=True,
|
||||
inference=True,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
).removeprefix("Logs:\n")
|
||||
|
||||
if config.dry_run:
|
||||
if decoupled_eval:
|
||||
trainer_submit = f" TRAIN_JOB_ID=$(sbatch --parsable {script_paths[0]} | cut -d';' -f1)"
|
||||
eval_submit = f" sbatch --dependency=after:$TRAIN_JOB_ID {script_paths[1]}"
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
eval_submit = (
|
||||
" sbatch --dependency=after:$TRAIN_JOB_ID "
|
||||
f"--export=ALL,TRAIN_JOB_ID=$TRAIN_JOB_ID {script_paths[1]}"
|
||||
)
|
||||
submit = "\n".join((trainer_submit, eval_submit))
|
||||
else:
|
||||
submit = f" sbatch {script_paths[0]}"
|
||||
note = (
|
||||
"\n\nSubmit the trainer job first. The eval job starts after the trainer allocation is ready."
|
||||
if decoupled_eval
|
||||
else ""
|
||||
)
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
submitted_job_ids: list[str] = []
|
||||
for path in script_paths:
|
||||
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
|
||||
# (e.g. multi-cluster sbatch appends "on cluster <name>").
|
||||
cmd = ["sbatch", "--parsable"]
|
||||
if submitted_job_ids:
|
||||
# Hold the eval job until the trainer job has started (not finished).
|
||||
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
cmd.append(f"--export=ALL,TRAIN_JOB_ID={submitted_job_ids[-1]}")
|
||||
cmd.append(str(path))
|
||||
logger.info(f"Submitting: {' '.join(cmd)}")
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
for job_id in submitted_job_ids:
|
||||
logger.warning(f"Cancelling already-submitted job {job_id}")
|
||||
subprocess.run(["scancel", job_id], capture_output=True, text=True)
|
||||
sys.exit(1)
|
||||
job_id = result.stdout.strip().split(";")[0]
|
||||
submitted_job_ids.append(job_id)
|
||||
logger.success(f"Submitted batch job {job_id}")
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(log_message)
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
|
||||
@@ -369,8 +297,8 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "sft")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
write_config(config, config_path)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
@@ -385,8 +313,6 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
|
||||
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
|
||||
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
|
||||
infer_gpu_ids: list[int] = []
|
||||
@@ -484,6 +410,9 @@ def sft_local(config: SFTConfig):
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
"PRL_ATTEMPT_CONFIG_DIR": str(config_dir),
|
||||
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
|
||||
"PRL_LOG_DIR": str(log_dir),
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "evals",
|
||||
},
|
||||
|
||||
+88
-24
@@ -13,8 +13,9 @@ inside the handshake until the receiver acknowledges.
|
||||
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
|
||||
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
|
||||
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
|
||||
are version-pinned measurements, so an overload cut only blocks admission and
|
||||
the in-flight pool drains through natural completions.
|
||||
are version-pinned measurements. By default, a newer online checkpoint cancels
|
||||
unfinished episodes from the prior version; callers can disable this when they need
|
||||
every epoch to drain.
|
||||
|
||||
Env servers: sources without an explicit ``serve.address`` get an env server
|
||||
spawned by the evals process at their derived address; sources with one are
|
||||
@@ -28,6 +29,7 @@ import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
|
||||
from prime_rl import monitors
|
||||
@@ -51,7 +53,7 @@ from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_def
|
||||
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
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir
|
||||
from prime_rl.utils.pathing import create_attempt_log_dir, get_all_ckpt_steps, get_config_dir
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
@@ -67,8 +69,13 @@ STARTUP_BROADCAST_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class Evals:
|
||||
def __init__(self, config: EvalsConfig) -> None:
|
||||
def __init__(self, config: EvalsConfig, log_dir: Path | None = None) -> None:
|
||||
self.config = config
|
||||
self.log_dir = log_dir or (
|
||||
Path(os.environ["PRL_LOG_DIR"])
|
||||
if "PRL_LOG_DIR" in os.environ
|
||||
else create_attempt_log_dir(config.output_dir)
|
||||
)
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
|
||||
@@ -209,7 +216,7 @@ class Evals:
|
||||
config = self.config
|
||||
addresses = config.eval.env_addresses
|
||||
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
|
||||
log_dir = get_log_dir(config.output_dir) / "envs" / "eval"
|
||||
log_dir = self.log_dir / "envs" / "eval"
|
||||
for source in config.eval.source:
|
||||
if source.serve.address is not None:
|
||||
continue
|
||||
@@ -316,6 +323,20 @@ class Evals:
|
||||
break
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
def next_published_step(self, step: int) -> int | None:
|
||||
"""Return the first newer checkpoint offered by the trainer."""
|
||||
assert self.config.online is not None
|
||||
assert self.config.online.broadcasts_dir is not None
|
||||
assert self.receiver is not None
|
||||
return next(
|
||||
(
|
||||
candidate
|
||||
for candidate in get_all_ckpt_steps(self.config.online.broadcasts_dir)
|
||||
if candidate > step and self.receiver.is_published(candidate)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
|
||||
"""Eval-due steps up to the newest published broadcast that are missing from
|
||||
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
|
||||
@@ -350,7 +371,10 @@ class Evals:
|
||||
# Every offered version must be received: the trainer blocks inside
|
||||
# the handshake, so a failed receive fails the run loudly.
|
||||
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
|
||||
await self.dispatcher.on_version_pending(step)
|
||||
await self.receiver.receive(step)
|
||||
self.policy.version = step
|
||||
await self.dispatcher.on_new_version(step)
|
||||
|
||||
if not fired:
|
||||
return
|
||||
@@ -365,34 +389,66 @@ class Evals:
|
||||
|
||||
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
|
||||
# between the trigger above and the weight reload completing.
|
||||
self.policy.version = step
|
||||
if not reload_weights:
|
||||
self.policy.version = step
|
||||
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
|
||||
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
|
||||
await self.consume_epoch(fired)
|
||||
await self.consume_epoch(fired, step)
|
||||
|
||||
async def consume_epoch(self, fired: list[str]) -> None:
|
||||
"""Consume dispatcher episodes until every fired env's epoch finalizes,
|
||||
routing them through the sink and monitors."""
|
||||
# An env with no examples emits no episodes, so its epoch can never finalize.
|
||||
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}
|
||||
cancellation_task: asyncio.Task[int] | None = None
|
||||
superseding_step: int | None = None
|
||||
online = self.config.online
|
||||
|
||||
while pending:
|
||||
item = await self.dispatcher.out_q.get()
|
||||
if (
|
||||
cancellation_task is None
|
||||
and online is not None
|
||||
and self.config.eval.cancel_on_new_checkpoint
|
||||
and (superseding_step := self.next_published_step(step)) is not None
|
||||
):
|
||||
get_logger().warning(
|
||||
f"Checkpoint {superseding_step} is ready - cancelling unfinished eval episodes for step {step}"
|
||||
)
|
||||
cancellation_task = asyncio.create_task(
|
||||
self.dispatcher.cancel_eval_step(step), name=f"cancel-eval-step-{step}"
|
||||
)
|
||||
|
||||
try:
|
||||
if online is not None and self.config.eval.cancel_on_new_checkpoint:
|
||||
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=POLL_INTERVAL_S)
|
||||
else:
|
||||
item = await self.dispatcher.out_q.get()
|
||||
except asyncio.TimeoutError:
|
||||
if cancellation_task is not None and cancellation_task.done():
|
||||
cancellation_task.result()
|
||||
continue
|
||||
|
||||
if isinstance(item, GroupCancellation):
|
||||
raise RuntimeError("Eval dispatcher emitted a group cancellation")
|
||||
if isinstance(item, DispatchFailure):
|
||||
eval_batch = self.eval_sink.cancel(item)
|
||||
elif isinstance(item, DispatchFailure):
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
else:
|
||||
step = eval_work(item).step
|
||||
await monitors.log([item], step, "eval", "all")
|
||||
item_step = eval_work(item).step
|
||||
await monitors.log([item], item_step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(item)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
pending.discard(eval_batch.env_name)
|
||||
|
||||
if cancellation_task is not None:
|
||||
cancelled = await cancellation_task
|
||||
get_logger().warning(
|
||||
f"Cancelled {cancelled} unfinished eval episodes for step {step}; "
|
||||
f"advancing to checkpoint {superseding_step}"
|
||||
)
|
||||
|
||||
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."""
|
||||
if not batch.episodes and not batch.failures:
|
||||
if not batch.episodes and not batch.failures and not batch.cancelled:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
|
||||
return
|
||||
|
||||
@@ -404,12 +460,15 @@ class Evals:
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", episodes), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
total_attempts = len(episodes) + len(batch.failures)
|
||||
total_attempts = len(episodes) + len(batch.failures) + batch.cancelled
|
||||
metrics |= dispatch_failure_metrics(
|
||||
batch.failures,
|
||||
prefix=f"eval/{batch.env_name}/all",
|
||||
total_attempts=total_attempts,
|
||||
)
|
||||
if batch.cancelled:
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
|
||||
metrics["step"] = float(batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
@@ -417,6 +476,13 @@ class Evals:
|
||||
eff, full = effective.metrics, episodes.metrics
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
if batch.cancelled:
|
||||
get_logger().warning(
|
||||
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Completed {len(episodes)}/{total_attempts} | Cancelled {batch.cancelled}/{total_attempts}"
|
||||
)
|
||||
return
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
@@ -461,8 +527,8 @@ class Evals:
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def run_evals(config: EvalsConfig) -> None:
|
||||
evals = Evals(config)
|
||||
async def run_evals(config: EvalsConfig, log_dir: Path | None = None) -> None:
|
||||
evals = Evals(config, log_dir)
|
||||
try:
|
||||
await evals.run()
|
||||
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
|
||||
@@ -472,11 +538,9 @@ async def run_evals(config: EvalsConfig) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.entrypoints.evals import main as entrypoint_main
|
||||
|
||||
set_proc_title("Evals")
|
||||
asyncio.run(run_evals(cli(EvalsConfig)))
|
||||
entrypoint_main()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -13,17 +13,21 @@ from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
|
||||
from prime_rl.transports.weights.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
|
||||
size_cuda_buffers,
|
||||
use_cuda_malloc_pool,
|
||||
from prime_rl.transports.weights.nixl.agent import (
|
||||
MemDesc,
|
||||
NixlAgent,
|
||||
NixlPeer,
|
||||
PreparedRead,
|
||||
group_notification,
|
||||
make_agent_name,
|
||||
set_ucx_env_defaults,
|
||||
)
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import use_cuda_malloc_pool
|
||||
from prime_rl.transports.weights.nixl.graph import (
|
||||
Destination,
|
||||
OperationChain,
|
||||
@@ -44,7 +48,6 @@ else:
|
||||
Worker = object
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nixl")
|
||||
_BUFFER_POLL_INTERVAL = 0.01
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -69,13 +72,14 @@ class LayerWeightTransferPlan:
|
||||
class WeightTransferGroup:
|
||||
name: str
|
||||
layers: list[LayerWeightTransferPlan]
|
||||
pulls: list[tuple[Any, Any, list[int]]]
|
||||
pulls: list[PreparedRead]
|
||||
|
||||
|
||||
@dataclass
|
||||
class WeightTransferPlan:
|
||||
receive_arenas: dict[torch.dtype, torch.Tensor]
|
||||
receive_buffer_count: int
|
||||
trainer_peers: list[NixlPeer]
|
||||
groups: list[WeightTransferGroup]
|
||||
|
||||
|
||||
@@ -100,7 +104,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
del inference_world_size, quantize_in_weight_transfer
|
||||
global_rank = rank_offset + self.device.index
|
||||
server_url = f"{host}:{port}"
|
||||
set_ucx_env_defaults()
|
||||
set_ucx_env_defaults(self.device.index)
|
||||
self.nixl_agent = NixlAgent(make_agent_name("inference", global_rank))
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=server_url),
|
||||
@@ -109,6 +113,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
session_id=session_id,
|
||||
worker_id=f"inference-{global_rank}",
|
||||
)
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
self.weight_transfer_timeout = timeout
|
||||
self.weight_transfer_plan: WeightTransferPlan | None = None
|
||||
logger.info(
|
||||
@@ -126,30 +131,13 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
trainer_ref = self.model_express.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=None,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
)[0]
|
||||
table = TrainerTensorTable.decode(self.model_express.fetch(trainer_ref).nixl_metadata)
|
||||
copies = self.trace_weight_loads(table)
|
||||
plan = self.build_transfer_plan(table, copies)
|
||||
self.buffer_sessions = []
|
||||
for buffer_index in range(table.staging_buffer_count):
|
||||
session = ModelExpressSession(
|
||||
client=self.model_express.client,
|
||||
role="inference",
|
||||
rank=self.model_express.rank,
|
||||
session_id=f"{self.model_express.session_id}:layers:{buffer_index}",
|
||||
worker_id=f"inference-buffer-{self.model_express.rank}-{buffer_index}",
|
||||
)
|
||||
session.publish()
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.buffer_sessions.append(session)
|
||||
# Join the current generation directly. Publishing a transient READY
|
||||
# before the first pull would let the trainer mistake initialization
|
||||
# for a completed acknowledgement.
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.weight_transfer_plan = plan
|
||||
self.group_generations = [0] * len(plan.groups)
|
||||
logger.info(
|
||||
"Initialized NIXL transfer plan on rank %d with %d groups",
|
||||
self.model_express.rank,
|
||||
@@ -255,14 +243,16 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
copies,
|
||||
replay_plans,
|
||||
)
|
||||
receive_buffer_count = self.choose_receive_buffer_count(
|
||||
receive_buffer_elements,
|
||||
table.staging_buffer_count,
|
||||
)
|
||||
receive_buffer_count = table.staging_buffer_count
|
||||
receive_arenas = self.allocate_receive_arenas(
|
||||
receive_buffer_elements,
|
||||
receive_buffer_count,
|
||||
)
|
||||
peers: list[NixlPeer] = []
|
||||
for agent in table.agents:
|
||||
peer = self.nixl_agent.add_remote_agent(agent.metadata)
|
||||
self.nixl_agent.make_connection(peer)
|
||||
peers.append(peer)
|
||||
groups = self.build_transfer_groups(
|
||||
table,
|
||||
copies,
|
||||
@@ -270,10 +260,12 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
receive_buffer_elements,
|
||||
receive_arenas,
|
||||
receive_buffer_count,
|
||||
peers,
|
||||
)
|
||||
return WeightTransferPlan(
|
||||
receive_arenas=receive_arenas,
|
||||
receive_buffer_count=receive_buffer_count,
|
||||
trainer_peers=peers,
|
||||
groups=groups,
|
||||
)
|
||||
|
||||
@@ -310,31 +302,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
group_elements[source_dtype][tensor_groups[source.name]] += prod(replay_plans[id(copy)].source_shape)
|
||||
return {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
|
||||
|
||||
def choose_receive_buffer_count(
|
||||
self,
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
staging_buffer_count: int,
|
||||
) -> int:
|
||||
receive_buffer_bytes = max(
|
||||
1,
|
||||
sum(elements * dtype.itemsize for dtype, elements in receive_buffer_elements.items()),
|
||||
)
|
||||
allocated_bytes = torch.cuda.memory_allocated(self.device)
|
||||
peak_growth_bytes = max(
|
||||
0,
|
||||
torch.cuda.max_memory_allocated(self.device) - allocated_bytes,
|
||||
)
|
||||
free_bytes, _ = torch.cuda.mem_get_info(self.device)
|
||||
max_receive_buffers = min(2, staging_buffer_count) if peak_growth_bytes else 1
|
||||
if peak_growth_bytes or free_bytes < receive_buffer_bytes:
|
||||
torch.cuda.empty_cache()
|
||||
return size_cuda_buffers(
|
||||
receive_buffer_bytes,
|
||||
max_receive_buffers,
|
||||
self.device,
|
||||
extra_headroom_bytes=receive_buffer_bytes + peak_growth_bytes,
|
||||
)
|
||||
|
||||
def allocate_receive_arenas(
|
||||
self,
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
@@ -362,6 +329,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
receive_arenas: dict[torch.dtype, torch.Tensor],
|
||||
receive_buffer_count: int,
|
||||
peers: list[NixlPeer],
|
||||
) -> list[WeightTransferGroup]:
|
||||
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
|
||||
tensor_groups = {
|
||||
@@ -390,7 +358,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
)
|
||||
|
||||
agent_devices = {agent_index: agent.device_id for agent_index, agent in enumerate(table.agents)}
|
||||
peer_names: dict[int, str] = {}
|
||||
transfer_groups: list[WeightTransferGroup] = []
|
||||
|
||||
for group_index, group in enumerate(table.groups):
|
||||
@@ -432,10 +399,9 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
persistent_plans_by_layer,
|
||||
),
|
||||
pulls=self.prepare_group_pulls(
|
||||
table,
|
||||
local_descs,
|
||||
remote_descs,
|
||||
peer_names,
|
||||
peers,
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -486,40 +452,37 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
def prepare_group_pulls(
|
||||
self,
|
||||
table: TrainerTensorTable,
|
||||
local_descs: dict[int, list[MemDesc]],
|
||||
remote_descs: dict[int, list[MemDesc]],
|
||||
peer_names: dict[int, str],
|
||||
) -> list[tuple[Any, Any, list[int]]]:
|
||||
pulls: list[tuple[Any, Any, list[int]]] = []
|
||||
for agent_index, remote in sorted(remote_descs.items()):
|
||||
peer_name = peer_names.get(agent_index)
|
||||
if peer_name is None:
|
||||
peer_name = self.nixl_agent.add_remote_agent(table.agents[agent_index].metadata)
|
||||
self.nixl_agent.make_connection(peer_name)
|
||||
peer_names[agent_index] = peer_name
|
||||
peers: list[NixlPeer],
|
||||
) -> list[PreparedRead]:
|
||||
pulls: list[PreparedRead] = []
|
||||
agent_indices = sorted(remote_descs)
|
||||
rotation = self.model_express.rank % len(agent_indices) if agent_indices else 0
|
||||
agent_indices = agent_indices[rotation:] + agent_indices[:rotation]
|
||||
for agent_index in agent_indices:
|
||||
remote = remote_descs[agent_index]
|
||||
peer = peers[agent_index]
|
||||
local_prepared = self.nixl_agent.prepare_xfer_dlist(local_descs[agent_index])
|
||||
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, agent_name=peer_name)
|
||||
pulls.append((local_prepared, remote_prepared, list(range(len(remote)))))
|
||||
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, peer=peer)
|
||||
pulls.append(
|
||||
self.nixl_agent.prepare_read(
|
||||
local_prepared,
|
||||
list(range(len(remote))),
|
||||
remote_prepared,
|
||||
)
|
||||
)
|
||||
return pulls
|
||||
|
||||
@torch.no_grad()
|
||||
def update_weights_from_path(self, weight_dir: str | None = None) -> None:
|
||||
del weight_dir
|
||||
plan = self.initialize_transfer()
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.model_express.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
)
|
||||
|
||||
started = time.perf_counter()
|
||||
self.apply_transfer_plan(plan)
|
||||
update_mla_absorbed_weights(self.raw_model)
|
||||
torch.cuda.synchronize(self.device)
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
logger.info(
|
||||
"Applied NIXL policy update on rank %d in %.2fs",
|
||||
self.model_express.rank,
|
||||
@@ -542,44 +505,30 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
def pull_group(group_index: int) -> WeightTransferGroup:
|
||||
transfer_group = plan.groups[group_index]
|
||||
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
|
||||
session.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
notification = group_notification(group_index, self.group_generations[group_index])
|
||||
self.nixl_agent.wait_for_notification(
|
||||
plan.trainer_peers,
|
||||
notification,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
poll_interval=_BUFFER_POLL_INTERVAL,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
|
||||
for local, remote, indices in transfer_group.pulls:
|
||||
handle = self.nixl_agent.post_read(local, indices, remote)
|
||||
for read in transfer_group.pulls:
|
||||
self.nixl_agent.post_read(read, notification)
|
||||
for read in transfer_group.pulls:
|
||||
self.nixl_agent.wait(
|
||||
handle,
|
||||
read,
|
||||
context=f"weight pull for {transfer_group.name}",
|
||||
timeout=self.weight_transfer_timeout,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
return transfer_group
|
||||
|
||||
def acknowledge_group(group_index: int) -> None:
|
||||
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
session.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
poll_interval=_BUFFER_POLL_INTERVAL,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.group_generations[group_index] += 1
|
||||
return transfer_group
|
||||
|
||||
def prefetch_group(group_index: int) -> WeightTransferGroup:
|
||||
torch.cuda.set_device(self.device)
|
||||
transfer_group = pull_group(group_index)
|
||||
acknowledge_group(group_index)
|
||||
return transfer_group
|
||||
return pull_group(group_index)
|
||||
|
||||
def replay_group(transfer_group: WeightTransferGroup) -> None:
|
||||
for layer_plan in transfer_group.layers:
|
||||
@@ -625,9 +574,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
replay_group(transfer_group)
|
||||
torch.cuda.synchronize(self.device)
|
||||
|
||||
if not pipelined:
|
||||
acknowledge_group(group_index)
|
||||
finally:
|
||||
cancelled.set()
|
||||
if executor is not None:
|
||||
|
||||
@@ -143,6 +143,7 @@ def eval_section(name: str, env_pattern: str) -> ws.Section:
|
||||
return section(
|
||||
name,
|
||||
regexes=[f"eval/{env_pattern}/all/[^/]+/avg@.*", f"eval/{env_pattern}/effective/[^/]+/avg@.*"]
|
||||
+ [f"eval/{env_pattern}/all/cancelled/mean"]
|
||||
+ [f"eval/{env_pattern}/{m}" for m in COMMON_METRICS]
|
||||
+ [f"eval/{env_pattern}/{r}" for r in COMMON_REGEXES],
|
||||
)
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
the weight update) drops train groups already past ``max_off_policy_steps`` — a
|
||||
compute-saving early cancel; the sink's queue sweep is what guarantees the
|
||||
bound. Eval episodes are measurements for the policy version they started
|
||||
with, so they are allowed to finish even if training advances. Train
|
||||
with. Online evals may explicitly cancel them when a newer checkpoint is ready. Train
|
||||
episodes sampled from a frozen model never go stale — their generation
|
||||
source doesn't change with policy updates.
|
||||
"""
|
||||
@@ -702,6 +702,7 @@ class Dispatcher:
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
group_id=str(group_id),
|
||||
step=group.step if group is not None else claimed[-1][1].step,
|
||||
count=cancelled,
|
||||
reason=reason,
|
||||
)
|
||||
@@ -745,6 +746,40 @@ class Dispatcher:
|
||||
await safe_cancel_all(train_tasks)
|
||||
return cancelled
|
||||
|
||||
async def cancel_eval_step(self, step: int) -> int:
|
||||
"""Cancel queued and active eval groups for a superseded checkpoint.
|
||||
|
||||
Scheduling remains paused until ``on_new_version`` runs after the
|
||||
replacement weights are live.
|
||||
"""
|
||||
if self.eval_source is None or self.eval_envs is None:
|
||||
return 0
|
||||
|
||||
self.policy_update_pending = True
|
||||
async with self.scheduling_lock:
|
||||
queued = self.eval_source.cancel_step(step)
|
||||
group_ids = [gid for gid, group in self.groups.items() if group.kind == "eval" and group.step == step]
|
||||
|
||||
cancelled = 0
|
||||
for group_id in group_ids:
|
||||
cancelled += await self.drop_group(group_id, reason="superseded")
|
||||
|
||||
for request in queued:
|
||||
count = self.eval_envs.get(request.env_name).config.group_size
|
||||
cancelled += count
|
||||
self.metrics.record_cancellation(kind="eval", env_name=request.env_name, n=count)
|
||||
await self.out_q.put(
|
||||
GroupCancellation(
|
||||
kind="eval",
|
||||
env_name=request.env_name,
|
||||
group_id=str(uuid.uuid4()),
|
||||
step=request.step,
|
||||
count=count,
|
||||
reason="superseded",
|
||||
)
|
||||
)
|
||||
return cancelled
|
||||
|
||||
# ── metrics ────────────────────────────────────────────────────────────
|
||||
|
||||
def gauges(self) -> dict[str, float]:
|
||||
|
||||
@@ -8,7 +8,7 @@ import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.metrics import EvalEpisodes
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -20,8 +20,10 @@ class EvalSink:
|
||||
self.eval_envs = eval_envs
|
||||
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
|
||||
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
|
||||
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)
|
||||
|
||||
def add(self, episode: vf.Episode) -> EvalBatch | None:
|
||||
env_name = episode_env_name(episode)
|
||||
@@ -50,11 +52,33 @@ class EvalSink:
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
def cancel(self, cancellation: GroupCancellation) -> EvalBatch | None:
|
||||
"""Count a dispatcher-cancelled group toward its superseded eval epoch."""
|
||||
if cancellation.kind != "eval":
|
||||
raise ValueError(f"EvalSink cannot process a {cancellation.kind} group cancellation")
|
||||
group_id = cancellation.group_id
|
||||
bkey = (cancellation.env_name, cancellation.step)
|
||||
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):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
def _group_size(self, group_id: str) -> int:
|
||||
return len(self.pending_groups[group_id]) + len(self.pending_group_failures[group_id])
|
||||
cancellation = self.pending_group_cancellations.get(group_id)
|
||||
return (
|
||||
len(self.pending_groups[group_id])
|
||||
+ len(self.pending_group_failures[group_id])
|
||||
+ (cancellation.count if cancellation is not None else 0)
|
||||
)
|
||||
|
||||
def _batch_size(self, key: tuple[str, int]) -> int:
|
||||
return len(self.pending_batches[key]) + len(self.pending_batch_failures[key])
|
||||
return (
|
||||
len(self.pending_batches[key])
|
||||
+ len(self.pending_batch_failures[key])
|
||||
+ self.pending_batch_cancellations[key]
|
||||
)
|
||||
|
||||
def group_size_for(self, env_name: str) -> int:
|
||||
return self.eval_envs.get(env_name).config.group_size
|
||||
@@ -64,23 +88,32 @@ class EvalSink:
|
||||
return len(env.examples) * env.config.group_size
|
||||
|
||||
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
|
||||
keys = set(self.pending_batches) | set(self.pending_batch_failures)
|
||||
keys = set(self.pending_batches) | set(self.pending_batch_failures) | set(self.pending_batch_cancellations)
|
||||
batch_counts = {key: self._batch_size(key) for key in keys}
|
||||
buffered: dict[tuple[str, int], int] = {}
|
||||
group_ids = set(self.pending_groups) | set(self.pending_group_failures)
|
||||
group_ids = set(self.pending_groups) | set(self.pending_group_failures) | set(self.pending_group_cancellations)
|
||||
for group_id in group_ids:
|
||||
group = self.pending_groups[group_id]
|
||||
failures = self.pending_group_failures[group_id]
|
||||
if not group and not failures:
|
||||
cancellation = self.pending_group_cancellations.get(group_id)
|
||||
if not group and not failures and cancellation is None:
|
||||
continue
|
||||
if group:
|
||||
env_name = episode_env_name(group[0])
|
||||
eval_step = eval_work(group[0]).step
|
||||
else:
|
||||
elif failures:
|
||||
env_name = failures[0].env_name
|
||||
eval_step = failures[0].step
|
||||
else:
|
||||
env_name = cancellation.env_name
|
||||
eval_step = cancellation.step
|
||||
key = (env_name, eval_step)
|
||||
buffered[key] = buffered.get(key, 0) + len(group) + len(failures)
|
||||
buffered[key] = (
|
||||
buffered.get(key, 0)
|
||||
+ len(group)
|
||||
+ len(failures)
|
||||
+ (cancellation.count if cancellation is not None else 0)
|
||||
)
|
||||
return [
|
||||
(
|
||||
env_name,
|
||||
@@ -95,17 +128,23 @@ class EvalSink:
|
||||
def process_group(self, group_id: str) -> None:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
failures = self.pending_group_failures.pop(group_id, [])
|
||||
if not group and not failures:
|
||||
cancellation = self.pending_group_cancellations.pop(group_id, None)
|
||||
if not group and not failures and cancellation is None:
|
||||
return
|
||||
if group:
|
||||
env_name = episode_env_name(group[0])
|
||||
eval_step = eval_work(group[0]).step
|
||||
else:
|
||||
elif failures:
|
||||
env_name = failures[0].env_name
|
||||
eval_step = failures[0].step
|
||||
else:
|
||||
env_name = cancellation.env_name
|
||||
eval_step = cancellation.step
|
||||
key = (env_name, eval_step)
|
||||
self.pending_batches[key].extend(group)
|
||||
self.pending_batch_failures[key].extend(failures)
|
||||
if cancellation is not None:
|
||||
self.pending_batch_cancellations[key] += cancellation.count
|
||||
|
||||
traces = [trace for episode in group for trace in episode.traces]
|
||||
survivors = [trace for trace in traces if not trace.has_error]
|
||||
@@ -116,6 +155,7 @@ class EvalSink:
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} "
|
||||
f"eval_step={eval_step} | episodes={len(group)} dispatch_failures={len(failures)} "
|
||||
f"cancelled={cancellation.count if cancellation is not None else 0} "
|
||||
f"traces={len(traces)} (errored={num_errored + len(failures)}) | reward={avg_reward:.4f}"
|
||||
)
|
||||
|
||||
@@ -123,9 +163,11 @@ class EvalSink:
|
||||
env_name, step = key
|
||||
episodes = self.pending_batches.pop(key, [])
|
||||
failures = self.pending_batch_failures.pop(key, [])
|
||||
cancelled = self.pending_batch_cancellations.pop(key, 0)
|
||||
return EvalBatch(
|
||||
env_name=env_name,
|
||||
step=step,
|
||||
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
|
||||
failures=failures,
|
||||
cancelled=cancelled,
|
||||
)
|
||||
|
||||
@@ -71,6 +71,12 @@ class EvalSource:
|
||||
return None
|
||||
return self.queue.popleft()
|
||||
|
||||
def cancel_step(self, step: int) -> list[TaskRequest]:
|
||||
"""Remove and return queued examples for a superseded eval step."""
|
||||
cancelled = [request for request in self.queue if request.step == step]
|
||||
self.queue = deque(request for request in self.queue if request.step != step)
|
||||
return cancelled
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
return bool(self.queue)
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ class Progress:
|
||||
|
||||
WorkKind = Literal["train", "eval"]
|
||||
|
||||
CancelReason = Literal["stale", "overload"]
|
||||
CancelReason = Literal["stale", "overload", "superseded"]
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -43,11 +43,12 @@ class GroupCancellation:
|
||||
"""Terminal marker for a dropped group: one message covering every episode
|
||||
the group still owed the sink (in-flight and never-dispatched), so
|
||||
count-to-``group_size`` finalization still fires. ``reason`` distinguishes
|
||||
pipeline decisions (staleness, overload cut) from episode errors."""
|
||||
pipeline decisions (staleness, overload cut, superseded eval) from episode errors."""
|
||||
|
||||
kind: WorkKind
|
||||
env_name: str
|
||||
group_id: str
|
||||
step: int
|
||||
count: int
|
||||
reason: CancelReason
|
||||
|
||||
@@ -131,6 +132,7 @@ class EvalBatch:
|
||||
step: int
|
||||
episodes: EvalEpisodes
|
||||
failures: list[DispatchFailure]
|
||||
cancelled: int = 0
|
||||
|
||||
|
||||
class VersionObserver(Protocol):
|
||||
|
||||
@@ -52,13 +52,12 @@ export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
# Per-attempt log dir: a relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
export LOG_DIR={{ log_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
|
||||
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
|
||||
mkdir -p $LOG_DIR/inference
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
# Setup environment
|
||||
|
||||
@@ -59,12 +59,10 @@ export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
export LOG_DIR={{ log_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
|
||||
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
|
||||
mkdir -p $LOG_DIR/trainer $LOG_DIR/inference
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
@@ -140,6 +138,17 @@ export MASTER_ADDR="${HOSTNAMES[$NUM_INFER_NODES]}"
|
||||
export MASTER_PORT=29500
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
echo "MASTER_PORT=${MASTER_PORT}"
|
||||
{% if use_nixl_broadcast -%}
|
||||
{% if launch_modelexpress -%}
|
||||
export WEIGHT_BROADCAST_HOST="$MASTER_ADDR"
|
||||
{% else -%}
|
||||
export WEIGHT_BROADCAST_HOST="{{ modelexpress_host }}"
|
||||
{% endif -%}
|
||||
export MODEL_EXPRESS_PORT={{ modelexpress_port }}
|
||||
export MODEL_EXPRESS_REDIS_PORT={{ modelexpress_redis_port }}
|
||||
echo "WEIGHT_BROADCAST_HOST=${WEIGHT_BROADCAST_HOST}"
|
||||
echo "MODEL_EXPRESS_PORT=${MODEL_EXPRESS_PORT}"
|
||||
{% endif %}
|
||||
|
||||
# The orchestrator runs on trainer rank 0's node (SLURM_PROCID == NUM_INFER_NODES) by
|
||||
# default; with orchestrator_on_inference it moves to the last inference node (a decode
|
||||
@@ -200,6 +209,10 @@ srun bash -s <<'CLEANUP_SH'
|
||||
# the exact process name, so it never hits the worktree path (e.g. mooncake-baby).
|
||||
pkill -9 -x mooncake_master 2>/dev/null
|
||||
pkill -9 -x mooncake_client 2>/dev/null
|
||||
{% if use_nixl_broadcast and launch_modelexpress %}
|
||||
pkill -9 -f "[m]odelexpress-server" 2>/dev/null
|
||||
pkill -9 -x redis-server 2>/dev/null
|
||||
{% endif %}
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
|
||||
@@ -236,6 +249,83 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
|
||||
export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
{% if use_nixl_broadcast -%}
|
||||
UCX_DIR="$PROJECT_DIR/third_party/ucx"
|
||||
if [ ! -x "$UCX_DIR/bin/ucx_info" ]; then
|
||||
echo "NIXL requires the UCX build installed by scripts/install_nixl_from_source.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
export LD_LIBRARY_PATH="$UCX_DIR/lib:$UCX_DIR/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
UCX_TRANSPORTS=$("$UCX_DIR/bin/ucx_info" -d)
|
||||
grep -q "Transport: cuda_copy" <<< "$UCX_TRANSPORTS" || {
|
||||
echo "NIXL requires UCX cuda_copy support" >&2
|
||||
exit 1
|
||||
}
|
||||
grep -q "Transport: rc_verbs" <<< "$UCX_TRANSPORTS" || {
|
||||
echo "NIXL requires UCX rc_verbs support" >&2
|
||||
exit 1
|
||||
}
|
||||
{% if launch_modelexpress %}
|
||||
|
||||
if [ "$SLURM_PROCID" -eq "$NUM_INFER_NODES" ]; then
|
||||
MX_BIN="$PROJECT_DIR/third_party/modelexpress/bin"
|
||||
if [ ! -x "$MX_BIN/modelexpress-server" ] || [ ! -x "$MX_BIN/redis-server" ]; then
|
||||
echo "ModelExpress server dependencies are missing; run scripts/install_modelexpress.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
MX_STATE_DIR="$LOG_DIR/modelexpress"
|
||||
mkdir -p "$MX_STATE_DIR/cache"
|
||||
"$MX_BIN/redis-server" \
|
||||
--port "$MODEL_EXPRESS_REDIS_PORT" \
|
||||
--bind 127.0.0.1 \
|
||||
--protected-mode no \
|
||||
--save "" \
|
||||
--appendonly no \
|
||||
--dir "$MX_STATE_DIR" \
|
||||
> "$MX_STATE_DIR/redis.log" 2>&1 &
|
||||
REDIS_PID=$!
|
||||
trap '[ -z "${MODEL_EXPRESS_PID:-}" ] || kill -TERM "$MODEL_EXPRESS_PID" 2>/dev/null; kill -TERM "$REDIS_PID" 2>/dev/null || true' EXIT
|
||||
|
||||
for _ in $(seq 1 60); do
|
||||
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/$MODEL_EXPRESS_REDIS_PORT" 2>/dev/null && break
|
||||
kill -0 "$REDIS_PID" 2>/dev/null || {
|
||||
tail -50 "$MX_STATE_DIR/redis.log" >&2
|
||||
exit 1
|
||||
}
|
||||
sleep 1
|
||||
done
|
||||
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/$MODEL_EXPRESS_REDIS_PORT" 2>/dev/null || {
|
||||
echo "Redis did not become ready on port $MODEL_EXPRESS_REDIS_PORT" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
MX_METADATA_BACKEND=redis \
|
||||
REDIS_URL="redis://127.0.0.1:$MODEL_EXPRESS_REDIS_PORT" \
|
||||
MX_HEARTBEAT_TIMEOUT_SECS=31536000 \
|
||||
"$MX_BIN/modelexpress-server" \
|
||||
--port "$MODEL_EXPRESS_PORT" \
|
||||
--database-path "$MX_STATE_DIR/models.db" \
|
||||
--cache-directory "$MX_STATE_DIR/cache" \
|
||||
> "$MX_STATE_DIR/server.log" 2>&1 &
|
||||
MODEL_EXPRESS_PID=$!
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
for _ in $(seq 1 120); do
|
||||
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null && break
|
||||
if [ -n "${MODEL_EXPRESS_PID:-}" ] && ! kill -0 "$MODEL_EXPRESS_PID" 2>/dev/null; then
|
||||
tail -50 "$MX_STATE_DIR/server.log" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null || {
|
||||
echo "ModelExpress is not reachable at $WEIGHT_BROADCAST_HOST:$MODEL_EXPRESS_PORT" >&2
|
||||
exit 1
|
||||
}
|
||||
{% endif %}
|
||||
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
|
||||
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
@@ -425,7 +515,8 @@ else
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% if use_nixl_broadcast %}--weight-broadcast.host $WEIGHT_BROADCAST_HOST \
|
||||
{% endif %}{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
@@ -470,6 +561,7 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
|
||||
(
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% elif use_nixl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $WEIGHT_BROADCAST_HOST"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}
|
||||
#SBATCH --nodes={{ num_nodes }}
|
||||
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition={{ partition }}
|
||||
@@ -26,87 +26,111 @@
|
||||
set -e
|
||||
|
||||
# Configs
|
||||
export NUM_NODES={{ num_nodes }}
|
||||
export NUM_TRAIN_NODES={{ num_train_nodes }}
|
||||
export NUM_INFER_NODES={{ num_infer_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
{% if online_eval -%}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
export DP_PER_NODE={{ dp_per_node }}
|
||||
{%- endif %}
|
||||
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export TRAIN_CONFIG_PATH={{ config_path }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
export LOG_DIR={{ log_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
|
||||
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
|
||||
mkdir -p $LOG_DIR/trainer
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
{% if online_eval -%}
|
||||
mkdir -p $LOG_DIR/inference
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
{% endif %}
|
||||
# Clean exits do not trigger srun --kill-on-bad-exit. Each terminal role
|
||||
# publishes its successful exit so every node uses the same completion condition.
|
||||
export TRAINER_DONE=$LAUNCHER_DIR/.sft_trainer_done_$SLURM_JOB_ID
|
||||
{% if online_eval -%}
|
||||
export EVAL_DONE=$LAUNCHER_DIR/.sft_eval_done_$SLURM_JOB_ID
|
||||
{%- endif %}
|
||||
mkdir -p "$LAUNCHER_DIR"
|
||||
rm -f "$TRAINER_DONE"{% if online_eval %} "$EVAL_DONE"{% endif %}
|
||||
|
||||
{% if prl_run_id %}
|
||||
# Trainer and evals (separate SLURM job) log to a single shared W&B run whose id
|
||||
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
|
||||
# outlives the trainer) finalizes it.
|
||||
# Trainer and evals log to one shared W&B run. The trainer creates the run,
|
||||
# and the evals process finalizes it after the final epoch.
|
||||
export PRL_RUN_ID={{ prl_run_id }}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_PRIMARY=trainer
|
||||
export WANDB_SHARED_FINISHER=evals
|
||||
export WANDB_SHARED_LABEL=trainer
|
||||
export WANDB_PROGRAM="uv run sft"
|
||||
{% endif %}
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
echo "HOSTNAMES=${HOSTNAMES[@]}"
|
||||
|
||||
export MASTER_ADDR="${HOSTNAMES[0]}"
|
||||
# Networking. Inference nodes occupy the first ranks, followed by trainer nodes.
|
||||
HOSTNAMES=( $(scontrol show hostnames $SLURM_JOB_NODELIST) )
|
||||
TRAIN_HOSTS=( ${HOSTNAMES[@]:$NUM_INFER_NODES:$NUM_TRAIN_NODES} )
|
||||
export ALL_HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
export MASTER_ADDR="${TRAIN_HOSTS[0]}"
|
||||
export MASTER_PORT=29500
|
||||
echo "HOSTNAMES=${HOSTNAMES[*]}"
|
||||
echo "TRAIN_HOSTS=${TRAIN_HOSTS[*]}"
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
echo "MASTER_PORT=${MASTER_PORT}"
|
||||
{% if use_nccl_broadcast %}
|
||||
# The eval job has a separate allocation. Publish the trainer's NCCL host through
|
||||
# the shared run directory under this job ID.
|
||||
printf '%s\n' "$MASTER_ADDR" > "$LAUNCHER_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
{% endif %}
|
||||
|
||||
{% if online_eval -%}
|
||||
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
|
||||
export HOSTNAMES_STR="${INFER_HOSTS[*]}"
|
||||
INFER_URLS="http://${INFER_HOSTS[0]}:${ROUTER_PORT}/v1"
|
||||
ADMIN_URLS=""
|
||||
ROUTER_ARGS=""
|
||||
for host in ${INFER_HOSTS[@]}; do
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + d))/v1"
|
||||
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
|
||||
done
|
||||
done
|
||||
export INFER_URLS
|
||||
export ADMIN_URLS
|
||||
export ROUTER_ARGS
|
||||
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
|
||||
echo "INFER_URLS=${INFER_URLS}"
|
||||
echo "ADMIN_URLS=${ADMIN_URLS}"
|
||||
{%- endif %}
|
||||
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): run the sync once on
|
||||
# every node. Re-source .env because unexported vars do not cross srun.
|
||||
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
|
||||
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
|
||||
SYNC_SH
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
cd $PROJECT_DIR && uv sync --all-extras --all-packages
|
||||
# Shared venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang. Harmless on clean nodes.
|
||||
#
|
||||
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
|
||||
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
|
||||
# because the surviving literal `vllm` strings below appear in the cmdline.
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python, torchrun, and
|
||||
# vLLM processes can otherwise retain GPUs or IPC files after SLURM termination.
|
||||
srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
sleep 2
|
||||
@@ -116,53 +140,141 @@ srun bash -s <<'CLEANUP_SH'
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
|
||||
# Run SFT
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
# tasks so a single trainer crash terminates the entire SLURM job instead of
|
||||
# leaving the surviving ranks (and their nodes) idle.
|
||||
#
|
||||
# The body goes to bash on stdin through a quoted heredoc instead of a
|
||||
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
|
||||
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
|
||||
# need no escaping. Nothing in the body reads stdin, which would otherwise eat
|
||||
# the rest of the script.
|
||||
# Run trainer and online-eval roles in one SLURM step. A non-zero exit on any
|
||||
# node terminates the other roles. Clean trainer exits let the final eval drain.
|
||||
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
set -o pipefail
|
||||
|
||||
# Setup environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Higher ulimit
|
||||
ulimit -n 65536
|
||||
|
||||
# Infiniband setup
|
||||
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
|
||||
export NCCL_IB_HCA=$IB_HCA
|
||||
IB_HCA=$(ibv_devinfo 2>/dev/null | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" | paste -sd,)
|
||||
[ -n "$IB_HCA" ] && export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
{% if online_eval -%}
|
||||
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
LOCAL_IP=$(hostname -I | awk "{print \$1}")
|
||||
CONFIG_PATH=$CONFIG_DIR/inference.json
|
||||
|
||||
# Inference env vars: launcher defaults + [env_vars] + [inference.env_vars]
|
||||
{%- for key, value in inference_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
{% include '_launch_rank.sh.j2' %}
|
||||
{% include '_launch_router.sh.j2' %}
|
||||
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
|
||||
| tee $LOG_DIR/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
EP={{ "1" if enable_expert_parallel else "0" }}
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
|
||||
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
|
||||
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
|
||||
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
|
||||
else
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$LOG_DIR/inference/router.log"
|
||||
{%- if eval_env_names %}
|
||||
|
||||
mkdir -p $LOG_DIR/envs/eval
|
||||
{%- for name in eval_env_names %}
|
||||
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
|
||||
> $LOG_DIR/envs/eval/{{ name }}.log 2>&1 &
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
# Evals drives inference through the router and sends admin operations
|
||||
# directly to each engine.
|
||||
{%- for key, value in evals_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
(
|
||||
PRL_LOG_DIR=$LOG_DIR WANDB_SHARED_LABEL=evals uv run evals \
|
||||
@ $CONFIG_DIR/evals.json \
|
||||
--eval.client.base-url $INFER_URLS \
|
||||
--eval.client.admin-base-url $ADMIN_URLS \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host $MASTER_ADDR \
|
||||
{%- endif %}
|
||||
2>&1 | tee $LOG_DIR/evals.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ]; then
|
||||
touch "$EVAL_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
fi
|
||||
else
|
||||
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
|
||||
{%- else %}
|
||||
TRAIN_NODE_RANK=$SLURM_PROCID
|
||||
{%- endif %}
|
||||
|
||||
# Trainer env vars: launcher defaults + [env_vars]
|
||||
{%- for key, value in trainer_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
echo $HOSTNAMES | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.sft.train \
|
||||
@ $CONFIG_PATH \
|
||||
echo $ALL_HOSTNAMES_STR | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
(
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.sft.train \
|
||||
@ $TRAIN_CONFIG_PATH \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host 0.0.0.0 \
|
||||
--weight-broadcast.host 0.0.0.0 \
|
||||
{%- endif %}
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
touch "$TRAINER_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
{% if online_eval %}fi{% endif %}
|
||||
|
||||
# Every node stays in the shared srun step until all terminal roles finish.
|
||||
{% if online_eval -%}
|
||||
( until [ -f "$TRAINER_DONE" ] && [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
|
||||
{% else -%}
|
||||
( until [ -f "$TRAINER_DONE" ]; do sleep 10; done ) &
|
||||
{% endif -%}
|
||||
COMPLETION_PID=$!
|
||||
|
||||
# Ignore clean component exits until the shared completion condition is met.
|
||||
# Propagate failures through --kill-on-bad-exit=1.
|
||||
while true; do
|
||||
wait -n -p FINISHED_PID
|
||||
EXIT_CODE=$?
|
||||
if [ "$EXIT_CODE" -ne 0 ] || [ "${FINISHED_PID:-}" = "$COMPLETION_PID" ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
REMAINING_PIDS=$(jobs -p)
|
||||
echo "[$(hostname)] completion condition met with code $EXIT_CODE - terminating remaining processes"
|
||||
for pid in $REMAINING_PIDS; do
|
||||
kill -TERM $pid 2>/dev/null || true
|
||||
done
|
||||
exit $EXIT_CODE
|
||||
LAUNCH_SH
|
||||
|
||||
@@ -1,260 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}-eval
|
||||
#SBATCH --nodes={{ num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
{%- if time %}
|
||||
#SBATCH --time={{ time }}
|
||||
{%- endif %}
|
||||
{%- if nodelist %}
|
||||
#SBATCH --nodelist={{ nodelist }}
|
||||
{%- endif %}
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ launcher_log_dir }}/eval_job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/eval_job_%j.log
|
||||
|
||||
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
|
||||
# DP rank behind a single router) plus the evals process and its env servers. The trainer
|
||||
# runs in a separate SLURM job. This job exits after evaluating the final weight
|
||||
# broadcast (max_steps).
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
set -e
|
||||
|
||||
# Configs
|
||||
export NUM_NODES={{ num_infer_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export CONFIG_PATH=$CONFIG_DIR/inference.json
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Move a previous job's inference logs aside instead of deleting them: rm of log
|
||||
# files another job's processes still hold open can wedge in the NFS client and
|
||||
# hang the whole job before srun even runs.
|
||||
[ -d $OUTPUT_DIR/logs/inference ] && mv $OUTPUT_DIR/logs/inference $OUTPUT_DIR/logs/inference_prev_$(date +%s)
|
||||
mkdir -p $OUTPUT_DIR/logs/inference
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
|
||||
# A clean evals exit cannot trip srun --kill-on-bad-exit (which only propagates
|
||||
# failures), so node 0 publishes completion through this sentinel and the other nodes
|
||||
# watch for it to release their engines.
|
||||
export EVAL_DONE=$LAUNCHER_DIR/.eval.done
|
||||
rm -f "$EVAL_DONE"
|
||||
{% if prl_run_id %}
|
||||
# Trainer (separate SLURM job) and evals log to a single shared W&B run whose id
|
||||
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
|
||||
# outlives the trainer) finalizes it.
|
||||
export PRL_RUN_ID={{ prl_run_id }}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_PRIMARY=trainer
|
||||
export WANDB_SHARED_FINISHER=evals
|
||||
export WANDB_PROGRAM="uv run sft"
|
||||
{% endif %}
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
{% if use_nccl_broadcast %}
|
||||
: "${TRAIN_JOB_ID:?TRAIN_JOB_ID is required for NCCL weight broadcast}"
|
||||
TRAIN_HOST_FILE="$LAUNCHER_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
|
||||
until [ -s "$TRAIN_HOST_FILE" ]; do sleep 1; done
|
||||
export TRAIN_HOST=$(<"$TRAIN_HOST_FILE")
|
||||
rm -f "$TRAIN_HOST_FILE"
|
||||
echo "TRAIN_HOST=${TRAIN_HOST}"
|
||||
{% endif %}
|
||||
|
||||
# Single global router on node 0 fronts every per-rank endpoint; admin ops
|
||||
# (pause/update_weights/resume) bypass it and hit each rank directly.
|
||||
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
ADMIN_URLS=""
|
||||
ROUTER_ARGS=""
|
||||
for host in ${HOSTNAMES[@]}; do
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + d))/v1"
|
||||
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
|
||||
done
|
||||
done
|
||||
export INFER_URLS
|
||||
export ADMIN_URLS
|
||||
export ROUTER_ARGS
|
||||
echo "HOSTNAMES=${HOSTNAMES[@]}"
|
||||
echo "INFER_URLS=${INFER_URLS}"
|
||||
echo "ADMIN_URLS=${ADMIN_URLS}"
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
|
||||
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
|
||||
SYNC_SH
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python/vllm processes and
|
||||
# vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM termination and
|
||||
# cause the next launch to hang. Harmless on clean nodes.
|
||||
#
|
||||
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
|
||||
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
|
||||
# because the surviving literal `vllm` strings below appear in the cmdline.
|
||||
srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|vllm|vllm::" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
|
||||
# Run the eval deployment
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
# tasks so a crashed engine/router/evals terminates the SLURM job instead
|
||||
# of leaving the surviving ranks holding nodes.
|
||||
#
|
||||
# The body goes to bash on stdin through a quoted heredoc instead of a
|
||||
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
|
||||
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
|
||||
# (including in the shared _launch_*.sh.j2 includes) need no escaping. Nothing in
|
||||
# the body reads stdin, which would otherwise eat the rest of the script.
|
||||
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
|
||||
# wait/cleanup block at the end of this script surfaces background
|
||||
# process crashes (router, engines) as task failures.
|
||||
set -o pipefail
|
||||
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
|
||||
# Higher ulimit
|
||||
ulimit -n 65536
|
||||
|
||||
# Infiniband setup
|
||||
IB_HCA=$(ibv_devinfo 2>/dev/null | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" | paste -sd,)
|
||||
[ -n "$IB_HCA" ] && export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
LOCAL_IP=$(hostname -I | awk "{print \$1}")
|
||||
# Inference env vars: launcher defaults + [env_vars] + [inference.env_vars]
|
||||
{%- for key, value in inference_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
{% include '_launch_rank.sh.j2' %}
|
||||
{% include '_launch_router.sh.j2' %}
|
||||
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
|
||||
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
EP={{ "1" if enable_expert_parallel else "0" }}
|
||||
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
|
||||
# each pinned to its TP slice of GPUs. Each node is an independent replica, so any MoE EP
|
||||
# group is node-local (rendezvous on LOCAL_IP); dense models run independent engines.
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
|
||||
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
|
||||
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
|
||||
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
|
||||
else
|
||||
# Dense or single-DP-rank EP (dp=1, e.g. EP within one tp=8 group):
|
||||
# independent single-engine servers. vLLM rejects the external-LB DP
|
||||
# args when data_parallel_size == 1; enable_expert_parallel in the
|
||||
# inference config alone shards experts across the TP group.
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
# Single global router on node 0 (external LB across all per-rank endpoints)
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
{%- if eval_env_names %}
|
||||
|
||||
# One env server per eval source next to the evals process, which connects to each
|
||||
# source at its deterministic loopback address (so this node), polling until
|
||||
# they are up - the servers and the evals process start in parallel.
|
||||
{%- for name in eval_env_names %}
|
||||
mkdir -p $OUTPUT_DIR/logs/envs/eval
|
||||
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
|
||||
> $OUTPUT_DIR/logs/envs/eval/{{ name }}.log 2>&1 &
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
# The evals process watches trainer broadcast markers and drives the pool:
|
||||
# data plane through the router, admin ops per rank.
|
||||
{%- for key, value in evals_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
WANDB_SHARED_LABEL=evals uv run evals \
|
||||
@ $CONFIG_DIR/evals.json \
|
||||
--eval.client.base-url $INFER_URLS \
|
||||
--eval.client.admin-base-url $ADMIN_URLS \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host $TRAIN_HOST \
|
||||
{%- endif %}
|
||||
2>&1 | tee $OUTPUT_DIR/logs/evals.log &
|
||||
EVALS_PID=$!
|
||||
else
|
||||
# Watch for the completion sentinel so this node's wait below returns when
|
||||
# the evals process (on node 0) finishes cleanly.
|
||||
( until [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
|
||||
fi
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
# turns background process crashes (engines, router, env servers, evals)
|
||||
# into task failures that --kill-on-bad-exit=1 can broadcast to the other nodes
|
||||
# so the whole job tears down instead of leaving zombies holding the allocation.
|
||||
wait -n -p FINISHED_PID
|
||||
EXIT_CODE=$?
|
||||
if [ "${FINISHED_PID:-}" = "${EVALS_PID:-none}" ]; then
|
||||
# Publish completion so the sentinel watchers on the other nodes release too
|
||||
# (a zero exit here never trips --kill-on-bad-exit).
|
||||
touch "$EVAL_DONE"
|
||||
fi
|
||||
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
|
||||
for pid in $(jobs -p); do
|
||||
kill -TERM $pid 2>/dev/null || true
|
||||
done
|
||||
exit $EXIT_CODE
|
||||
LAUNCH_SH
|
||||
@@ -26,6 +26,8 @@
|
||||
set -e
|
||||
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR={{ config_dir }}
|
||||
export PRL_ATTEMPT_LOG_DIR={{ log_dir }}
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
@@ -38,4 +40,87 @@ uv sync --all-extras --all-packages
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
|
||||
uv run rl @ {{ config_path }}
|
||||
{% if use_nixl_broadcast %}
|
||||
{% if launch_modelexpress -%}
|
||||
export WEIGHT_BROADCAST_HOST="127.0.0.1"
|
||||
{% else -%}
|
||||
export WEIGHT_BROADCAST_HOST="{{ modelexpress_host }}"
|
||||
{% endif -%}
|
||||
export MODEL_EXPRESS_PORT={{ modelexpress_port }}
|
||||
UCX_DIR="$PROJECT_DIR/third_party/ucx"
|
||||
if [ ! -x "$UCX_DIR/bin/ucx_info" ]; then
|
||||
echo "NIXL requires the UCX build installed by scripts/install_nixl_from_source.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
export LD_LIBRARY_PATH="$UCX_DIR/lib:$UCX_DIR/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
UCX_TRANSPORTS=$("$UCX_DIR/bin/ucx_info" -d)
|
||||
grep -q "Transport: cuda_copy" <<< "$UCX_TRANSPORTS" || {
|
||||
echo "NIXL requires UCX cuda_copy support" >&2
|
||||
exit 1
|
||||
}
|
||||
grep -q "Transport: rc_verbs" <<< "$UCX_TRANSPORTS" || {
|
||||
echo "NIXL requires UCX rc_verbs support" >&2
|
||||
exit 1
|
||||
}
|
||||
{% if launch_modelexpress %}
|
||||
MX_BIN="$PROJECT_DIR/third_party/modelexpress/bin"
|
||||
if [ ! -x "$MX_BIN/modelexpress-server" ] || [ ! -x "$MX_BIN/redis-server" ]; then
|
||||
echo "ModelExpress server dependencies are missing; run scripts/install_modelexpress.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
pkill -9 -f "[m]odelexpress-server" 2>/dev/null || true
|
||||
pkill -9 -x redis-server 2>/dev/null || true
|
||||
|
||||
MX_STATE_DIR="{{ output_dir }}/modelexpress"
|
||||
mkdir -p "$MX_STATE_DIR/cache"
|
||||
"$MX_BIN/redis-server" \
|
||||
--port {{ modelexpress_redis_port }} \
|
||||
--bind 127.0.0.1 \
|
||||
--protected-mode no \
|
||||
--save "" \
|
||||
--appendonly no \
|
||||
--dir "$MX_STATE_DIR" \
|
||||
> "$MX_STATE_DIR/redis.log" 2>&1 &
|
||||
REDIS_PID=$!
|
||||
trap '[ -z "${MODEL_EXPRESS_PID:-}" ] || kill -TERM "$MODEL_EXPRESS_PID" 2>/dev/null; kill -TERM "$REDIS_PID" 2>/dev/null || true' EXIT
|
||||
|
||||
for _ in $(seq 1 60); do
|
||||
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/{{ modelexpress_redis_port }}" 2>/dev/null && break
|
||||
kill -0 "$REDIS_PID" 2>/dev/null || {
|
||||
tail -50 "$MX_STATE_DIR/redis.log" >&2
|
||||
exit 1
|
||||
}
|
||||
sleep 1
|
||||
done
|
||||
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/{{ modelexpress_redis_port }}" 2>/dev/null || {
|
||||
echo "Redis did not become ready on port {{ modelexpress_redis_port }}" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
MX_METADATA_BACKEND=redis \
|
||||
REDIS_URL="redis://127.0.0.1:{{ modelexpress_redis_port }}" \
|
||||
MX_HEARTBEAT_TIMEOUT_SECS=31536000 \
|
||||
"$MX_BIN/modelexpress-server" \
|
||||
--port {{ modelexpress_port }} \
|
||||
--database-path "$MX_STATE_DIR/models.db" \
|
||||
--cache-directory "$MX_STATE_DIR/cache" \
|
||||
> "$MX_STATE_DIR/server.log" 2>&1 &
|
||||
MODEL_EXPRESS_PID=$!
|
||||
{% endif %}
|
||||
|
||||
for _ in $(seq 1 120); do
|
||||
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null && break
|
||||
{% if launch_modelexpress %}
|
||||
kill -0 "$MODEL_EXPRESS_PID" 2>/dev/null || {
|
||||
tail -50 "$MX_STATE_DIR/server.log" >&2
|
||||
exit 1
|
||||
}
|
||||
{% endif %}
|
||||
sleep 1
|
||||
done
|
||||
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null || {
|
||||
echo "ModelExpress is not reachable at $WEIGHT_BROADCAST_HOST:$MODEL_EXPRESS_PORT" >&2
|
||||
exit 1
|
||||
}
|
||||
{% endif %}
|
||||
uv run rl @ {{ config_path }}{% if use_nixl_broadcast %} --weight-broadcast.host "$WEIGHT_BROADCAST_HOST"{% endif %}
|
||||
|
||||
@@ -26,6 +26,8 @@
|
||||
set -e
|
||||
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR={{ config_dir }}
|
||||
export PRL_ATTEMPT_LOG_DIR={{ log_dir }}
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
|
||||
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
|
||||
from jaxtyping import Bool, Float, Int, jaxtyped
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.configs.trainer import CustomLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -106,64 +106,9 @@ def compute_importance_ratio_and_mismatch_kl(
|
||||
return log_importance_ratio, importance_ratio, mismatch_kl
|
||||
|
||||
|
||||
def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossOutputs:
|
||||
"""
|
||||
DPPO+KL loss for RL training, combining:
|
||||
- DPPO-Binary TV Loss (https://arxiv.org/pdf/2602.04879)
|
||||
- Kimi-K2.5 KL Loss (https://arxiv.org/pdf/2602.02276)
|
||||
|
||||
The mask is conditioned on the advantage sign: for positive advantages,
|
||||
we mask tokens whose probability increased too much (trust region violation
|
||||
in the upweight direction); for negative advantages, we mask tokens whose
|
||||
probability decreased too much (trust region violation in the downweight
|
||||
direction).
|
||||
"""
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
|
||||
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
|
||||
dppo_invalid_mask_high = probs_diff > loss_config.dppo_mask_high
|
||||
dppo_invalid_mask_low = probs_diff < -loss_config.dppo_mask_low
|
||||
positive_advantages = advantages > 0
|
||||
negative_advantages = advantages < 0
|
||||
dppo_invalid_mask = torch.where(positive_advantages, dppo_invalid_mask_high, dppo_invalid_mask_low)
|
||||
|
||||
is_masked = dppo_invalid_mask
|
||||
is_masked_high = positive_advantages & dppo_invalid_mask_high
|
||||
is_masked_low = negative_advantages & dppo_invalid_mask_low
|
||||
drop_mask = loss_mask & is_masked
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
loss = per_token_loss.sum()
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
|
||||
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
|
||||
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
|
||||
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
|
||||
"""IPO loss type: a symmetric trust region (mask tokens whose probability
|
||||
moved more than ``ipo_threshold`` in absolute terms), policy gradient via
|
||||
moved more than ``eps`` in absolute terms), policy gradient via
|
||||
the importance ratio, and a squared-log-ratio KL regularizer."""
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
@@ -176,7 +121,7 @@ def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
|
||||
|
||||
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
|
||||
|
||||
is_masked = abs_probs_diff > loss_config.ipo_threshold
|
||||
is_masked = abs_probs_diff > loss_config.eps
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
@@ -261,8 +206,8 @@ def ce_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
|
||||
def setup_rl_loss_fn(loss_config: LossConfig) -> LossFn:
|
||||
"""Build the loss fn for the rl component from ``trainer.loss``:
|
||||
``default_loss_fn`` (``DefaultLossConfig``), ``ipo_loss_fn``
|
||||
(``IPOLossConfig``), or the imported function (``CustomLossConfig``).
|
||||
``ipo_loss_fn`` (``IPOLossConfig``) or the imported function
|
||||
(``CustomLossConfig``).
|
||||
The ce / ref_kl loss types are fixed and unaffected by ``trainer.loss``."""
|
||||
if isinstance(loss_config, CustomLossConfig):
|
||||
custom_fn = import_object(loss_config.import_path)
|
||||
@@ -270,14 +215,10 @@ def setup_rl_loss_fn(loss_config: LossConfig) -> LossFn:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return custom_fn(inputs, **kwargs)
|
||||
elif isinstance(loss_config, IPOLossConfig):
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return ipo_loss_fn(inputs, loss_config)
|
||||
else:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return default_loss_fn(inputs, loss_config)
|
||||
return ipo_loss_fn(inputs, loss_config)
|
||||
|
||||
return rl_fn
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ from typing import Any
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
|
||||
from prime_rl.configs.trainer import IPOLossConfig, TrainerConfig
|
||||
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
@@ -181,7 +181,6 @@ def _compute_export_tensors(
|
||||
|
||||
inference_logprobs = micro_batch["inference_logprobs"].to(trainer_logprobs.device)
|
||||
loss_mask = micro_batch["loss_mask"].to(trainer_logprobs.device)
|
||||
advantages = micro_batch["advantages"].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)
|
||||
@@ -189,15 +188,12 @@ def _compute_export_tensors(
|
||||
fields["importance_ratio"] = ratio
|
||||
fields["mismatch_kl"] = mismatch_kl
|
||||
fields["prob_delta"] = prob_delta
|
||||
if isinstance(loss_config, DefaultLossConfig):
|
||||
invalid_high = prob_delta > loss_config.dppo_mask_high
|
||||
invalid_low = prob_delta < -loss_config.dppo_mask_low
|
||||
positive_advantages = advantages > 0
|
||||
negative_advantages = advantages < 0
|
||||
invalid = torch.where(positive_advantages, invalid_high, invalid_low)
|
||||
fields["is_masked"] = loss_mask & invalid
|
||||
fields["is_masked_high"] = loss_mask & positive_advantages & invalid_high
|
||||
fields["is_masked_low"] = loss_mask & negative_advantages & invalid_low
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -293,10 +293,6 @@ def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) ->
|
||||
skip_prefixes = ("trainer_probs/", "inference_probs/")
|
||||
mean_max_only_prefixes = (
|
||||
"is_masked/",
|
||||
"is_masked_low/",
|
||||
"is_masked_high/",
|
||||
"masked_advantage_positive/",
|
||||
"masked_advantage_negative/",
|
||||
"mismatch_kl/",
|
||||
"masked_mismatch_kl/",
|
||||
"unmasked_mismatch_kl/",
|
||||
|
||||
@@ -5,6 +5,8 @@ from __future__ import annotations
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Sequence
|
||||
|
||||
from torch import Tensor
|
||||
@@ -12,6 +14,23 @@ from torch import Tensor
|
||||
MemDesc = tuple[int, int, int]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class PreparedRead:
|
||||
"""Reusable READ request with descriptor lists kept alive for its lifetime."""
|
||||
|
||||
local_descriptors: Any
|
||||
remote_descriptors: Any
|
||||
handle: Any
|
||||
|
||||
|
||||
def group_notification(group_index: int, generation: int) -> str:
|
||||
return f"{group_index:08x}:{generation:016x}"
|
||||
|
||||
|
||||
def policy_notification(step: int, event: str) -> str:
|
||||
return f"policy:{step:016x}:{event}"
|
||||
|
||||
|
||||
class NixlAgent:
|
||||
def __init__(self, name: str) -> None:
|
||||
try:
|
||||
@@ -21,6 +40,7 @@ class NixlAgent:
|
||||
|
||||
self.name = name
|
||||
self._agent = nixl_agent(name, nixl_agent_config(backends=["UCX"]))
|
||||
self._notifications: dict[str, list[bytes]] = {}
|
||||
|
||||
def register_tensor(self, tensor: Tensor) -> None:
|
||||
self._agent.register_memory(tensor, backends=["UCX"])
|
||||
@@ -28,21 +48,24 @@ class NixlAgent:
|
||||
def get_metadata(self) -> bytes:
|
||||
return self._agent.get_agent_metadata()
|
||||
|
||||
def add_remote_agent(self, metadata: bytes) -> str:
|
||||
return self._agent.add_remote_agent(metadata)
|
||||
def add_remote_agent(self, metadata: bytes) -> NixlPeer:
|
||||
return NixlPeer(
|
||||
local_agent=self,
|
||||
remote_agent_name=self._agent.add_remote_agent(metadata).decode(),
|
||||
)
|
||||
|
||||
def make_connection(self, peer_name: str) -> None:
|
||||
self._agent.make_connection(peer_name)
|
||||
def make_connection(self, peer: NixlPeer) -> None:
|
||||
self._agent.make_connection(peer.remote_agent_name)
|
||||
|
||||
def prepare_xfer_dlist(self, descs: Sequence[MemDesc], agent_name: str | None = None) -> Any:
|
||||
def prepare_xfer_dlist(self, descs: Sequence[MemDesc], peer: NixlPeer | None = None) -> Any:
|
||||
return self._agent.prep_xfer_dlist(
|
||||
agent_name=agent_name or "",
|
||||
agent_name=peer.remote_agent_name if peer is not None else "",
|
||||
xfer_list=list(descs),
|
||||
mem_type="cuda",
|
||||
mem_type="VRAM",
|
||||
backends=["UCX"],
|
||||
)
|
||||
|
||||
def post_read(self, local: Any, indices: Sequence[int], remote: Any) -> Any:
|
||||
def prepare_read(self, local: Any, indices: Sequence[int], remote: Any) -> PreparedRead:
|
||||
handle = self._agent.make_prepped_xfer(
|
||||
operation="READ",
|
||||
local_xfer_side=local,
|
||||
@@ -51,14 +74,49 @@ class NixlAgent:
|
||||
remote_indices=list(indices),
|
||||
backends=["UCX"],
|
||||
)
|
||||
state = self._agent.transfer(handle)
|
||||
return PreparedRead(
|
||||
local_descriptors=local,
|
||||
remote_descriptors=remote,
|
||||
handle=handle,
|
||||
)
|
||||
|
||||
def post_read(self, read: PreparedRead, notification: str) -> None:
|
||||
state = self._agent.transfer(read.handle, notification.encode())
|
||||
if state in ("ERR", "ERROR", "FAIL"):
|
||||
raise RuntimeError(f"NIXL READ post failed with state {state}")
|
||||
return handle
|
||||
|
||||
def send_notification(self, peer: NixlPeer, notification: str) -> None:
|
||||
self._agent.send_notif(peer.remote_agent_name, notification)
|
||||
|
||||
def wait_for_notification(
|
||||
self,
|
||||
peers: Sequence[NixlPeer],
|
||||
notification: str,
|
||||
*,
|
||||
timeout: float,
|
||||
cancelled: Callable[[], bool] | None = None,
|
||||
) -> None:
|
||||
pending = {peer.remote_agent_name for peer in peers}
|
||||
encoded_notification = notification.encode()
|
||||
deadline = time.monotonic() + timeout
|
||||
while pending:
|
||||
if cancelled is not None and cancelled():
|
||||
raise RuntimeError("NIXL notification wait cancelled")
|
||||
for sender, messages in self._agent.get_new_notifs(backends=["UCX"]).items():
|
||||
self._notifications.setdefault(sender, []).extend(messages)
|
||||
for sender in list(pending):
|
||||
messages = self._notifications.get(sender, [])
|
||||
if encoded_notification in messages:
|
||||
messages.remove(encoded_notification)
|
||||
pending.remove(sender)
|
||||
if pending and time.monotonic() >= deadline:
|
||||
raise TimeoutError(f"NIXL notification wait timed out after {timeout}s, missing={sorted(pending)}")
|
||||
if pending:
|
||||
time.sleep(0.0005)
|
||||
|
||||
def wait(
|
||||
self,
|
||||
handle: Any,
|
||||
read: PreparedRead,
|
||||
context: str = "",
|
||||
timeout: float | None = None,
|
||||
cancelled: Callable[[], bool] | None = None,
|
||||
@@ -66,26 +124,84 @@ class NixlAgent:
|
||||
deadline = None if timeout is None else time.monotonic() + timeout
|
||||
while True:
|
||||
if cancelled is not None and cancelled():
|
||||
self._agent.release_xfer_handle(handle)
|
||||
self._agent.release_xfer_handle(read.handle)
|
||||
raise RuntimeError(f"NIXL transfer cancelled, context={context!r}")
|
||||
state = self._agent.check_xfer_state(handle)
|
||||
state = self._agent.check_xfer_state(read.handle)
|
||||
if state in ("DONE", "SUCCESS"):
|
||||
self._agent.release_xfer_handle(handle)
|
||||
return
|
||||
if state in ("ERR", "ERROR", "FAIL"):
|
||||
self._agent.release_xfer_handle(handle)
|
||||
self._agent.release_xfer_handle(read.handle)
|
||||
raise RuntimeError(f"NIXL transfer failed with state={state}, context={context!r}")
|
||||
if deadline is not None and time.monotonic() >= deadline:
|
||||
self._agent.release_xfer_handle(handle)
|
||||
self._agent.release_xfer_handle(read.handle)
|
||||
raise TimeoutError(f"NIXL transfer timed out after {timeout}s, context={context!r}")
|
||||
time.sleep(0.0005)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class NixlPeer:
|
||||
local_agent: NixlAgent
|
||||
remote_agent_name: str
|
||||
|
||||
|
||||
def make_agent_name(role: str, global_rank: int) -> str:
|
||||
return f"{role}-{socket.gethostname()}-r{global_rank}"
|
||||
|
||||
|
||||
def set_ucx_env_defaults() -> None:
|
||||
def set_ucx_env_defaults(device_index: int) -> None:
|
||||
if "UCX_NET_DEVICES" not in os.environ:
|
||||
import pynvml
|
||||
|
||||
visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
|
||||
visible_device = str(device_index)
|
||||
if visible_devices:
|
||||
visible_device = visible_devices.split(",")[device_index].strip()
|
||||
|
||||
pynvml.nvmlInit()
|
||||
try:
|
||||
if visible_device.isdecimal():
|
||||
handle = pynvml.nvmlDeviceGetHandleByIndex(int(visible_device))
|
||||
elif visible_device.startswith("GPU-"):
|
||||
handle = pynvml.nvmlDeviceGetHandleByUUID(visible_device.encode())
|
||||
else:
|
||||
raise RuntimeError(f"Unsupported CUDA_VISIBLE_DEVICES entry for NIXL: {visible_device}")
|
||||
bus_id = pynvml.nvmlDeviceGetPciInfo(handle).busId
|
||||
finally:
|
||||
pynvml.nvmlShutdown()
|
||||
|
||||
if isinstance(bus_id, bytes):
|
||||
bus_id = bus_id.decode()
|
||||
domain, bus, device = bus_id.rsplit(":", 2)
|
||||
gpu_path = Path("/sys/bus/pci/devices") / f"{int(domain, 16):04x}:{bus.lower()}:{device.lower()}"
|
||||
if not gpu_path.exists():
|
||||
raise RuntimeError(f"GPU PCI device is missing from sysfs: {gpu_path}")
|
||||
|
||||
rdma_ports: list[tuple[str, Path]] = []
|
||||
for hca_path in sorted(Path("/sys/class/infiniband").glob("*")):
|
||||
for port_path in sorted((hca_path / "ports").glob("*")):
|
||||
if (port_path / "link_layer").read_text().strip() != "InfiniBand":
|
||||
continue
|
||||
if "ACTIVE" not in (port_path / "state").read_text():
|
||||
continue
|
||||
rdma_ports.append((f"{hca_path.name}:{port_path.name}", (hca_path / "device").resolve()))
|
||||
if not rdma_ports:
|
||||
raise RuntimeError("NIXL requires an active InfiniBand port")
|
||||
|
||||
gpu_parts = gpu_path.resolve().parts
|
||||
ports_by_distance: list[tuple[int, str]] = []
|
||||
for port, device_path in rdma_ports:
|
||||
device_parts = device_path.parts
|
||||
common_parts = 0
|
||||
for gpu_part, device_part in zip(gpu_parts, device_parts):
|
||||
if gpu_part != device_part:
|
||||
break
|
||||
common_parts += 1
|
||||
distance = len(gpu_parts) + len(device_parts) - 2 * common_parts
|
||||
ports_by_distance.append((distance, port))
|
||||
|
||||
os.environ["UCX_NET_DEVICES"] = min(ports_by_distance)[1]
|
||||
os.environ.setdefault("UCX_MAX_RNDV_RAILS", "1")
|
||||
os.environ.setdefault("UCX_MAX_RMA_RAILS", "1")
|
||||
os.environ.setdefault("UCX_TLS", "rc_x,rc,dc_x,dc,cuda_copy")
|
||||
os.environ.setdefault("UCX_IB_GPU_DIRECT_RDMA", "y")
|
||||
os.environ.setdefault("UCX_RNDV_SCHEME", "get_zcopy")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""CUDA memory sizing and a cudaMalloc-backed pool for NIXL arenas."""
|
||||
"""cudaMalloc-backed pool for NIXL arenas."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,17 +19,6 @@ _pool: torch.cuda.MemPool | None = None
|
||||
_allocator: torch.cuda.memory.CUDAPluggableAllocator | None = None
|
||||
|
||||
|
||||
def size_cuda_buffers(
|
||||
buffer_bytes: int,
|
||||
max_buffers: int,
|
||||
device: torch.device,
|
||||
extra_headroom_bytes: int,
|
||||
) -> int:
|
||||
free_bytes, total_bytes = torch.cuda.mem_get_info(device)
|
||||
headroom_bytes = max(4 * 1024**3, int(total_bytes * 0.02)) + extra_headroom_bytes
|
||||
return max(1, min(max_buffers, (free_bytes - headroom_bytes) // buffer_bytes))
|
||||
|
||||
|
||||
def _get_pool() -> torch.cuda.MemPool:
|
||||
global _pool, _allocator
|
||||
if _pool is not None:
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
"""Role-scoped synchronization over ModelExpress.
|
||||
|
||||
The policy session coordinates a complete weight update with the orchestrator.
|
||||
A separate layer session uses the same READY/INITIALIZING handshake to keep a
|
||||
bounded transfer arena live until every inference worker has acknowledged it.
|
||||
"""
|
||||
"""ModelExpress startup discovery for NIXL peers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
import grpc
|
||||
@@ -26,13 +21,6 @@ class ModelExpressSession:
|
||||
rank: int
|
||||
session_id: str
|
||||
worker_id: str
|
||||
_source_id: str | None = field(init=False, default=None, repr=False)
|
||||
|
||||
@property
|
||||
def source_id(self) -> str:
|
||||
if self._source_id is None:
|
||||
raise RuntimeError("ModelExpress metadata must be published before updating status")
|
||||
return self._source_id
|
||||
|
||||
def identity(self, role: Role) -> p2p_pb2.SourceIdentity:
|
||||
return p2p_pb2.SourceIdentity(
|
||||
@@ -65,28 +53,23 @@ class ModelExpressSession:
|
||||
worker_rank=self.rank,
|
||||
nixl_metadata=nixl_metadata,
|
||||
)
|
||||
self._source_id = self._rpc(
|
||||
lambda: self.client.publish_metadata(self.identity(self.role), worker, self.worker_id)
|
||||
return self._rpc(
|
||||
lambda: self.client.publish_metadata(
|
||||
self.identity(self.role),
|
||||
worker,
|
||||
self.worker_id,
|
||||
)
|
||||
)
|
||||
return self._source_id
|
||||
|
||||
def set_status(self, status: int) -> None:
|
||||
if not self._rpc(lambda: self.client.update_status(self.source_id, self.worker_id, self.rank, status)):
|
||||
raise RuntimeError(f"failed to set ModelExpress status {status} for {self.role} rank {self.rank}")
|
||||
|
||||
def list_sources(self, role: Role, status: int | None) -> list[p2p_pb2.SourceInstanceRef]:
|
||||
response = self._rpc(lambda: self.client.list_sources(self.identity(role), status_filter=status))
|
||||
def list_sources(self, role: Role) -> list[p2p_pb2.SourceInstanceRef]:
|
||||
response = self._rpc(lambda: self.client.list_sources(self.identity(role)))
|
||||
return list(response.instances)
|
||||
|
||||
def exists_role_with_status(self, role: Role, status: int) -> bool:
|
||||
return bool(self.list_sources(role, status))
|
||||
|
||||
def wait_for(
|
||||
self,
|
||||
role: Role,
|
||||
*,
|
||||
count: int,
|
||||
status: int | None,
|
||||
timeout: float,
|
||||
poll_interval: float = 0.05,
|
||||
cancelled: Callable[[], bool] | None = None,
|
||||
@@ -96,14 +79,14 @@ class ModelExpressSession:
|
||||
while True:
|
||||
if cancelled is not None and cancelled():
|
||||
raise RuntimeError(f"cancelled waiting for {count} {role} worker(s) in session {self.session_id!r}")
|
||||
refs = self.list_sources(role, status)
|
||||
refs = self.list_sources(role)
|
||||
by_rank = {ref.worker_rank: ref for ref in refs}
|
||||
if expected_ranks.issubset(by_rank):
|
||||
return [by_rank[rank] for rank in range(count)]
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError(
|
||||
f"timed out waiting for {count} {role} worker(s) in session {self.session_id!r} "
|
||||
f"with status={status}; found ranks={sorted(by_rank)}"
|
||||
f"with ranks={sorted(by_rank)}"
|
||||
)
|
||||
time.sleep(poll_interval)
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ from typing import cast
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
|
||||
@@ -25,11 +24,15 @@ from prime_rl.orchestrator.clients import init_nixl_broadcast, update_weights
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
|
||||
from prime_rl.transports.weights.nixl.agent import NixlAgent, make_agent_name, set_ucx_env_defaults
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
|
||||
size_cuda_buffers,
|
||||
use_cuda_malloc_pool,
|
||||
from prime_rl.transports.weights.nixl.agent import (
|
||||
NixlAgent,
|
||||
NixlPeer,
|
||||
group_notification,
|
||||
make_agent_name,
|
||||
policy_notification,
|
||||
set_ucx_env_defaults,
|
||||
)
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import use_cuda_malloc_pool
|
||||
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.transports.weights.nixl.trainer_tensor_table import (
|
||||
TrainerAgent,
|
||||
@@ -40,8 +43,6 @@ from prime_rl.transports.weights.nixl.trainer_tensor_table import (
|
||||
)
|
||||
|
||||
LAYER_RE = re.compile(r"(?:^|\.)layers\.(\d+)(?=\.|$)")
|
||||
BUFFER_POLL_INTERVAL = 0.01
|
||||
MAX_STAGING_BUFFER_COUNT = 8
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -79,7 +80,7 @@ class NIXLWeightSender(WeightSender):
|
||||
self.config = config
|
||||
self.parallel_dims = parallel_dims
|
||||
if self.is_serving_rank:
|
||||
set_ucx_env_defaults()
|
||||
set_ucx_env_defaults(torch.cuda.current_device())
|
||||
self.nixl_agent = NixlAgent(make_agent_name("trainer", self.world.rank))
|
||||
self.initialized = False
|
||||
self.transfer_group_names: list[str] = []
|
||||
@@ -87,8 +88,10 @@ class NIXLWeightSender(WeightSender):
|
||||
self.staged_shards_by_group: dict[int, list[StagedTensorShard]] = {}
|
||||
self.staging_arenas: dict[torch.dtype, torch.Tensor] = {}
|
||||
self.staging_buffer_count: int
|
||||
self.model_express: ModelExpressSession | None = None
|
||||
self.buffer_sessions: list[ModelExpressSession] = []
|
||||
self.inference_peers: list[NixlPeer]
|
||||
self.orchestrator_peer: NixlPeer
|
||||
self.group_generations: list[int]
|
||||
self.broadcast_count = 0
|
||||
|
||||
@property
|
||||
def is_serving_rank(self) -> bool:
|
||||
@@ -184,31 +187,6 @@ class NIXLWeightSender(WeightSender):
|
||||
)
|
||||
return local_shards
|
||||
|
||||
def choose_staging_buffer_count(self, largest_group_bytes: int) -> int:
|
||||
local_buffer_count = min(len(self.transfer_group_names), MAX_STAGING_BUFFER_COUNT)
|
||||
if self.is_serving_rank and largest_group_bytes:
|
||||
device = self.staged_shards[0].source_tensor.device
|
||||
allocated_bytes = torch.cuda.memory_allocated()
|
||||
peak_growth_bytes = max(0, torch.cuda.max_memory_allocated() - allocated_bytes)
|
||||
free_bytes, _ = torch.cuda.mem_get_info(device)
|
||||
max_buffers = local_buffer_count if peak_growth_bytes else 1
|
||||
if peak_growth_bytes or free_bytes < largest_group_bytes:
|
||||
torch.cuda.empty_cache()
|
||||
local_buffer_count = size_cuda_buffers(
|
||||
largest_group_bytes,
|
||||
max_buffers,
|
||||
device,
|
||||
extra_headroom_bytes=peak_growth_bytes,
|
||||
)
|
||||
|
||||
staging_buffer_count = torch.tensor(
|
||||
local_buffer_count,
|
||||
dtype=torch.int64,
|
||||
device=torch.device("cuda", torch.cuda.current_device()),
|
||||
)
|
||||
dist.all_reduce(staging_buffer_count, op=dist.ReduceOp.MIN)
|
||||
return int(staging_buffer_count.item())
|
||||
|
||||
def allocate_staging_arenas(self, largest_group_elements: dict[torch.dtype, int]) -> None:
|
||||
if not self.is_serving_rank or not any(largest_group_elements.values()):
|
||||
return
|
||||
@@ -248,8 +226,10 @@ class NIXLWeightSender(WeightSender):
|
||||
for shard in self.staged_shards:
|
||||
group_elements[shard.wire_dtype][shard.group_index] += shard.source_tensor.numel()
|
||||
largest_group_elements = {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
|
||||
largest_group_bytes = sum(elements * dtype.itemsize for dtype, elements in largest_group_elements.items())
|
||||
self.staging_buffer_count = self.choose_staging_buffer_count(largest_group_bytes)
|
||||
self.staging_buffer_count = min(
|
||||
len(self.transfer_group_names),
|
||||
2 if self.config.overlap_transfer_and_replay else 1,
|
||||
)
|
||||
self.allocate_staging_arenas(largest_group_elements)
|
||||
|
||||
grouped: dict[int, list[StagedTensorShard]] = defaultdict(list)
|
||||
@@ -363,18 +343,6 @@ class NIXLWeightSender(WeightSender):
|
||||
table = self.merge_trainer_table_fragments(table_fragments)
|
||||
server_url = f"{self.config.host}:{self.config.port}"
|
||||
client = MxClient(server_url=server_url)
|
||||
self.buffer_sessions = []
|
||||
for buffer_index in range(self.staging_buffer_count):
|
||||
session = ModelExpressSession(
|
||||
client=client,
|
||||
role="trainer",
|
||||
rank=0,
|
||||
session_id=f"{self.config.session_id}:layers:{buffer_index}",
|
||||
worker_id=f"trainer-buffer-{buffer_index}",
|
||||
)
|
||||
session.publish()
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.buffer_sessions.append(session)
|
||||
self.model_express = ModelExpressSession(
|
||||
client=client,
|
||||
role="trainer",
|
||||
@@ -383,7 +351,6 @@ class NIXLWeightSender(WeightSender):
|
||||
worker_id="trainer-table",
|
||||
)
|
||||
self.model_express.publish(nixl_metadata=table.encode())
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
tensor_count = sum(len(group.tensors) for group in table.groups)
|
||||
self.logger.info(
|
||||
f"Published {tensor_count} trainer tensors in {len(table.groups)} groups "
|
||||
@@ -391,59 +358,75 @@ class NIXLWeightSender(WeightSender):
|
||||
)
|
||||
self.initialized = True
|
||||
|
||||
def finish_staging_buffer_transfer(self, buffer_index: int) -> None:
|
||||
if self.world.is_master:
|
||||
session = self.buffer_sessions[buffer_index]
|
||||
session.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.config.timeout,
|
||||
poll_interval=BUFFER_POLL_INTERVAL,
|
||||
)
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
session.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.config.timeout,
|
||||
poll_interval=BUFFER_POLL_INTERVAL,
|
||||
)
|
||||
dist.barrier()
|
||||
def finish_transfer_group(self, group_index: int) -> None:
|
||||
if not self.is_serving_rank:
|
||||
return
|
||||
notification = group_notification(group_index, self.group_generations[group_index])
|
||||
self.nixl_agent.wait_for_notification(
|
||||
self.inference_peers,
|
||||
notification,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.group_generations[group_index] += 1
|
||||
|
||||
@torch.no_grad()
|
||||
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
|
||||
self.initialize_transfer(model)
|
||||
start = time.perf_counter()
|
||||
|
||||
if self.world.is_master:
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
self.model_express.wait_for(
|
||||
startup = self.broadcast_count == 0
|
||||
if self.world.is_master and startup:
|
||||
orchestrator_ref = self.model_express.wait_for(
|
||||
"orchestrator",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.model_express.wait_for(
|
||||
)[0]
|
||||
inference_refs = self.model_express.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
inference_metadata: list[bytes] | None = [
|
||||
self.model_express.fetch(ref).nixl_metadata for ref in inference_refs
|
||||
]
|
||||
orchestrator_metadata = self.model_express.fetch(orchestrator_ref).nixl_metadata
|
||||
else:
|
||||
inference_metadata = None
|
||||
|
||||
if startup:
|
||||
objects = [inference_metadata]
|
||||
dist.broadcast_object_list(objects, src=0)
|
||||
if self.is_serving_rank:
|
||||
self.inference_peers = []
|
||||
for metadata in cast(list[bytes], objects[0]):
|
||||
peer = self.nixl_agent.add_remote_agent(metadata)
|
||||
self.nixl_agent.make_connection(peer)
|
||||
self.inference_peers.append(peer)
|
||||
self.group_generations = [0] * len(self.transfer_group_names)
|
||||
if self.world.is_master:
|
||||
self.orchestrator_peer = self.nixl_agent.add_remote_agent(orchestrator_metadata)
|
||||
self.nixl_agent.make_connection(self.orchestrator_peer)
|
||||
|
||||
if self.world.is_master:
|
||||
self.nixl_agent.send_notification(
|
||||
self.orchestrator_peer,
|
||||
policy_notification(step, "ready"),
|
||||
)
|
||||
|
||||
for group, group_name in enumerate(self.transfer_group_names):
|
||||
group_start = time.perf_counter()
|
||||
buffer_index = group % self.staging_buffer_count
|
||||
if group >= self.staging_buffer_count:
|
||||
self.finish_staging_buffer_transfer(buffer_index)
|
||||
self.finish_transfer_group(group - self.staging_buffer_count)
|
||||
|
||||
if self.is_serving_rank:
|
||||
for shard in self.staged_shards_by_group.get(group, ()):
|
||||
shard.copy_to_staging()
|
||||
torch.cuda.synchronize()
|
||||
dist.barrier()
|
||||
notification = group_notification(group, self.group_generations[group])
|
||||
for peer in self.inference_peers:
|
||||
self.nixl_agent.send_notification(peer, notification)
|
||||
if self.world.is_master:
|
||||
self.buffer_sessions[buffer_index].set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
self.logger.debug(
|
||||
f"NIXL+ModelExpress policy v{step} group {group_name} staged in buffer {buffer_index} in "
|
||||
f"{time.perf_counter() - group_start:.2f}s"
|
||||
@@ -451,35 +434,28 @@ class NIXLWeightSender(WeightSender):
|
||||
|
||||
first_pending_group = max(0, len(self.transfer_group_names) - self.staging_buffer_count)
|
||||
for group in range(first_pending_group, len(self.transfer_group_names)):
|
||||
buffer_index = group % self.staging_buffer_count
|
||||
self.finish_staging_buffer_transfer(buffer_index)
|
||||
self.finish_transfer_group(group)
|
||||
|
||||
if self.world.is_master:
|
||||
self.model_express.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
self.nixl_agent.wait_for_notification(
|
||||
[self.orchestrator_peer],
|
||||
policy_notification(step, "complete"),
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.model_express.wait_for(
|
||||
"orchestrator",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
dist.barrier()
|
||||
self.broadcast_count += 1
|
||||
self.logger.info(f"NIXL+ModelExpress policy v{step} synchronized in {time.perf_counter() - start:.2f}s")
|
||||
|
||||
|
||||
class NIXLWeightReceiver(WeightReceiver):
|
||||
"""Drives the orchestrator's side of the ModelExpress rendezvous. Version
|
||||
discovery runs on the shared sentinels; the unversioned ModelExpress
|
||||
statuses only choreograph the transfer itself."""
|
||||
"""Drives NIXL discovery and policy synchronization for the orchestrator."""
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self.session = ModelExpressSession(
|
||||
set_ucx_env_defaults(0)
|
||||
self.nixl_agent = NixlAgent(make_agent_name("orchestrator", 0))
|
||||
self.trainer_peer: NixlPeer | None = None
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=f"{self.config.host}:{self.config.port}"),
|
||||
role="orchestrator",
|
||||
rank=0,
|
||||
@@ -496,23 +472,31 @@ class NIXLWeightReceiver(WeightReceiver):
|
||||
self.config.inference_world_size,
|
||||
self.config.session_id,
|
||||
)
|
||||
self.session.publish()
|
||||
await self.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
|
||||
async def set_status(self, status: int) -> None:
|
||||
await asyncio.to_thread(self.session.set_status, status)
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
|
||||
async def receive(self, step: int) -> None:
|
||||
# ACK the trainer (it waits for the orchestrator's READY before the
|
||||
# engines' INITIALIZING), run the transfer, then close the cycle.
|
||||
self._ack(step)
|
||||
await self.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
await update_weights(self.admin_clients, None, step=step)
|
||||
await self.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
if self.trainer_peer is None:
|
||||
trainer_refs = await asyncio.to_thread(
|
||||
self.model_express.wait_for,
|
||||
"trainer",
|
||||
count=1,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
trainer_worker = await asyncio.to_thread(self.model_express.fetch, trainer_refs[0])
|
||||
trainer_table = TrainerTensorTable.decode(trainer_worker.nixl_metadata)
|
||||
self.trainer_peer = self.nixl_agent.add_remote_agent(trainer_table.agents[0].metadata)
|
||||
self.nixl_agent.make_connection(self.trainer_peer)
|
||||
|
||||
trainer_peer = self.trainer_peer
|
||||
await asyncio.to_thread(
|
||||
self.session.wait_for,
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
self.nixl_agent.wait_for_notification,
|
||||
[trainer_peer],
|
||||
policy_notification(step, "ready"),
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
await update_weights(self.admin_clients, None, step=step)
|
||||
self.nixl_agent.send_notification(
|
||||
trainer_peer,
|
||||
policy_notification(step, "complete"),
|
||||
)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import asyncio
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
@@ -12,26 +14,67 @@ def get_log_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "logs"
|
||||
|
||||
|
||||
def create_attempt_log_dir(run_dir: Path) -> Path:
|
||||
"""Create ``logs/attempt_<n>`` for this launch attempt and repoint ``logs/latest`` to it.
|
||||
def _attempt_numbers(parent: Path) -> set[int]:
|
||||
return {
|
||||
int(path.name.removeprefix("attempt_"))
|
||||
for path in parent.glob("attempt_*")
|
||||
if path.name.removeprefix("attempt_").isdigit()
|
||||
}
|
||||
|
||||
Every launch — fresh or resumed — gets its own numbered log directory, so a resume
|
||||
never overwrites an earlier attempt's logs. Returns the attempt directory."""
|
||||
logs_dir = get_log_dir(run_dir)
|
||||
logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
attempts = (
|
||||
int(p.name.removeprefix("attempt_"))
|
||||
for p in logs_dir.glob("attempt_*")
|
||||
if p.name.removeprefix("attempt_").isdigit()
|
||||
)
|
||||
attempt_dir = logs_dir / f"attempt_{1 + max(attempts, default=0)}"
|
||||
attempt_dir.mkdir()
|
||||
# Atomically repoint the relative ``latest`` symlink: create a temp link, then rename.
|
||||
tmp_link = logs_dir / f".{attempt_dir.name}"
|
||||
|
||||
def _point_latest(parent: Path, attempt_dir: Path) -> None:
|
||||
"""Atomically point ``parent/latest`` at a relative attempt directory."""
|
||||
tmp_link = parent / f".{attempt_dir.name}"
|
||||
if tmp_link.is_symlink() or tmp_link.exists():
|
||||
tmp_link.unlink()
|
||||
os.symlink(attempt_dir.name, tmp_link)
|
||||
os.replace(tmp_link, logs_dir / "latest")
|
||||
os.replace(tmp_link, parent / "latest")
|
||||
|
||||
|
||||
def create_attempt_dirs(run_dir: Path) -> tuple[Path, Path]:
|
||||
"""Create matching config and log directories for one launch attempt.
|
||||
|
||||
Returns the concrete resolved-config and log directories. The ``latest``
|
||||
symlink under each artifact root points to the new attempt.
|
||||
"""
|
||||
configs_dir = run_dir / "configs"
|
||||
logs_dir = get_log_dir(run_dir)
|
||||
configs_dir.mkdir(parents=True, exist_ok=True)
|
||||
logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
attempts = _attempt_numbers(configs_dir) | _attempt_numbers(logs_dir)
|
||||
attempt_name = f"attempt_{1 + max(attempts, default=0)}"
|
||||
config_attempt_dir = configs_dir / attempt_name
|
||||
log_dir = logs_dir / attempt_name
|
||||
config_dir = config_attempt_dir / "resolved"
|
||||
config_dir.mkdir(parents=True)
|
||||
log_dir.mkdir()
|
||||
_point_latest(configs_dir, config_attempt_dir)
|
||||
_point_latest(logs_dir, log_dir)
|
||||
return config_dir, log_dir
|
||||
|
||||
|
||||
def prepare_attempt_dirs(run_dir: Path) -> tuple[Path, Path]:
|
||||
"""Reuse a launcher-pinned attempt or allocate a new one."""
|
||||
config_dir = os.environ.get("PRL_ATTEMPT_CONFIG_DIR")
|
||||
log_dir = os.environ.get("PRL_ATTEMPT_LOG_DIR")
|
||||
if config_dir is None and log_dir is None:
|
||||
return create_attempt_dirs(run_dir)
|
||||
if config_dir is None or log_dir is None:
|
||||
raise RuntimeError("PRL_ATTEMPT_CONFIG_DIR and PRL_ATTEMPT_LOG_DIR must be set together")
|
||||
resolved_config_dir = Path(config_dir)
|
||||
attempt_log_dir = Path(log_dir)
|
||||
resolved_config_dir.mkdir(parents=True, exist_ok=True)
|
||||
attempt_log_dir.mkdir(parents=True, exist_ok=True)
|
||||
return resolved_config_dir, attempt_log_dir
|
||||
|
||||
|
||||
def create_attempt_log_dir(run_dir: Path) -> Path:
|
||||
"""Create a log-only attempt for standalone processes without config dumps."""
|
||||
logs_dir = get_log_dir(run_dir)
|
||||
logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
attempt_dir = logs_dir / f"attempt_{1 + max(_attempt_numbers(logs_dir), default=0)}"
|
||||
attempt_dir.mkdir()
|
||||
_point_latest(logs_dir, attempt_dir)
|
||||
return attempt_dir
|
||||
|
||||
|
||||
@@ -104,15 +147,31 @@ CACHE_DIR = home_dir() / ".cache" / "prime-rl"
|
||||
|
||||
|
||||
def get_config_dir(output_dir: Path) -> Path:
|
||||
"""Resolved per-component config dumps (JSON). The launch TOML copy lives one
|
||||
level up, at `configs/<entrypoint>.toml`."""
|
||||
return output_dir / "configs" / "resolved"
|
||||
"""Return the current attempt's resolved config directory.
|
||||
|
||||
The environment override pins child processes to their launch attempt. The
|
||||
legacy path keeps tools compatible with runs created before config attempts.
|
||||
"""
|
||||
if config_dir := os.environ.get("PRL_ATTEMPT_CONFIG_DIR"):
|
||||
return Path(config_dir)
|
||||
configs_dir = output_dir / "configs"
|
||||
latest = configs_dir / "latest" / "resolved"
|
||||
legacy = configs_dir / "resolved"
|
||||
return legacy if legacy.is_dir() and not latest.exists() else latest
|
||||
|
||||
|
||||
def write_launch_toml(run_dir: Path, name: str) -> None:
|
||||
"""Copy the launch `@` TOML file(s) verbatim to `configs/<name>.toml`."""
|
||||
import sys
|
||||
def write_launch_command(config_dir: Path, name: str) -> None:
|
||||
"""Write the user-facing launch command once for a config attempt."""
|
||||
attempt_dir = config_dir.parent
|
||||
attempt_dir.mkdir(parents=True, exist_ok=True)
|
||||
command_path = attempt_dir / "command.txt"
|
||||
if not command_path.exists():
|
||||
command = shlex.join(["uv", "run", name, *sys.argv[1:]])
|
||||
command_path.write_text(f"{command}\n")
|
||||
|
||||
|
||||
def write_launch_toml(config_dir: Path, name: str) -> None:
|
||||
"""Copy the root `@` TOML file(s) to the config attempt."""
|
||||
argv = sys.argv[1:]
|
||||
paths = []
|
||||
for i, arg in enumerate(argv):
|
||||
@@ -124,9 +183,13 @@ def write_launch_toml(run_dir: Path, name: str) -> None:
|
||||
if not tomls:
|
||||
return
|
||||
texts = [text for _, text in tomls] if len(tomls) == 1 else [f"# @ {p}\n{text}" for p, text in tomls]
|
||||
config_dir = run_dir / "configs"
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
(config_dir / f"{name}.toml").write_text("\n".join(texts))
|
||||
(config_dir.parent / f"{name}.toml").write_text("\n".join(texts))
|
||||
|
||||
|
||||
def write_launch_artifacts(config_dir: Path, name: str) -> None:
|
||||
"""Write the user command and launch TOML for a config attempt."""
|
||||
write_launch_command(config_dir, name)
|
||||
write_launch_toml(config_dir, name)
|
||||
|
||||
|
||||
def get_launcher_dir(output_dir: Path) -> Path:
|
||||
@@ -192,7 +255,13 @@ def has_run_artifacts(run_dir: Path) -> bool:
|
||||
if not run_dir.exists():
|
||||
return False
|
||||
launcher_entries = {entry for pattern in LAUNCHER_ARTIFACTS for entry in run_dir.glob(pattern)}
|
||||
return any(entry not in launcher_entries for entry in run_dir.iterdir())
|
||||
for entry in run_dir.iterdir():
|
||||
if entry in launcher_entries:
|
||||
continue
|
||||
if entry.name == "logs" and entry.is_dir() and not any(path.is_file() for path in entry.rglob("*")):
|
||||
continue
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def validate_run_dir(
|
||||
|
||||
@@ -86,7 +86,28 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
|
||||
# resolved concatenated document renders as a tree
|
||||
page.click("#tabs [data-tab=config]")
|
||||
page.wait_for_timeout(1500)
|
||||
assert page.locator("#config-attempt-select").input_value() == "latest"
|
||||
assert page.locator("#config-attempt-select option:checked").inner_text().startswith("latest (attempt ")
|
||||
assert page.eval_on_selector("#config-view", "e => e.innerText.length") > 100, "config view did not render"
|
||||
command = page.locator("#config-command-text").inner_text()
|
||||
assert command.startswith("uv run "), f"launch command did not render: {command!r}"
|
||||
if page.locator("#config-attempt-select option").count() > 2:
|
||||
latest_config = page.locator("#config-view").inner_text()
|
||||
first_attempt = page.locator("#config-attempt-select option").nth(1).get_attribute("value")
|
||||
page.locator("#config-attempt-select").select_option(first_attempt, force=True)
|
||||
page.wait_for_timeout(1000)
|
||||
assert page.locator("#config-attempt-select").input_value() == first_attempt
|
||||
assert page.locator("#config-view").inner_text() != latest_config
|
||||
earlier_command = page.locator("#config-command-text").inner_text()
|
||||
assert earlier_command.startswith("uv run ")
|
||||
assert earlier_command != command, "attempt selector did not change the launch command"
|
||||
page.locator("#config-attempt-select").select_option("latest", force=True)
|
||||
page.wait_for_timeout(1000)
|
||||
assert page.locator("#config-command-text").inner_text() == command
|
||||
page.context.grant_permissions(["clipboard-read", "clipboard-write"], origin=base)
|
||||
page.click("#config-command-copy")
|
||||
page.wait_for_function("document.querySelector('#config-command-copy').classList.contains('copied')")
|
||||
assert page.evaluate("navigator.clipboard.readText()") == command
|
||||
page.click("#config-format [data-fmt=json]")
|
||||
page.wait_for_timeout(1500)
|
||||
assert page.locator("#config-view .j-line").count() > 10, "resolved config tree did not render"
|
||||
@@ -111,6 +132,8 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
|
||||
# logs: the merged pane shows lines
|
||||
page.click("#tabs [data-tab=logs]")
|
||||
page.wait_for_timeout(PAGE_SETTLE_MS)
|
||||
assert page.locator("#attempt-select").input_value() == "latest"
|
||||
assert page.locator("#attempt-select option:checked").inner_text().startswith("latest (attempt ")
|
||||
log_lines = page.locator(".log-pane .ll").count()
|
||||
assert log_lines > 10, f"log pane rendered only {log_lines} lines"
|
||||
|
||||
|
||||
@@ -8,12 +8,12 @@ verifies KL mismatch through the loss pipeline.
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.trainer import DefaultLossConfig
|
||||
from prime_rl.configs.trainer import IPOLossConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
|
||||
from prime_rl.trainer.rl.loss import (
|
||||
LossInputs,
|
||||
default_loss_fn,
|
||||
ipo_loss_fn,
|
||||
selective_log_softmax,
|
||||
shift_tensor_right,
|
||||
)
|
||||
@@ -107,7 +107,7 @@ def test_kl_zero_when_identical():
|
||||
advantages=advantages,
|
||||
loss_mask=loss_mask,
|
||||
)
|
||||
result = default_loss_fn(inputs, DefaultLossConfig())
|
||||
result = ipo_loss_fn(inputs, IPOLossConfig(eps=10.0))
|
||||
|
||||
assert result.metrics["unmasked_mismatch_kl"].item() == pytest.approx(0.0, abs=1e-6), (
|
||||
f"Expected zero KL for identical models, got {result.metrics['unmasked_mismatch_kl'].item()}"
|
||||
@@ -141,7 +141,7 @@ def test_kl_positive_after_perturbation():
|
||||
advantages=advantages,
|
||||
loss_mask=loss_mask,
|
||||
)
|
||||
result = default_loss_fn(inputs, DefaultLossConfig())
|
||||
result = ipo_loss_fn(inputs, IPOLossConfig(eps=10.0))
|
||||
kl = result.metrics["unmasked_mismatch_kl"].item()
|
||||
|
||||
assert kl > 0, f"Expected positive KL after perturbation, got {kl}"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig
|
||||
from prime_rl.configs.trainer import CustomLossConfig, IPOLossConfig
|
||||
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs, compute_entropy, compute_loss, setup_rl_loss_fn
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
@@ -14,7 +14,7 @@ def test_grpo_loss():
|
||||
advantages = [torch.randn(50).cuda(), torch.randn(30).cuda()]
|
||||
loss_mask = [torch.ones(50, dtype=torch.bool).cuda(), torch.ones(30, dtype=torch.bool).cuda()]
|
||||
|
||||
rl_loss_fn = setup_rl_loss_fn(DefaultLossConfig(dppo_mask_high=10.0))
|
||||
rl_loss_fn = setup_rl_loss_fn(IPOLossConfig(eps=10.0))
|
||||
loss, _ = compute_loss(
|
||||
trainer_logprobs,
|
||||
inference_logprobs,
|
||||
@@ -39,7 +39,7 @@ def test_gspo_loss():
|
||||
advantages = [torch.randn(40).cuda(), torch.randn(60).cuda()]
|
||||
loss_mask = [torch.ones(40, dtype=torch.bool).cuda(), torch.ones(60, dtype=torch.bool).cuda()]
|
||||
|
||||
rl_loss_fn = setup_rl_loss_fn(DefaultLossConfig(dppo_mask_high=10.0))
|
||||
rl_loss_fn = setup_rl_loss_fn(IPOLossConfig(eps=10.0))
|
||||
loss, _ = compute_loss(
|
||||
trainer_logprobs,
|
||||
inference_logprobs,
|
||||
@@ -93,7 +93,7 @@ def test_ce_component_matches_masked_nll():
|
||||
rl_weights = [torch.zeros(3, dtype=torch.float32).cuda()]
|
||||
ce_weights = [torch.tensor([1.0, 0.0, 1.0], dtype=torch.float32).cuda()]
|
||||
|
||||
rl_loss_fn = setup_rl_loss_fn(DefaultLossConfig())
|
||||
rl_loss_fn = setup_rl_loss_fn(IPOLossConfig())
|
||||
loss, metrics = compute_loss(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=inference_logprobs,
|
||||
@@ -124,7 +124,7 @@ def test_ce_component_applies_weights():
|
||||
rl_weights = [torch.zeros(3, dtype=torch.float32).cuda()]
|
||||
ce_weights = [torch.tensor([0.1, 0.0, 0.1], dtype=torch.float32).cuda()]
|
||||
|
||||
rl_loss_fn = setup_rl_loss_fn(DefaultLossConfig())
|
||||
rl_loss_fn = setup_rl_loss_fn(IPOLossConfig())
|
||||
loss, _ = compute_loss(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=inference_logprobs,
|
||||
@@ -152,7 +152,7 @@ def test_explicit_rl_weights_match_absent_stream():
|
||||
advantages = [torch.randn(50).cuda()]
|
||||
loss_mask = [torch.rand(50).cuda() > 0.3]
|
||||
|
||||
rl_loss_fn = setup_rl_loss_fn(DefaultLossConfig())
|
||||
rl_loss_fn = setup_rl_loss_fn(IPOLossConfig())
|
||||
kwargs = dict(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=inference_logprobs,
|
||||
@@ -188,7 +188,7 @@ def test_disjoint_components_in_one_sequence():
|
||||
ref_kl_weights = torch.zeros(n, dtype=torch.float32)
|
||||
ref_kl_weights[8:] = 1.0
|
||||
|
||||
rl_loss_fn = setup_rl_loss_fn(DefaultLossConfig(dppo_mask_high=10.0))
|
||||
rl_loss_fn = setup_rl_loss_fn(IPOLossConfig(eps=10.0))
|
||||
loss, metrics = compute_loss(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=inference_logprobs,
|
||||
@@ -220,7 +220,7 @@ def test_empty_components_keep_backward_valid():
|
||||
rl_weights = [torch.zeros(6, dtype=torch.float32).cuda()]
|
||||
ce_weights = [torch.zeros(6, dtype=torch.float32).cuda()]
|
||||
|
||||
rl_loss_fn = setup_rl_loss_fn(DefaultLossConfig())
|
||||
rl_loss_fn = setup_rl_loss_fn(IPOLossConfig())
|
||||
loss, _ = compute_loss(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=inference_logprobs,
|
||||
@@ -254,7 +254,7 @@ def test_overlapping_components_sum():
|
||||
loss_mask = [torch.ones(n, dtype=torch.bool).cuda()]
|
||||
ce_weights = [torch.full((n,), 0.5, dtype=torch.float32).cuda()]
|
||||
|
||||
rl_loss_fn = setup_rl_loss_fn(DefaultLossConfig(dppo_mask_high=10.0))
|
||||
rl_loss_fn = setup_rl_loss_fn(IPOLossConfig(eps=10.0))
|
||||
kwargs = dict(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=inference_logprobs,
|
||||
|
||||
@@ -2,6 +2,7 @@ import pytest
|
||||
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_dirs,
|
||||
get_broadcast_dir,
|
||||
get_rollout_dir,
|
||||
get_step_path,
|
||||
@@ -23,8 +24,13 @@ def test_empty_dir_passes(tmp_path):
|
||||
def test_dir_with_launcher_artifacts_passes(tmp_path):
|
||||
run_dir = tmp_path / "submitted"
|
||||
run_dir.mkdir()
|
||||
(run_dir / "configs").mkdir()
|
||||
(run_dir / "configs" / "trainer.toml").touch()
|
||||
config_dir, log_dir = create_attempt_dirs(run_dir)
|
||||
(config_dir / "trainer.json").touch()
|
||||
next_config_dir, next_log_dir = create_attempt_dirs(run_dir)
|
||||
assert next_config_dir.parent.name == "attempt_2"
|
||||
assert next_log_dir.name == "attempt_2"
|
||||
assert (run_dir / "configs" / "latest").resolve() == next_config_dir.parent
|
||||
assert (run_dir / "logs" / "latest").resolve() == next_log_dir
|
||||
(run_dir / "launcher").mkdir()
|
||||
(run_dir / "launcher" / "rl.sbatch").touch()
|
||||
(run_dir / "launcher" / ".trainer.done").touch()
|
||||
|
||||
@@ -6,7 +6,7 @@ the checkpoint's model state, gather rank-parallel, convert to HF format, and
|
||||
write sharded safetensors plus config/tokenizer assets.
|
||||
|
||||
The model and tokenizer configs are read from the run's resolved config
|
||||
(``<run>/configs/resolved/trainer.json`` or ``sft.json``). LoRA checkpoints are not
|
||||
(``<run>/configs/latest/resolved/trainer.json`` or ``sft.json``). LoRA checkpoints are not
|
||||
supported — the script exports full fine-tunes only.
|
||||
|
||||
Usage (from the prime-rl repo; more ranks = faster gathers and writes, and
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Convert episode traces into a branch-level Hugging Face dataset.
|
||||
|
||||
Train and eval runs save one episode per line in `traces.jsonl`. This tool writes one
|
||||
dataset row for every branch of every agent trace. It does not select or filter rows.
|
||||
|
||||
Each row includes `messages` and JSON-encoded `tools` for SFT. It also includes trace,
|
||||
agent, task, run, outcome, error, timing, and usage metadata. Scalar outcome fields such
|
||||
as `reward`, `stop_condition`, `has_error`, and `is_truncated` stay as top-level columns
|
||||
so later scripts can filter them directly. Metadata with variable schemas stays as JSON.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python tools/convert_traces_to_hf_dataset.py <traces.jsonl> --name <dir-or-repo-id>
|
||||
[--subset default] [--split train] [--public] [--local]
|
||||
|
||||
By default, the tool creates a private Hugging Face Hub repo named `<name>`. Use `--public`
|
||||
to create a public repo. With `--local`, it writes `<name>/<subset>/<split>.parquet` and
|
||||
registers it in `<name>/README.md` instead.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
from datasets import Dataset
|
||||
from pydantic import BaseModel
|
||||
from verifiers.v1 import Trace, WireEpisode
|
||||
from verifiers.v1.dialects.chat import message_to_wire
|
||||
|
||||
|
||||
def jsonable(value: Any) -> Any:
|
||||
if isinstance(value, BaseModel):
|
||||
return value.model_dump(mode="json", exclude_none=True)
|
||||
if isinstance(value, list):
|
||||
return [jsonable(item) for item in value]
|
||||
if isinstance(value, dict):
|
||||
return {key: jsonable(item) for key, item in value.items()}
|
||||
return value
|
||||
|
||||
|
||||
def as_json(value: Any) -> str:
|
||||
return json.dumps(jsonable(value))
|
||||
|
||||
|
||||
def trace_rows(episode: WireEpisode, trace: Trace) -> list[dict]:
|
||||
"""Convert each branch of one trace without selecting or filtering it."""
|
||||
last_error = trace.last_error
|
||||
run = episode.run
|
||||
work = getattr(run, "work", None)
|
||||
policy = getattr(work, "policy", None)
|
||||
common = {
|
||||
"episode_id": episode.id,
|
||||
"episode_ok": episode.ok,
|
||||
"episode_has_error": bool(episode.errors),
|
||||
"episode_errors": as_json(episode.errors),
|
||||
"env_id": episode.env.id,
|
||||
"env_name": episode.env.name,
|
||||
"group_id": episode.group.id if episode.group else None,
|
||||
"run_type": run.type if run else None,
|
||||
"run_id": run.id if run else None,
|
||||
"run_name": run.name if run else None,
|
||||
"work_type": work.type if work else None,
|
||||
"step": getattr(work, "step", None),
|
||||
"policy_start": policy.start if policy else None,
|
||||
"policy_end": policy.end if policy else None,
|
||||
"trace_id": trace.id,
|
||||
"trace_version": trace.version,
|
||||
"verifiers_version": trace.verifiers.version,
|
||||
"verifiers_commit": trace.verifiers.commit,
|
||||
"task_type": trace.task.type,
|
||||
"task_data": as_json(trace.task.data),
|
||||
"task_key": trace.task.key,
|
||||
"task_hash": trace.task.hash,
|
||||
"agent": trace.agent.name,
|
||||
"trainable": trace.agent.trainable,
|
||||
"agent_config": as_json(trace.agent.config),
|
||||
"agent_runtime": as_json(trace.agent.runtime),
|
||||
"tools": as_json(trace.tools),
|
||||
"reward": trace.reward,
|
||||
"rewards": as_json(trace.rewards),
|
||||
"metrics": as_json(trace.metrics),
|
||||
"info": as_json(trace.info),
|
||||
"is_completed": trace.is_completed,
|
||||
"ok": trace.ok,
|
||||
"stop_condition": trace.stop_condition,
|
||||
"has_error": trace.has_error,
|
||||
"error_type": last_error.type if last_error else None,
|
||||
"error_message": last_error.message if last_error else None,
|
||||
"error_status_code": last_error.status_code if last_error else None,
|
||||
"errors": as_json(trace.errors),
|
||||
"is_truncated": trace.is_truncated,
|
||||
"request_rewrites": as_json(trace.request_rewrites),
|
||||
"response_rewrites": as_json(trace.response_rewrites),
|
||||
"extra_usage": as_json(trace.extra_usage),
|
||||
"timing": as_json(trace.timing),
|
||||
"num_branches": trace.num_branches,
|
||||
"num_turns": trace.num_turns,
|
||||
"num_input_tokens": trace.num_input_tokens,
|
||||
"num_output_tokens": trace.num_output_tokens,
|
||||
"num_total_tokens": trace.num_total_tokens,
|
||||
}
|
||||
return [
|
||||
{
|
||||
**common,
|
||||
"branch_index": branch.index,
|
||||
"messages": [message_to_wire(m) for m in branch.messages],
|
||||
"calls": as_json(branch.calls),
|
||||
"branch_num_input_tokens": branch.num_input_tokens,
|
||||
"branch_num_output_tokens": branch.num_output_tokens,
|
||||
"branch_num_total_tokens": branch.num_total_tokens,
|
||||
}
|
||||
for branch in trace.branches
|
||||
]
|
||||
|
||||
|
||||
def register_in_dataset_card(root: Path, subset: str, split: str, rel_path: str) -> None:
|
||||
"""Point the dataset card's `configs` metadata at the parquet, so
|
||||
`load_dataset(root, subset, split=split)` resolves it."""
|
||||
readme = root / "README.md"
|
||||
meta: dict = {}
|
||||
body = ""
|
||||
if readme.exists():
|
||||
text = readme.read_text()
|
||||
lines = text.splitlines(keepends=True)
|
||||
end = next((i for i, line in enumerate(lines[1:], 1) if line.strip() == "---"), None)
|
||||
if lines and lines[0].strip() == "---" and end is not None:
|
||||
header = "".join(lines[1:end])
|
||||
body = "".join(lines[end + 1 :])
|
||||
meta = yaml.safe_load(header) or {}
|
||||
else:
|
||||
body = text
|
||||
configs = meta.setdefault("configs", [])
|
||||
config = next((c for c in configs if c["config_name"] == subset), None)
|
||||
if config is None:
|
||||
config = {"config_name": subset, "data_files": []}
|
||||
configs.append(config)
|
||||
entry = next((e for e in config["data_files"] if e["split"] == split), None)
|
||||
if entry is None:
|
||||
config["data_files"].append({"split": split, "path": rel_path})
|
||||
else:
|
||||
entry["path"] = rel_path
|
||||
text = f"---\n{yaml.safe_dump(meta, sort_keys=False)}---\n{body}"
|
||||
readme.write_text(text if text.endswith("\n") else text + "\n")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("traces", type=Path, help="a run's traces.jsonl (one episode per line)")
|
||||
parser.add_argument("--name", required=True, help="HF repo id, or output dataset dir with --local")
|
||||
parser.add_argument("--subset", default="default", help="dataset config name")
|
||||
parser.add_argument("--split", default="train", help="dataset split name")
|
||||
parser.add_argument("--public", action="store_true", help="make a new Hub dataset public")
|
||||
parser.add_argument("--local", action="store_true", help="write parquet locally instead of pushing")
|
||||
args = parser.parse_args()
|
||||
if args.local and args.public:
|
||||
parser.error("--public cannot be used with --local")
|
||||
|
||||
num_episodes, num_traces, rows = 0, 0, []
|
||||
with args.traces.open(encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if not line.strip():
|
||||
continue
|
||||
num_episodes += 1
|
||||
episode = WireEpisode.model_validate(json.loads(line))
|
||||
for trace in episode.traces:
|
||||
num_traces += 1
|
||||
rows.extend(trace_rows(episode, trace))
|
||||
print(f"traces-to-hf: {num_episodes} episode(s) -> {num_traces} trace(s) -> {len(rows)} branch(es)")
|
||||
if not rows:
|
||||
raise SystemExit("traces-to-hf: no branches found")
|
||||
|
||||
dataset = Dataset.from_list(rows)
|
||||
if not args.local:
|
||||
dataset.push_to_hub(
|
||||
args.name,
|
||||
config_name=args.subset,
|
||||
split=args.split,
|
||||
private=not args.public,
|
||||
)
|
||||
print(
|
||||
f"traces-to-hf: pushed to {args.name} (subset={args.subset}, split={args.split}, private={not args.public})"
|
||||
)
|
||||
return
|
||||
root = Path(args.name)
|
||||
rel_path = f"{args.subset}/{args.split}.parquet"
|
||||
path = root / rel_path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
dataset.to_parquet(str(path))
|
||||
register_in_dataset_card(root, args.subset, args.split, rel_path)
|
||||
print(f"traces-to-hf: wrote {path} (subset={args.subset}, split={args.split})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user