Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
26af0c49e6 | ||
|
|
fc12ef2c66 | ||
|
|
95734aa1dd |
+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
|
||||
|
||||
|
||||
@@ -231,6 +231,24 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
|
||||
|
||||
### NIXL weight broadcast
|
||||
|
||||
Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transfer. Before the first SLURM run, install the NIXL/UCX build and the ModelExpress service binaries on the shared filesystem:
|
||||
|
||||
```bash
|
||||
bash scripts/install_nixl_from_source.sh
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
|
||||
bash scripts/install_modelexpress.sh
|
||||
```
|
||||
|
||||
The generated job starts a job-scoped ModelExpress server and Redis backend on the trainer head node and passes that address to every component. To use an existing service, set `slurm.launch_modelexpress = false` and configure `weight_broadcast.host` and `weight_broadcast.port`.
|
||||
|
||||
The launcher requires the CUDA and InfiniBand transports from `third_party/ucx`. Each NIXL process selects the active InfiniBand port nearest its GPU; an explicitly configured `UCX_NET_DEVICES` takes precedence. Inference ranks start their pulls at different trainer ranks so concurrent workers distribute traffic across all available source rails.
|
||||
|
||||
ModelExpress exchanges peer metadata during startup. Weight updates reuse prepared NIXL requests, post every trainer-rank read in a transfer group concurrently, and use versioned NIXL notifications for source readiness and buffer credits.
|
||||
|
||||
By default, the trainer and inference worker each allocate one transfer arena. Set `weight_broadcast.overlap_transfer_and_replay = true` to allocate two arenas on both sides and replay one weight group while receiving the next. The additional arena is the size of the largest transfer group per GPU; allocation errors are reported instead of silently disabling overlap.
|
||||
|
||||
### Custom Templates
|
||||
|
||||
For unusual partitions, module loads, or environment setup, supply your own Jinja2 template:
|
||||
|
||||
+1
-1
@@ -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):
|
||||
|
||||
@@ -408,6 +408,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
|
||||
@@ -158,6 +158,9 @@ class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
@@ -490,7 +493,10 @@ class RLConfig(BaseConfig):
|
||||
trainer_config_type = TrainerNCCLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
|
||||
else:
|
||||
transport_config = dict(session_id=self.weight_broadcast.session_id)
|
||||
transport_config = dict(
|
||||
session_id=self.weight_broadcast.session_id,
|
||||
overlap_transfer_and_replay=self.weight_broadcast.overlap_transfer_and_replay,
|
||||
)
|
||||
trainer_config_type = TrainerNIXLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNIXLWeightBroadcastConfig
|
||||
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
|
||||
|
||||
@@ -106,6 +106,9 @@ class SlurmConfig(BaseConfig):
|
||||
pre_run_command: str | None = None
|
||||
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
|
||||
|
||||
launch_modelexpress: bool = True
|
||||
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
|
||||
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
|
||||
|
||||
|
||||
@@ -492,26 +492,10 @@ class CheckpointConfig(BaseConfig):
|
||||
"""Skip loading the optimizer state from checkpoint."""
|
||||
|
||||
|
||||
class DefaultLossConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
dppo_mask_low: float = Field(0.2, ge=0)
|
||||
"""Lower DPPO masking threshold."""
|
||||
|
||||
dppo_mask_high: float = Field(0.2, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(1e-3, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IPOLossConfig(BaseConfig):
|
||||
type: Literal["ipo"] = "ipo"
|
||||
ipo_threshold: float = Field(0.1, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
eps: float = Field(0.1, ge=0)
|
||||
"""Maximum absolute probability change before a token is masked."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
@@ -530,7 +514,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -581,6 +565,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two staging arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
@@ -595,7 +582,7 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
data: DataLoaderConfig = DataLoaderConfig()
|
||||
|
||||
loss: LossConfig = DefaultLossConfig()
|
||||
loss: LossConfig = IPOLossConfig()
|
||||
"""Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this."""
|
||||
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
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"
|
||||
@@ -73,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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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'))"`).
|
||||
|
||||
@@ -454,9 +454,24 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
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,
|
||||
@@ -510,6 +525,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
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(
|
||||
@@ -550,6 +566,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
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)
|
||||
|
||||
@@ -13,17 +13,21 @@ from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
|
||||
from prime_rl.transports.weights.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
|
||||
size_cuda_buffers,
|
||||
use_cuda_malloc_pool,
|
||||
from prime_rl.transports.weights.nixl.agent import (
|
||||
MemDesc,
|
||||
NixlAgent,
|
||||
NixlPeer,
|
||||
PreparedRead,
|
||||
group_notification,
|
||||
make_agent_name,
|
||||
set_ucx_env_defaults,
|
||||
)
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import use_cuda_malloc_pool
|
||||
from prime_rl.transports.weights.nixl.graph import (
|
||||
Destination,
|
||||
OperationChain,
|
||||
@@ -44,7 +48,6 @@ else:
|
||||
Worker = object
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nixl")
|
||||
_BUFFER_POLL_INTERVAL = 0.01
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -69,13 +72,14 @@ class LayerWeightTransferPlan:
|
||||
class WeightTransferGroup:
|
||||
name: str
|
||||
layers: list[LayerWeightTransferPlan]
|
||||
pulls: list[tuple[Any, Any, list[int]]]
|
||||
pulls: list[PreparedRead]
|
||||
|
||||
|
||||
@dataclass
|
||||
class WeightTransferPlan:
|
||||
receive_arenas: dict[torch.dtype, torch.Tensor]
|
||||
receive_buffer_count: int
|
||||
trainer_peers: list[NixlPeer]
|
||||
groups: list[WeightTransferGroup]
|
||||
|
||||
|
||||
@@ -100,7 +104,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
del inference_world_size, quantize_in_weight_transfer
|
||||
global_rank = rank_offset + self.device.index
|
||||
server_url = f"{host}:{port}"
|
||||
set_ucx_env_defaults()
|
||||
set_ucx_env_defaults(self.device.index)
|
||||
self.nixl_agent = NixlAgent(make_agent_name("inference", global_rank))
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=server_url),
|
||||
@@ -109,6 +113,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
session_id=session_id,
|
||||
worker_id=f"inference-{global_rank}",
|
||||
)
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
self.weight_transfer_timeout = timeout
|
||||
self.weight_transfer_plan: WeightTransferPlan | None = None
|
||||
logger.info(
|
||||
@@ -126,30 +131,13 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
trainer_ref = self.model_express.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=None,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
)[0]
|
||||
table = TrainerTensorTable.decode(self.model_express.fetch(trainer_ref).nixl_metadata)
|
||||
copies = self.trace_weight_loads(table)
|
||||
plan = self.build_transfer_plan(table, copies)
|
||||
self.buffer_sessions = []
|
||||
for buffer_index in range(table.staging_buffer_count):
|
||||
session = ModelExpressSession(
|
||||
client=self.model_express.client,
|
||||
role="inference",
|
||||
rank=self.model_express.rank,
|
||||
session_id=f"{self.model_express.session_id}:layers:{buffer_index}",
|
||||
worker_id=f"inference-buffer-{self.model_express.rank}-{buffer_index}",
|
||||
)
|
||||
session.publish()
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.buffer_sessions.append(session)
|
||||
# Join the current generation directly. Publishing a transient READY
|
||||
# before the first pull would let the trainer mistake initialization
|
||||
# for a completed acknowledgement.
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.weight_transfer_plan = plan
|
||||
self.group_generations = [0] * len(plan.groups)
|
||||
logger.info(
|
||||
"Initialized NIXL transfer plan on rank %d with %d groups",
|
||||
self.model_express.rank,
|
||||
@@ -255,14 +243,16 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
copies,
|
||||
replay_plans,
|
||||
)
|
||||
receive_buffer_count = self.choose_receive_buffer_count(
|
||||
receive_buffer_elements,
|
||||
table.staging_buffer_count,
|
||||
)
|
||||
receive_buffer_count = table.staging_buffer_count
|
||||
receive_arenas = self.allocate_receive_arenas(
|
||||
receive_buffer_elements,
|
||||
receive_buffer_count,
|
||||
)
|
||||
peers: list[NixlPeer] = []
|
||||
for agent in table.agents:
|
||||
peer = self.nixl_agent.add_remote_agent(agent.metadata)
|
||||
self.nixl_agent.make_connection(peer)
|
||||
peers.append(peer)
|
||||
groups = self.build_transfer_groups(
|
||||
table,
|
||||
copies,
|
||||
@@ -270,10 +260,12 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
receive_buffer_elements,
|
||||
receive_arenas,
|
||||
receive_buffer_count,
|
||||
peers,
|
||||
)
|
||||
return WeightTransferPlan(
|
||||
receive_arenas=receive_arenas,
|
||||
receive_buffer_count=receive_buffer_count,
|
||||
trainer_peers=peers,
|
||||
groups=groups,
|
||||
)
|
||||
|
||||
@@ -310,31 +302,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
group_elements[source_dtype][tensor_groups[source.name]] += prod(replay_plans[id(copy)].source_shape)
|
||||
return {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
|
||||
|
||||
def choose_receive_buffer_count(
|
||||
self,
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
staging_buffer_count: int,
|
||||
) -> int:
|
||||
receive_buffer_bytes = max(
|
||||
1,
|
||||
sum(elements * dtype.itemsize for dtype, elements in receive_buffer_elements.items()),
|
||||
)
|
||||
allocated_bytes = torch.cuda.memory_allocated(self.device)
|
||||
peak_growth_bytes = max(
|
||||
0,
|
||||
torch.cuda.max_memory_allocated(self.device) - allocated_bytes,
|
||||
)
|
||||
free_bytes, _ = torch.cuda.mem_get_info(self.device)
|
||||
max_receive_buffers = min(2, staging_buffer_count) if peak_growth_bytes else 1
|
||||
if peak_growth_bytes or free_bytes < receive_buffer_bytes:
|
||||
torch.cuda.empty_cache()
|
||||
return size_cuda_buffers(
|
||||
receive_buffer_bytes,
|
||||
max_receive_buffers,
|
||||
self.device,
|
||||
extra_headroom_bytes=receive_buffer_bytes + peak_growth_bytes,
|
||||
)
|
||||
|
||||
def allocate_receive_arenas(
|
||||
self,
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
@@ -362,6 +329,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
receive_arenas: dict[torch.dtype, torch.Tensor],
|
||||
receive_buffer_count: int,
|
||||
peers: list[NixlPeer],
|
||||
) -> list[WeightTransferGroup]:
|
||||
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
|
||||
tensor_groups = {
|
||||
@@ -390,7 +358,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
)
|
||||
|
||||
agent_devices = {agent_index: agent.device_id for agent_index, agent in enumerate(table.agents)}
|
||||
peer_names: dict[int, str] = {}
|
||||
transfer_groups: list[WeightTransferGroup] = []
|
||||
|
||||
for group_index, group in enumerate(table.groups):
|
||||
@@ -432,10 +399,9 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
persistent_plans_by_layer,
|
||||
),
|
||||
pulls=self.prepare_group_pulls(
|
||||
table,
|
||||
local_descs,
|
||||
remote_descs,
|
||||
peer_names,
|
||||
peers,
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -486,40 +452,37 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
def prepare_group_pulls(
|
||||
self,
|
||||
table: TrainerTensorTable,
|
||||
local_descs: dict[int, list[MemDesc]],
|
||||
remote_descs: dict[int, list[MemDesc]],
|
||||
peer_names: dict[int, str],
|
||||
) -> list[tuple[Any, Any, list[int]]]:
|
||||
pulls: list[tuple[Any, Any, list[int]]] = []
|
||||
for agent_index, remote in sorted(remote_descs.items()):
|
||||
peer_name = peer_names.get(agent_index)
|
||||
if peer_name is None:
|
||||
peer_name = self.nixl_agent.add_remote_agent(table.agents[agent_index].metadata)
|
||||
self.nixl_agent.make_connection(peer_name)
|
||||
peer_names[agent_index] = peer_name
|
||||
peers: list[NixlPeer],
|
||||
) -> list[PreparedRead]:
|
||||
pulls: list[PreparedRead] = []
|
||||
agent_indices = sorted(remote_descs)
|
||||
rotation = self.model_express.rank % len(agent_indices) if agent_indices else 0
|
||||
agent_indices = agent_indices[rotation:] + agent_indices[:rotation]
|
||||
for agent_index in agent_indices:
|
||||
remote = remote_descs[agent_index]
|
||||
peer = peers[agent_index]
|
||||
local_prepared = self.nixl_agent.prepare_xfer_dlist(local_descs[agent_index])
|
||||
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, agent_name=peer_name)
|
||||
pulls.append((local_prepared, remote_prepared, list(range(len(remote)))))
|
||||
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, peer=peer)
|
||||
pulls.append(
|
||||
self.nixl_agent.prepare_read(
|
||||
local_prepared,
|
||||
list(range(len(remote))),
|
||||
remote_prepared,
|
||||
)
|
||||
)
|
||||
return pulls
|
||||
|
||||
@torch.no_grad()
|
||||
def update_weights_from_path(self, weight_dir: str | None = None) -> None:
|
||||
del weight_dir
|
||||
plan = self.initialize_transfer()
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.model_express.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
)
|
||||
|
||||
started = time.perf_counter()
|
||||
self.apply_transfer_plan(plan)
|
||||
update_mla_absorbed_weights(self.raw_model)
|
||||
torch.cuda.synchronize(self.device)
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
logger.info(
|
||||
"Applied NIXL policy update on rank %d in %.2fs",
|
||||
self.model_express.rank,
|
||||
@@ -542,44 +505,30 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
def pull_group(group_index: int) -> WeightTransferGroup:
|
||||
transfer_group = plan.groups[group_index]
|
||||
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
|
||||
session.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
notification = group_notification(group_index, self.group_generations[group_index])
|
||||
self.nixl_agent.wait_for_notification(
|
||||
plan.trainer_peers,
|
||||
notification,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
poll_interval=_BUFFER_POLL_INTERVAL,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
|
||||
for local, remote, indices in transfer_group.pulls:
|
||||
handle = self.nixl_agent.post_read(local, indices, remote)
|
||||
for read in transfer_group.pulls:
|
||||
self.nixl_agent.post_read(read, notification)
|
||||
for read in transfer_group.pulls:
|
||||
self.nixl_agent.wait(
|
||||
handle,
|
||||
read,
|
||||
context=f"weight pull for {transfer_group.name}",
|
||||
timeout=self.weight_transfer_timeout,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
return transfer_group
|
||||
|
||||
def acknowledge_group(group_index: int) -> None:
|
||||
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
session.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
poll_interval=_BUFFER_POLL_INTERVAL,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.group_generations[group_index] += 1
|
||||
return transfer_group
|
||||
|
||||
def prefetch_group(group_index: int) -> WeightTransferGroup:
|
||||
torch.cuda.set_device(self.device)
|
||||
transfer_group = pull_group(group_index)
|
||||
acknowledge_group(group_index)
|
||||
return transfer_group
|
||||
return pull_group(group_index)
|
||||
|
||||
def replay_group(transfer_group: WeightTransferGroup) -> None:
|
||||
for layer_plan in transfer_group.layers:
|
||||
@@ -625,9 +574,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
replay_group(transfer_group)
|
||||
torch.cuda.synchronize(self.device)
|
||||
|
||||
if not pipelined:
|
||||
acknowledge_group(group_index)
|
||||
finally:
|
||||
cancelled.set()
|
||||
if executor is not None:
|
||||
|
||||
@@ -138,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
|
||||
@@ -198,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)
|
||||
@@ -234,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
|
||||
@@ -423,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
|
||||
@@ -468,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
|
||||
|
||||
@@ -40,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 %}
|
||||
|
||||
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
|
||||
from jaxtyping import Bool, Float, Int, jaxtyped
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.configs.trainer import CustomLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -106,64 +106,9 @@ def compute_importance_ratio_and_mismatch_kl(
|
||||
return log_importance_ratio, importance_ratio, mismatch_kl
|
||||
|
||||
|
||||
def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossOutputs:
|
||||
"""
|
||||
DPPO+KL loss for RL training, combining:
|
||||
- DPPO-Binary TV Loss (https://arxiv.org/pdf/2602.04879)
|
||||
- Kimi-K2.5 KL Loss (https://arxiv.org/pdf/2602.02276)
|
||||
|
||||
The mask is conditioned on the advantage sign: for positive advantages,
|
||||
we mask tokens whose probability increased too much (trust region violation
|
||||
in the upweight direction); for negative advantages, we mask tokens whose
|
||||
probability decreased too much (trust region violation in the downweight
|
||||
direction).
|
||||
"""
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
|
||||
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
|
||||
dppo_invalid_mask_high = probs_diff > loss_config.dppo_mask_high
|
||||
dppo_invalid_mask_low = probs_diff < -loss_config.dppo_mask_low
|
||||
positive_advantages = advantages > 0
|
||||
negative_advantages = advantages < 0
|
||||
dppo_invalid_mask = torch.where(positive_advantages, dppo_invalid_mask_high, dppo_invalid_mask_low)
|
||||
|
||||
is_masked = dppo_invalid_mask
|
||||
is_masked_high = positive_advantages & dppo_invalid_mask_high
|
||||
is_masked_low = negative_advantages & dppo_invalid_mask_low
|
||||
drop_mask = loss_mask & is_masked
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
loss = per_token_loss.sum()
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
|
||||
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
|
||||
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
|
||||
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
|
||||
"""IPO loss type: a symmetric trust region (mask tokens whose probability
|
||||
moved more than ``ipo_threshold`` in absolute terms), policy gradient via
|
||||
moved more than ``eps`` in absolute terms), policy gradient via
|
||||
the importance ratio, and a squared-log-ratio KL regularizer."""
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
@@ -176,7 +121,7 @@ def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
|
||||
|
||||
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
|
||||
|
||||
is_masked = abs_probs_diff > loss_config.ipo_threshold
|
||||
is_masked = abs_probs_diff > loss_config.eps
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
@@ -261,8 +206,8 @@ def ce_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
|
||||
def setup_rl_loss_fn(loss_config: LossConfig) -> LossFn:
|
||||
"""Build the loss fn for the rl component from ``trainer.loss``:
|
||||
``default_loss_fn`` (``DefaultLossConfig``), ``ipo_loss_fn``
|
||||
(``IPOLossConfig``), or the imported function (``CustomLossConfig``).
|
||||
``ipo_loss_fn`` (``IPOLossConfig``) or the imported function
|
||||
(``CustomLossConfig``).
|
||||
The ce / ref_kl loss types are fixed and unaffected by ``trainer.loss``."""
|
||||
if isinstance(loss_config, CustomLossConfig):
|
||||
custom_fn = import_object(loss_config.import_path)
|
||||
@@ -270,14 +215,10 @@ def setup_rl_loss_fn(loss_config: LossConfig) -> LossFn:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return custom_fn(inputs, **kwargs)
|
||||
elif isinstance(loss_config, IPOLossConfig):
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return ipo_loss_fn(inputs, loss_config)
|
||||
else:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return default_loss_fn(inputs, loss_config)
|
||||
return ipo_loss_fn(inputs, loss_config)
|
||||
|
||||
return rl_fn
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ from typing import Any
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
|
||||
from prime_rl.configs.trainer import IPOLossConfig, TrainerConfig
|
||||
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
@@ -181,7 +181,6 @@ def _compute_export_tensors(
|
||||
|
||||
inference_logprobs = micro_batch["inference_logprobs"].to(trainer_logprobs.device)
|
||||
loss_mask = micro_batch["loss_mask"].to(trainer_logprobs.device)
|
||||
advantages = micro_batch["advantages"].to(trainer_logprobs.device)
|
||||
with torch.no_grad():
|
||||
log_ratio, ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(trainer_logprobs, inference_logprobs)
|
||||
prob_delta = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
|
||||
@@ -189,15 +188,12 @@ def _compute_export_tensors(
|
||||
fields["importance_ratio"] = ratio
|
||||
fields["mismatch_kl"] = mismatch_kl
|
||||
fields["prob_delta"] = prob_delta
|
||||
if isinstance(loss_config, DefaultLossConfig):
|
||||
invalid_high = prob_delta > loss_config.dppo_mask_high
|
||||
invalid_low = prob_delta < -loss_config.dppo_mask_low
|
||||
positive_advantages = advantages > 0
|
||||
negative_advantages = advantages < 0
|
||||
invalid = torch.where(positive_advantages, invalid_high, invalid_low)
|
||||
fields["is_masked"] = loss_mask & invalid
|
||||
fields["is_masked_high"] = loss_mask & positive_advantages & invalid_high
|
||||
fields["is_masked_low"] = loss_mask & negative_advantages & invalid_low
|
||||
if isinstance(loss_config, IPOLossConfig):
|
||||
invalid_high = prob_delta > loss_config.eps
|
||||
invalid_low = prob_delta < -loss_config.eps
|
||||
fields["is_masked"] = loss_mask & (invalid_high | invalid_low)
|
||||
fields["is_masked_high"] = loss_mask & invalid_high
|
||||
fields["is_masked_low"] = loss_mask & invalid_low
|
||||
return fields
|
||||
|
||||
|
||||
|
||||
@@ -293,10 +293,6 @@ def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) ->
|
||||
skip_prefixes = ("trainer_probs/", "inference_probs/")
|
||||
mean_max_only_prefixes = (
|
||||
"is_masked/",
|
||||
"is_masked_low/",
|
||||
"is_masked_high/",
|
||||
"masked_advantage_positive/",
|
||||
"masked_advantage_negative/",
|
||||
"mismatch_kl/",
|
||||
"masked_mismatch_kl/",
|
||||
"unmasked_mismatch_kl/",
|
||||
|
||||
@@ -5,6 +5,8 @@ from __future__ import annotations
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Sequence
|
||||
|
||||
from torch import Tensor
|
||||
@@ -12,6 +14,23 @@ from torch import Tensor
|
||||
MemDesc = tuple[int, int, int]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class PreparedRead:
|
||||
"""Reusable READ request with descriptor lists kept alive for its lifetime."""
|
||||
|
||||
local_descriptors: Any
|
||||
remote_descriptors: Any
|
||||
handle: Any
|
||||
|
||||
|
||||
def group_notification(group_index: int, generation: int) -> str:
|
||||
return f"{group_index:08x}:{generation:016x}"
|
||||
|
||||
|
||||
def policy_notification(step: int, event: str) -> str:
|
||||
return f"policy:{step:016x}:{event}"
|
||||
|
||||
|
||||
class NixlAgent:
|
||||
def __init__(self, name: str) -> None:
|
||||
try:
|
||||
@@ -21,6 +40,7 @@ class NixlAgent:
|
||||
|
||||
self.name = name
|
||||
self._agent = nixl_agent(name, nixl_agent_config(backends=["UCX"]))
|
||||
self._notifications: dict[str, list[bytes]] = {}
|
||||
|
||||
def register_tensor(self, tensor: Tensor) -> None:
|
||||
self._agent.register_memory(tensor, backends=["UCX"])
|
||||
@@ -28,21 +48,24 @@ class NixlAgent:
|
||||
def get_metadata(self) -> bytes:
|
||||
return self._agent.get_agent_metadata()
|
||||
|
||||
def add_remote_agent(self, metadata: bytes) -> str:
|
||||
return self._agent.add_remote_agent(metadata)
|
||||
def add_remote_agent(self, metadata: bytes) -> NixlPeer:
|
||||
return NixlPeer(
|
||||
local_agent=self,
|
||||
remote_agent_name=self._agent.add_remote_agent(metadata).decode(),
|
||||
)
|
||||
|
||||
def make_connection(self, peer_name: str) -> None:
|
||||
self._agent.make_connection(peer_name)
|
||||
def make_connection(self, peer: NixlPeer) -> None:
|
||||
self._agent.make_connection(peer.remote_agent_name)
|
||||
|
||||
def prepare_xfer_dlist(self, descs: Sequence[MemDesc], agent_name: str | None = None) -> Any:
|
||||
def prepare_xfer_dlist(self, descs: Sequence[MemDesc], peer: NixlPeer | None = None) -> Any:
|
||||
return self._agent.prep_xfer_dlist(
|
||||
agent_name=agent_name or "",
|
||||
agent_name=peer.remote_agent_name if peer is not None else "",
|
||||
xfer_list=list(descs),
|
||||
mem_type="cuda",
|
||||
backends=["UCX"],
|
||||
)
|
||||
|
||||
def post_read(self, local: Any, indices: Sequence[int], remote: Any) -> Any:
|
||||
def prepare_read(self, local: Any, indices: Sequence[int], remote: Any) -> PreparedRead:
|
||||
handle = self._agent.make_prepped_xfer(
|
||||
operation="READ",
|
||||
local_xfer_side=local,
|
||||
@@ -51,14 +74,49 @@ class NixlAgent:
|
||||
remote_indices=list(indices),
|
||||
backends=["UCX"],
|
||||
)
|
||||
state = self._agent.transfer(handle)
|
||||
return PreparedRead(
|
||||
local_descriptors=local,
|
||||
remote_descriptors=remote,
|
||||
handle=handle,
|
||||
)
|
||||
|
||||
def post_read(self, read: PreparedRead, notification: str) -> None:
|
||||
state = self._agent.transfer(read.handle, notification.encode())
|
||||
if state in ("ERR", "ERROR", "FAIL"):
|
||||
raise RuntimeError(f"NIXL READ post failed with state {state}")
|
||||
return handle
|
||||
|
||||
def send_notification(self, peer: NixlPeer, notification: str) -> None:
|
||||
self._agent.send_notif(peer.remote_agent_name, notification)
|
||||
|
||||
def wait_for_notification(
|
||||
self,
|
||||
peers: Sequence[NixlPeer],
|
||||
notification: str,
|
||||
*,
|
||||
timeout: float,
|
||||
cancelled: Callable[[], bool] | None = None,
|
||||
) -> None:
|
||||
pending = {peer.remote_agent_name for peer in peers}
|
||||
encoded_notification = notification.encode()
|
||||
deadline = time.monotonic() + timeout
|
||||
while pending:
|
||||
if cancelled is not None and cancelled():
|
||||
raise RuntimeError("NIXL notification wait cancelled")
|
||||
for sender, messages in self._agent.get_new_notifs(backends=["UCX"]).items():
|
||||
self._notifications.setdefault(sender, []).extend(messages)
|
||||
for sender in list(pending):
|
||||
messages = self._notifications.get(sender, [])
|
||||
if encoded_notification in messages:
|
||||
messages.remove(encoded_notification)
|
||||
pending.remove(sender)
|
||||
if pending and time.monotonic() >= deadline:
|
||||
raise TimeoutError(f"NIXL notification wait timed out after {timeout}s, missing={sorted(pending)}")
|
||||
if pending:
|
||||
time.sleep(0.0005)
|
||||
|
||||
def wait(
|
||||
self,
|
||||
handle: Any,
|
||||
read: PreparedRead,
|
||||
context: str = "",
|
||||
timeout: float | None = None,
|
||||
cancelled: Callable[[], bool] | None = None,
|
||||
@@ -66,26 +124,84 @@ class NixlAgent:
|
||||
deadline = None if timeout is None else time.monotonic() + timeout
|
||||
while True:
|
||||
if cancelled is not None and cancelled():
|
||||
self._agent.release_xfer_handle(handle)
|
||||
self._agent.release_xfer_handle(read.handle)
|
||||
raise RuntimeError(f"NIXL transfer cancelled, context={context!r}")
|
||||
state = self._agent.check_xfer_state(handle)
|
||||
state = self._agent.check_xfer_state(read.handle)
|
||||
if state in ("DONE", "SUCCESS"):
|
||||
self._agent.release_xfer_handle(handle)
|
||||
return
|
||||
if state in ("ERR", "ERROR", "FAIL"):
|
||||
self._agent.release_xfer_handle(handle)
|
||||
self._agent.release_xfer_handle(read.handle)
|
||||
raise RuntimeError(f"NIXL transfer failed with state={state}, context={context!r}")
|
||||
if deadline is not None and time.monotonic() >= deadline:
|
||||
self._agent.release_xfer_handle(handle)
|
||||
self._agent.release_xfer_handle(read.handle)
|
||||
raise TimeoutError(f"NIXL transfer timed out after {timeout}s, context={context!r}")
|
||||
time.sleep(0.0005)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class NixlPeer:
|
||||
local_agent: NixlAgent
|
||||
remote_agent_name: str
|
||||
|
||||
|
||||
def make_agent_name(role: str, global_rank: int) -> str:
|
||||
return f"{role}-{socket.gethostname()}-r{global_rank}"
|
||||
|
||||
|
||||
def set_ucx_env_defaults() -> None:
|
||||
def set_ucx_env_defaults(device_index: int) -> None:
|
||||
if "UCX_NET_DEVICES" not in os.environ:
|
||||
import pynvml
|
||||
|
||||
visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
|
||||
visible_device = str(device_index)
|
||||
if visible_devices:
|
||||
visible_device = visible_devices.split(",")[device_index].strip()
|
||||
|
||||
pynvml.nvmlInit()
|
||||
try:
|
||||
if visible_device.isdecimal():
|
||||
handle = pynvml.nvmlDeviceGetHandleByIndex(int(visible_device))
|
||||
elif visible_device.startswith("GPU-"):
|
||||
handle = pynvml.nvmlDeviceGetHandleByUUID(visible_device.encode())
|
||||
else:
|
||||
raise RuntimeError(f"Unsupported CUDA_VISIBLE_DEVICES entry for NIXL: {visible_device}")
|
||||
bus_id = pynvml.nvmlDeviceGetPciInfo(handle).busId
|
||||
finally:
|
||||
pynvml.nvmlShutdown()
|
||||
|
||||
if isinstance(bus_id, bytes):
|
||||
bus_id = bus_id.decode()
|
||||
domain, bus, device = bus_id.rsplit(":", 2)
|
||||
gpu_path = Path("/sys/bus/pci/devices") / f"{int(domain, 16):04x}:{bus.lower()}:{device.lower()}"
|
||||
if not gpu_path.exists():
|
||||
raise RuntimeError(f"GPU PCI device is missing from sysfs: {gpu_path}")
|
||||
|
||||
rdma_ports: list[tuple[str, Path]] = []
|
||||
for hca_path in sorted(Path("/sys/class/infiniband").glob("*")):
|
||||
for port_path in sorted((hca_path / "ports").glob("*")):
|
||||
if (port_path / "link_layer").read_text().strip() != "InfiniBand":
|
||||
continue
|
||||
if "ACTIVE" not in (port_path / "state").read_text():
|
||||
continue
|
||||
rdma_ports.append((f"{hca_path.name}:{port_path.name}", (hca_path / "device").resolve()))
|
||||
if not rdma_ports:
|
||||
raise RuntimeError("NIXL requires an active InfiniBand port")
|
||||
|
||||
gpu_parts = gpu_path.resolve().parts
|
||||
ports_by_distance: list[tuple[int, str]] = []
|
||||
for port, device_path in rdma_ports:
|
||||
device_parts = device_path.parts
|
||||
common_parts = 0
|
||||
for gpu_part, device_part in zip(gpu_parts, device_parts):
|
||||
if gpu_part != device_part:
|
||||
break
|
||||
common_parts += 1
|
||||
distance = len(gpu_parts) + len(device_parts) - 2 * common_parts
|
||||
ports_by_distance.append((distance, port))
|
||||
|
||||
os.environ["UCX_NET_DEVICES"] = min(ports_by_distance)[1]
|
||||
os.environ.setdefault("UCX_MAX_RNDV_RAILS", "1")
|
||||
os.environ.setdefault("UCX_MAX_RMA_RAILS", "1")
|
||||
os.environ.setdefault("UCX_TLS", "rc_x,rc,dc_x,dc,cuda_copy")
|
||||
os.environ.setdefault("UCX_IB_GPU_DIRECT_RDMA", "y")
|
||||
os.environ.setdefault("UCX_RNDV_SCHEME", "get_zcopy")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""CUDA memory sizing and a cudaMalloc-backed pool for NIXL arenas."""
|
||||
"""cudaMalloc-backed pool for NIXL arenas."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,17 +19,6 @@ _pool: torch.cuda.MemPool | None = None
|
||||
_allocator: torch.cuda.memory.CUDAPluggableAllocator | None = None
|
||||
|
||||
|
||||
def size_cuda_buffers(
|
||||
buffer_bytes: int,
|
||||
max_buffers: int,
|
||||
device: torch.device,
|
||||
extra_headroom_bytes: int,
|
||||
) -> int:
|
||||
free_bytes, total_bytes = torch.cuda.mem_get_info(device)
|
||||
headroom_bytes = max(4 * 1024**3, int(total_bytes * 0.02)) + extra_headroom_bytes
|
||||
return max(1, min(max_buffers, (free_bytes - headroom_bytes) // buffer_bytes))
|
||||
|
||||
|
||||
def _get_pool() -> torch.cuda.MemPool:
|
||||
global _pool, _allocator
|
||||
if _pool is not None:
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
"""Role-scoped synchronization over ModelExpress.
|
||||
|
||||
The policy session coordinates a complete weight update with the orchestrator.
|
||||
A separate layer session uses the same READY/INITIALIZING handshake to keep a
|
||||
bounded transfer arena live until every inference worker has acknowledged it.
|
||||
"""
|
||||
"""ModelExpress startup discovery for NIXL peers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
import grpc
|
||||
@@ -26,13 +21,6 @@ class ModelExpressSession:
|
||||
rank: int
|
||||
session_id: str
|
||||
worker_id: str
|
||||
_source_id: str | None = field(init=False, default=None, repr=False)
|
||||
|
||||
@property
|
||||
def source_id(self) -> str:
|
||||
if self._source_id is None:
|
||||
raise RuntimeError("ModelExpress metadata must be published before updating status")
|
||||
return self._source_id
|
||||
|
||||
def identity(self, role: Role) -> p2p_pb2.SourceIdentity:
|
||||
return p2p_pb2.SourceIdentity(
|
||||
@@ -65,28 +53,23 @@ class ModelExpressSession:
|
||||
worker_rank=self.rank,
|
||||
nixl_metadata=nixl_metadata,
|
||||
)
|
||||
self._source_id = self._rpc(
|
||||
lambda: self.client.publish_metadata(self.identity(self.role), worker, self.worker_id)
|
||||
return self._rpc(
|
||||
lambda: self.client.publish_metadata(
|
||||
self.identity(self.role),
|
||||
worker,
|
||||
self.worker_id,
|
||||
)
|
||||
)
|
||||
return self._source_id
|
||||
|
||||
def set_status(self, status: int) -> None:
|
||||
if not self._rpc(lambda: self.client.update_status(self.source_id, self.worker_id, self.rank, status)):
|
||||
raise RuntimeError(f"failed to set ModelExpress status {status} for {self.role} rank {self.rank}")
|
||||
|
||||
def list_sources(self, role: Role, status: int | None) -> list[p2p_pb2.SourceInstanceRef]:
|
||||
response = self._rpc(lambda: self.client.list_sources(self.identity(role), status_filter=status))
|
||||
def list_sources(self, role: Role) -> list[p2p_pb2.SourceInstanceRef]:
|
||||
response = self._rpc(lambda: self.client.list_sources(self.identity(role)))
|
||||
return list(response.instances)
|
||||
|
||||
def exists_role_with_status(self, role: Role, status: int) -> bool:
|
||||
return bool(self.list_sources(role, status))
|
||||
|
||||
def wait_for(
|
||||
self,
|
||||
role: Role,
|
||||
*,
|
||||
count: int,
|
||||
status: int | None,
|
||||
timeout: float,
|
||||
poll_interval: float = 0.05,
|
||||
cancelled: Callable[[], bool] | None = None,
|
||||
@@ -96,14 +79,14 @@ class ModelExpressSession:
|
||||
while True:
|
||||
if cancelled is not None and cancelled():
|
||||
raise RuntimeError(f"cancelled waiting for {count} {role} worker(s) in session {self.session_id!r}")
|
||||
refs = self.list_sources(role, status)
|
||||
refs = self.list_sources(role)
|
||||
by_rank = {ref.worker_rank: ref for ref in refs}
|
||||
if expected_ranks.issubset(by_rank):
|
||||
return [by_rank[rank] for rank in range(count)]
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError(
|
||||
f"timed out waiting for {count} {role} worker(s) in session {self.session_id!r} "
|
||||
f"with status={status}; found ranks={sorted(by_rank)}"
|
||||
f"with ranks={sorted(by_rank)}"
|
||||
)
|
||||
time.sleep(poll_interval)
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ from typing import cast
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
|
||||
@@ -25,11 +24,15 @@ from prime_rl.orchestrator.clients import init_nixl_broadcast, update_weights
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
|
||||
from prime_rl.transports.weights.nixl.agent import NixlAgent, make_agent_name, set_ucx_env_defaults
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
|
||||
size_cuda_buffers,
|
||||
use_cuda_malloc_pool,
|
||||
from prime_rl.transports.weights.nixl.agent import (
|
||||
NixlAgent,
|
||||
NixlPeer,
|
||||
group_notification,
|
||||
make_agent_name,
|
||||
policy_notification,
|
||||
set_ucx_env_defaults,
|
||||
)
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import use_cuda_malloc_pool
|
||||
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.transports.weights.nixl.trainer_tensor_table import (
|
||||
TrainerAgent,
|
||||
@@ -40,8 +43,6 @@ from prime_rl.transports.weights.nixl.trainer_tensor_table import (
|
||||
)
|
||||
|
||||
LAYER_RE = re.compile(r"(?:^|\.)layers\.(\d+)(?=\.|$)")
|
||||
BUFFER_POLL_INTERVAL = 0.01
|
||||
MAX_STAGING_BUFFER_COUNT = 8
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -79,7 +80,7 @@ class NIXLWeightSender(WeightSender):
|
||||
self.config = config
|
||||
self.parallel_dims = parallel_dims
|
||||
if self.is_serving_rank:
|
||||
set_ucx_env_defaults()
|
||||
set_ucx_env_defaults(torch.cuda.current_device())
|
||||
self.nixl_agent = NixlAgent(make_agent_name("trainer", self.world.rank))
|
||||
self.initialized = False
|
||||
self.transfer_group_names: list[str] = []
|
||||
@@ -87,8 +88,10 @@ class NIXLWeightSender(WeightSender):
|
||||
self.staged_shards_by_group: dict[int, list[StagedTensorShard]] = {}
|
||||
self.staging_arenas: dict[torch.dtype, torch.Tensor] = {}
|
||||
self.staging_buffer_count: int
|
||||
self.model_express: ModelExpressSession | None = None
|
||||
self.buffer_sessions: list[ModelExpressSession] = []
|
||||
self.inference_peers: list[NixlPeer]
|
||||
self.orchestrator_peer: NixlPeer
|
||||
self.group_generations: list[int]
|
||||
self.broadcast_count = 0
|
||||
|
||||
@property
|
||||
def is_serving_rank(self) -> bool:
|
||||
@@ -184,31 +187,6 @@ class NIXLWeightSender(WeightSender):
|
||||
)
|
||||
return local_shards
|
||||
|
||||
def choose_staging_buffer_count(self, largest_group_bytes: int) -> int:
|
||||
local_buffer_count = min(len(self.transfer_group_names), MAX_STAGING_BUFFER_COUNT)
|
||||
if self.is_serving_rank and largest_group_bytes:
|
||||
device = self.staged_shards[0].source_tensor.device
|
||||
allocated_bytes = torch.cuda.memory_allocated()
|
||||
peak_growth_bytes = max(0, torch.cuda.max_memory_allocated() - allocated_bytes)
|
||||
free_bytes, _ = torch.cuda.mem_get_info(device)
|
||||
max_buffers = local_buffer_count if peak_growth_bytes else 1
|
||||
if peak_growth_bytes or free_bytes < largest_group_bytes:
|
||||
torch.cuda.empty_cache()
|
||||
local_buffer_count = size_cuda_buffers(
|
||||
largest_group_bytes,
|
||||
max_buffers,
|
||||
device,
|
||||
extra_headroom_bytes=peak_growth_bytes,
|
||||
)
|
||||
|
||||
staging_buffer_count = torch.tensor(
|
||||
local_buffer_count,
|
||||
dtype=torch.int64,
|
||||
device=torch.device("cuda", torch.cuda.current_device()),
|
||||
)
|
||||
dist.all_reduce(staging_buffer_count, op=dist.ReduceOp.MIN)
|
||||
return int(staging_buffer_count.item())
|
||||
|
||||
def allocate_staging_arenas(self, largest_group_elements: dict[torch.dtype, int]) -> None:
|
||||
if not self.is_serving_rank or not any(largest_group_elements.values()):
|
||||
return
|
||||
@@ -248,8 +226,10 @@ class NIXLWeightSender(WeightSender):
|
||||
for shard in self.staged_shards:
|
||||
group_elements[shard.wire_dtype][shard.group_index] += shard.source_tensor.numel()
|
||||
largest_group_elements = {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
|
||||
largest_group_bytes = sum(elements * dtype.itemsize for dtype, elements in largest_group_elements.items())
|
||||
self.staging_buffer_count = self.choose_staging_buffer_count(largest_group_bytes)
|
||||
self.staging_buffer_count = min(
|
||||
len(self.transfer_group_names),
|
||||
2 if self.config.overlap_transfer_and_replay else 1,
|
||||
)
|
||||
self.allocate_staging_arenas(largest_group_elements)
|
||||
|
||||
grouped: dict[int, list[StagedTensorShard]] = defaultdict(list)
|
||||
@@ -363,18 +343,6 @@ class NIXLWeightSender(WeightSender):
|
||||
table = self.merge_trainer_table_fragments(table_fragments)
|
||||
server_url = f"{self.config.host}:{self.config.port}"
|
||||
client = MxClient(server_url=server_url)
|
||||
self.buffer_sessions = []
|
||||
for buffer_index in range(self.staging_buffer_count):
|
||||
session = ModelExpressSession(
|
||||
client=client,
|
||||
role="trainer",
|
||||
rank=0,
|
||||
session_id=f"{self.config.session_id}:layers:{buffer_index}",
|
||||
worker_id=f"trainer-buffer-{buffer_index}",
|
||||
)
|
||||
session.publish()
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.buffer_sessions.append(session)
|
||||
self.model_express = ModelExpressSession(
|
||||
client=client,
|
||||
role="trainer",
|
||||
@@ -383,7 +351,6 @@ class NIXLWeightSender(WeightSender):
|
||||
worker_id="trainer-table",
|
||||
)
|
||||
self.model_express.publish(nixl_metadata=table.encode())
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
tensor_count = sum(len(group.tensors) for group in table.groups)
|
||||
self.logger.info(
|
||||
f"Published {tensor_count} trainer tensors in {len(table.groups)} groups "
|
||||
@@ -391,59 +358,75 @@ class NIXLWeightSender(WeightSender):
|
||||
)
|
||||
self.initialized = True
|
||||
|
||||
def finish_staging_buffer_transfer(self, buffer_index: int) -> None:
|
||||
if self.world.is_master:
|
||||
session = self.buffer_sessions[buffer_index]
|
||||
session.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.config.timeout,
|
||||
poll_interval=BUFFER_POLL_INTERVAL,
|
||||
)
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
session.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.config.timeout,
|
||||
poll_interval=BUFFER_POLL_INTERVAL,
|
||||
)
|
||||
dist.barrier()
|
||||
def finish_transfer_group(self, group_index: int) -> None:
|
||||
if not self.is_serving_rank:
|
||||
return
|
||||
notification = group_notification(group_index, self.group_generations[group_index])
|
||||
self.nixl_agent.wait_for_notification(
|
||||
self.inference_peers,
|
||||
notification,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.group_generations[group_index] += 1
|
||||
|
||||
@torch.no_grad()
|
||||
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
|
||||
self.initialize_transfer(model)
|
||||
start = time.perf_counter()
|
||||
|
||||
if self.world.is_master:
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
self.model_express.wait_for(
|
||||
startup = self.broadcast_count == 0
|
||||
if self.world.is_master and startup:
|
||||
orchestrator_ref = self.model_express.wait_for(
|
||||
"orchestrator",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.model_express.wait_for(
|
||||
)[0]
|
||||
inference_refs = self.model_express.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
inference_metadata: list[bytes] | None = [
|
||||
self.model_express.fetch(ref).nixl_metadata for ref in inference_refs
|
||||
]
|
||||
orchestrator_metadata = self.model_express.fetch(orchestrator_ref).nixl_metadata
|
||||
else:
|
||||
inference_metadata = None
|
||||
|
||||
if startup:
|
||||
objects = [inference_metadata]
|
||||
dist.broadcast_object_list(objects, src=0)
|
||||
if self.is_serving_rank:
|
||||
self.inference_peers = []
|
||||
for metadata in cast(list[bytes], objects[0]):
|
||||
peer = self.nixl_agent.add_remote_agent(metadata)
|
||||
self.nixl_agent.make_connection(peer)
|
||||
self.inference_peers.append(peer)
|
||||
self.group_generations = [0] * len(self.transfer_group_names)
|
||||
if self.world.is_master:
|
||||
self.orchestrator_peer = self.nixl_agent.add_remote_agent(orchestrator_metadata)
|
||||
self.nixl_agent.make_connection(self.orchestrator_peer)
|
||||
|
||||
if self.world.is_master:
|
||||
self.nixl_agent.send_notification(
|
||||
self.orchestrator_peer,
|
||||
policy_notification(step, "ready"),
|
||||
)
|
||||
|
||||
for group, group_name in enumerate(self.transfer_group_names):
|
||||
group_start = time.perf_counter()
|
||||
buffer_index = group % self.staging_buffer_count
|
||||
if group >= self.staging_buffer_count:
|
||||
self.finish_staging_buffer_transfer(buffer_index)
|
||||
self.finish_transfer_group(group - self.staging_buffer_count)
|
||||
|
||||
if self.is_serving_rank:
|
||||
for shard in self.staged_shards_by_group.get(group, ()):
|
||||
shard.copy_to_staging()
|
||||
torch.cuda.synchronize()
|
||||
dist.barrier()
|
||||
notification = group_notification(group, self.group_generations[group])
|
||||
for peer in self.inference_peers:
|
||||
self.nixl_agent.send_notification(peer, notification)
|
||||
if self.world.is_master:
|
||||
self.buffer_sessions[buffer_index].set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
self.logger.debug(
|
||||
f"NIXL+ModelExpress policy v{step} group {group_name} staged in buffer {buffer_index} in "
|
||||
f"{time.perf_counter() - group_start:.2f}s"
|
||||
@@ -451,35 +434,28 @@ class NIXLWeightSender(WeightSender):
|
||||
|
||||
first_pending_group = max(0, len(self.transfer_group_names) - self.staging_buffer_count)
|
||||
for group in range(first_pending_group, len(self.transfer_group_names)):
|
||||
buffer_index = group % self.staging_buffer_count
|
||||
self.finish_staging_buffer_transfer(buffer_index)
|
||||
self.finish_transfer_group(group)
|
||||
|
||||
if self.world.is_master:
|
||||
self.model_express.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
self.nixl_agent.wait_for_notification(
|
||||
[self.orchestrator_peer],
|
||||
policy_notification(step, "complete"),
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.model_express.wait_for(
|
||||
"orchestrator",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
dist.barrier()
|
||||
self.broadcast_count += 1
|
||||
self.logger.info(f"NIXL+ModelExpress policy v{step} synchronized in {time.perf_counter() - start:.2f}s")
|
||||
|
||||
|
||||
class NIXLWeightReceiver(WeightReceiver):
|
||||
"""Drives the orchestrator's side of the ModelExpress rendezvous. Version
|
||||
discovery runs on the shared sentinels; the unversioned ModelExpress
|
||||
statuses only choreograph the transfer itself."""
|
||||
"""Drives NIXL discovery and policy synchronization for the orchestrator."""
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self.session = ModelExpressSession(
|
||||
set_ucx_env_defaults(0)
|
||||
self.nixl_agent = NixlAgent(make_agent_name("orchestrator", 0))
|
||||
self.trainer_peer: NixlPeer | None = None
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=f"{self.config.host}:{self.config.port}"),
|
||||
role="orchestrator",
|
||||
rank=0,
|
||||
@@ -496,23 +472,31 @@ class NIXLWeightReceiver(WeightReceiver):
|
||||
self.config.inference_world_size,
|
||||
self.config.session_id,
|
||||
)
|
||||
self.session.publish()
|
||||
await self.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
|
||||
async def set_status(self, status: int) -> None:
|
||||
await asyncio.to_thread(self.session.set_status, status)
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
|
||||
async def receive(self, step: int) -> None:
|
||||
# ACK the trainer (it waits for the orchestrator's READY before the
|
||||
# engines' INITIALIZING), run the transfer, then close the cycle.
|
||||
self._ack(step)
|
||||
await self.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
await update_weights(self.admin_clients, None, step=step)
|
||||
await self.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
if self.trainer_peer is None:
|
||||
trainer_refs = await asyncio.to_thread(
|
||||
self.model_express.wait_for,
|
||||
"trainer",
|
||||
count=1,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
trainer_worker = await asyncio.to_thread(self.model_express.fetch, trainer_refs[0])
|
||||
trainer_table = TrainerTensorTable.decode(trainer_worker.nixl_metadata)
|
||||
self.trainer_peer = self.nixl_agent.add_remote_agent(trainer_table.agents[0].metadata)
|
||||
self.nixl_agent.make_connection(self.trainer_peer)
|
||||
|
||||
trainer_peer = self.trainer_peer
|
||||
await asyncio.to_thread(
|
||||
self.session.wait_for,
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
self.nixl_agent.wait_for_notification,
|
||||
[trainer_peer],
|
||||
policy_notification(step, "ready"),
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
await update_weights(self.admin_clients, None, step=step)
|
||||
self.nixl_agent.send_notification(
|
||||
trainer_peer,
|
||||
policy_notification(step, "complete"),
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user