Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc12ef2c66 | ||
|
|
95734aa1dd | ||
|
|
0c58f007bc | ||
|
|
d09bf96dbe | ||
|
|
05967ffcd2 |
+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.
|
||||
|
||||
@@ -231,6 +231,20 @@ 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.
|
||||
|
||||
### Custom Templates
|
||||
|
||||
For unusual partitions, module loads, or environment setup, supply your own Jinja2 template:
|
||||
|
||||
+10
-3
@@ -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,7 +198,7 @@ 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 Trainer and Inference Pool
|
||||
|
||||
@@ -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`):
|
||||
|
||||
@@ -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)``.
|
||||
|
||||
@@ -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):
|
||||
@@ -595,7 +579,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()
|
||||
|
||||
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
|
||||
@@ -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'))"`).
|
||||
@@ -96,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
|
||||
@@ -130,7 +131,7 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
## 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
|
||||
|
||||
|
||||
@@ -11,6 +11,10 @@ the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
|
||||
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
|
||||
|
||||
@@ -408,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()}
|
||||
|
||||
|
||||
|
||||
@@ -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}` })),
|
||||
],
|
||||
@@ -1217,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;
|
||||
}
|
||||
|
||||
@@ -1344,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";
|
||||
@@ -1356,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;
|
||||
@@ -1418,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() {
|
||||
@@ -1431,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 */
|
||||
@@ -1578,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 = "";
|
||||
@@ -1755,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();
|
||||
@@ -3532,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(() => {
|
||||
@@ -3635,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;
|
||||
@@ -4084,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>
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -17,17 +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,
|
||||
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,
|
||||
@@ -141,7 +139,9 @@ 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
|
||||
|
||||
@@ -165,6 +165,8 @@ 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),
|
||||
@@ -199,7 +201,8 @@ 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=get_config_dir(config.run_dir),
|
||||
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),
|
||||
@@ -233,8 +236,8 @@ def sft_slurm(config: SFTConfig):
|
||||
|
||||
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"}
|
||||
@@ -258,12 +261,12 @@ def sft_slurm(config: SFTConfig):
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, script_path, prl_run_id)
|
||||
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,
|
||||
@@ -294,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}")
|
||||
@@ -310,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] = []
|
||||
@@ -409,6 +410,8 @@ 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",
|
||||
|
||||
+75
-15
@@ -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
|
||||
@@ -322,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),
|
||||
@@ -356,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
|
||||
@@ -371,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
|
||||
|
||||
@@ -410,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)
|
||||
@@ -423,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} | "
|
||||
|
||||
@@ -100,7 +100,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),
|
||||
@@ -492,7 +492,11 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
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()):
|
||||
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_name = peer_names.get(agent_index)
|
||||
if peer_name is None:
|
||||
peer_name = self.nixl_agent.add_remote_agent(table.agents[agent_index].metadata)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -42,13 +42,10 @@ 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
|
||||
|
||||
@@ -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,7 @@ from __future__ import annotations
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Sequence
|
||||
|
||||
from torch import Tensor
|
||||
@@ -85,7 +86,60 @@ 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")
|
||||
|
||||
@@ -79,7 +79,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] = []
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user