Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6d2b3f252 | ||
|
|
13553dd88a | ||
|
|
d37b57ba6e | ||
|
|
802a364e6a | ||
|
|
9b9de2f1bc | ||
|
|
fe38722e8b | ||
|
|
c69f5b0389 | ||
|
|
29e4222767 | ||
|
|
e3e3a87dea |
@@ -15,9 +15,6 @@ lr = 5e-5
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
@@ -12,9 +12,6 @@ lr = 5e-5
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
@@ -5,9 +5,6 @@ max_steps = 10
|
||||
[resume]
|
||||
step = 5
|
||||
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
|
||||
@@ -2,9 +2,6 @@ max_steps = 5
|
||||
|
||||
[ckpt]
|
||||
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
|
||||
@@ -70,9 +70,6 @@ lr = 1e-4
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -75,9 +75,6 @@ lr = 1e-4
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -77,7 +77,6 @@ max_inflight_activations = 1
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
@@ -142,7 +141,6 @@ rollout = 3600
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
|
||||
+1
-6
@@ -115,12 +115,7 @@ dropout = 0.0
|
||||
|
||||
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
|
||||
|
||||
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
|
||||
|
||||
```toml
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
```
|
||||
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
|
||||
|
||||
## Disaggregated Prefill/Decode Inference
|
||||
|
||||
|
||||
+1
-1
@@ -153,7 +153,7 @@ type = "echo"
|
||||
|
||||
### The Algorithm Classes
|
||||
|
||||
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
|
||||
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
|
||||
|
||||
| `algo.type` | Class | hook(s) — stage |
|
||||
|---|---|---|
|
||||
|
||||
+1
-1
@@ -109,7 +109,7 @@ uv run sft \
|
||||
--data.name PrimeIntellect/Reverse-Text-SFT \
|
||||
--max_steps 200 \
|
||||
--optim.lr 1e-4 \
|
||||
--ckpt.weights
|
||||
--ckpt
|
||||
```
|
||||
|
||||
Then run the full RL stack on reverse-text:
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundl
|
||||
uv run rl @ examples/basic/reverse-text/rl.toml
|
||||
```
|
||||
|
||||
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/<run_name>/weights/step_20`.
|
||||
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes with a final DCP checkpoint at `outputs/<run_name>/checkpoints/step_20`.
|
||||
|
||||
## Documentation
|
||||
|
||||
|
||||
+3
-14
@@ -204,11 +204,11 @@ num_train_gpus = 1 # trainer
|
||||
num_infer_gpus = 1 # inference
|
||||
```
|
||||
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. The handoff is the filesystem, not NCCL: the trainer writes an HF weight checkpoint at every step an eval env is due (in addition to `ckpt.interval`), and the evals process watches `weights/step_{n}`, points the inference server at each stable checkpoint (`/update_weights` reload from disk), and runs the due envs against it — sequentially per checkpoint, so every epoch measures exactly one policy version. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final checkpoint always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at every step an eval env is due, and the evals process watches `broadcasts/step_{n}` for synchronization markers before it drives the NCCL receive. It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
|
||||
#### Multi-Node (Decoupled Trainer and Inference Pool)
|
||||
|
||||
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two independent SLURM jobs**. `deployment.num_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
|
||||
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
@@ -223,7 +223,7 @@ tensor_parallel_size = 8
|
||||
job_name = "my-run"
|
||||
```
|
||||
|
||||
The only coupling is weight checkpoints on the shared filesystem, so the jobs' lifetimes are independent: when training finishes, the trainer job exits and releases its nodes even while evals are still running; the eval job keeps draining pending checkpoints and exits after evaluating the final one (`max_steps` — without it the eval job never sees a final checkpoint and holds its allocation until walltime). Trainer and evals log to a single shared W&B run across both jobs — the trainer creates it, the evals process finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
|
||||
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
@@ -272,7 +272,6 @@ Checkpointing is split across processes because the orchestrator and trainer can
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
|
||||
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
|
||||
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
|
||||
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<run_dir>/weights/step_N/` |
|
||||
|
||||
### Enabling Checkpoints
|
||||
|
||||
@@ -304,16 +303,6 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
|
||||
--resume.dir outputs/my-run/checkpoints/step_10
|
||||
```
|
||||
|
||||
### Serving Checkpoints
|
||||
|
||||
HF-compatible weight snapshots are written under `<run_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via `--ckpt.weights-only` for cheaper snapshots). Upload directly:
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/<model>-RL outputs/<run_name>/weights/step_100
|
||||
```
|
||||
|
||||
For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write the raw adapter alongside the merged weights — useful when serving the adapter through a separate `/load_lora_adapter` call.
|
||||
|
||||
## Observability
|
||||
|
||||
### Log Files
|
||||
|
||||
@@ -59,7 +59,6 @@ max_inflight_activations = 1
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
|
||||
@@ -76,7 +76,6 @@ max_inflight_activations = 1
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
@@ -142,7 +141,6 @@ rollout = 3600
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
|
||||
@@ -60,7 +60,6 @@ max_inflight_activations = 1
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
|
||||
@@ -55,7 +55,6 @@ max_inflight_activations = 1
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
skip_gather_master_weights = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "adamw"
|
||||
|
||||
@@ -56,7 +56,6 @@ max_inflight_activations = 1
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
|
||||
@@ -98,11 +98,7 @@ uv run rl @ examples/basic/alphabet-sort/rl.toml \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
This will write a weight checkpoint in `outputs/rl/weights/step_100`. Upload it to HF to be able to use it as the final model for evaluation.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-4B-Instruct-AlphabetSort-RL outputs/rl/weights/step_100
|
||||
```
|
||||
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL`](https://huggingface.co/PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL).
|
||||
|
||||
|
||||
@@ -60,11 +60,7 @@ uv run torchrun \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
This should write a weight checkpoint in `outputs/sft/weights/step_100`. Upload it to HF to be able to use it as the base model for RL.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT outputs/sft/weights/step_100
|
||||
```
|
||||
This should write a DCP checkpoint in `outputs/sft/checkpoints/step_100`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT).
|
||||
|
||||
@@ -83,11 +79,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
This will write a weight checkpoint in `outputs/rl/weights/step_20`. As before, let's upload it to HF.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-RL outputs/rl/weights/step_20
|
||||
```
|
||||
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_20`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL).
|
||||
|
||||
@@ -134,17 +126,7 @@ Exec into the trainer pod and run SFT:
|
||||
```bash
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
|
||||
# This will save checkpoints to /data/outputs/sft/weights/step_100
|
||||
```
|
||||
|
||||
Upload the checkpoint to HuggingFace or use it directly from shared storage:
|
||||
|
||||
```bash
|
||||
# Option 1: Upload to HuggingFace (from within the pod)
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT /data/outputs/sft/weights/step_100
|
||||
|
||||
# Option 2: Use local checkpoint path in RL config
|
||||
# Update the model.name in the RL configs to point to /data/outputs/sft/weights/step_100
|
||||
# This will save DCP checkpoints to /data/outputs/sft/checkpoints/step_100
|
||||
```
|
||||
|
||||
### Step 3: Deploy RL Training
|
||||
@@ -212,11 +194,11 @@ kubectl exec -it my-exp-trainer-0 -- bash
|
||||
|
||||
# If inference server isn't running with the RL model, start it in another terminal:
|
||||
kubectl exec -it my-exp-inference-0 -- bash
|
||||
uv run inference --vllm.model /data/outputs/weights/step_20
|
||||
uv run inference --vllm.model /data/outputs/weights_hf/step_20
|
||||
|
||||
# Back in trainer pod, run evaluation
|
||||
uv run eval reverse-text --harness.id null \
|
||||
-m /data/outputs/weights/step_20 \
|
||||
-m /data/outputs/weights_hf/step_20 \
|
||||
--client.base-url $INFERENCE_URL \
|
||||
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
```
|
||||
|
||||
@@ -103,11 +103,7 @@ The unified config file automatically configures:
|
||||
- **Orchestrator**: Rollout generation with tool calling enabled
|
||||
- **Inference**: vLLM server for Qwen3-4B-Instruct-2507 with tool parsing enabled
|
||||
|
||||
This will write weight checkpoints in `outputs/rl/weights/step_*`. Upload the final checkpoint to HuggingFace:
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-4B-Instruct-WikiSearch-RL outputs/rl/weights/step_500
|
||||
```
|
||||
This will write DCP checkpoints in `outputs/rl/checkpoints/step_*`.
|
||||
|
||||
## Evaluation
|
||||
|
||||
|
||||
@@ -62,11 +62,7 @@ uv run torchrun \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
After training completes, you will find the final weight checkpoint in `outputs/sft/weights/step_20`. Upload it to HF to be able to use it as the base model for RL we will do in the next section.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-1.7B-Wordle-SFT outputs/sft/weights/step_20
|
||||
```
|
||||
After training completes, you will find the final DCP checkpoint in `outputs/sft/checkpoints/step_20`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-SFT).
|
||||
|
||||
@@ -86,11 +82,7 @@ uv run rl @ examples/basic/wordle/rl.toml \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
This will write a weight checkpoint in `outputs/rl/weights/step_100`. As before, let's upload it to HF.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-1.7B-Wordle-RL outputs/rl/weights/step_100
|
||||
```
|
||||
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-RL).
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
max_steps = 20
|
||||
|
||||
[ckpt]
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.5-0.8B"
|
||||
|
||||
@@ -47,8 +47,6 @@ lr = 1e-5
|
||||
|
||||
[ckpt]
|
||||
interval = 200
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
|
||||
@@ -5,6 +5,7 @@ from pydantic import Field, model_validator
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
@@ -40,14 +41,14 @@ class EvalsEvalConfig(EvalConfig):
|
||||
|
||||
|
||||
class OnlineConfig(BaseConfig):
|
||||
"""Checkpoint-driven online evals: watch a weights directory for new HF checkpoints
|
||||
and evaluate each eligible one. Without this block the evals process runs every eval
|
||||
source once against the weights the inference server currently serves, then exits."""
|
||||
"""Broadcast-driven online evals: watch a broadcasts directory for new weight
|
||||
broadcasts and evaluate each eligible one. Without this block the evals process runs
|
||||
every eval source once against the weights the inference server currently serves,
|
||||
then exits."""
|
||||
|
||||
weights_dir: Path | None = None
|
||||
"""Directory to watch for ``step_{n}`` HF weight checkpoints. The ``sft`` launcher
|
||||
fills it from ``ckpt.output_dir`` when checkpoints are redirected to another volume;
|
||||
defaults to ``<output_dir>/weights``."""
|
||||
broadcasts_dir: Path | None = None
|
||||
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
|
||||
``<output_dir>/broadcasts``."""
|
||||
|
||||
max_steps: int | None = None
|
||||
"""Trainer step at which the run ends. The final checkpoint always fires every
|
||||
@@ -64,15 +65,15 @@ class EvalsConfig(BaseConfig):
|
||||
"""``uv run evals``: run the configured evals against a live inference server.
|
||||
Standalone (no ``[online]``), one epoch of every eval source runs against the
|
||||
served weights and the evals process exits. With ``[online]``, the evals process watches a
|
||||
weights directory for new HF checkpoints, points the inference server at each one
|
||||
(``/update_weights`` from disk), and runs the configured evals against the updated
|
||||
weights — the ``sft`` launcher writes this config; it also works standalone against
|
||||
any trainer that writes ``weights/step_{n}`` HF checkpoints with ``STABLE`` markers."""
|
||||
broadcasts directory for new weight broadcasts, updates the inference server through
|
||||
the configured transport, and runs the configured evals against the updated weights.
|
||||
The ``sft`` launcher writes this config; filesystem mode also works standalone against
|
||||
any trainer that writes ``broadcasts/step_{n}`` directories with ``STABLE`` markers."""
|
||||
|
||||
model: str = "Qwen/Qwen3-0.6B"
|
||||
"""Name the inference server serves the model under — the ``model`` field of every
|
||||
eval request and the startup model check. Auto-filled from ``model.name`` by the
|
||||
``sft`` launcher; the name stays fixed across checkpoint reloads (weights are
|
||||
``sft`` launcher; the name stays fixed across weight updates (weights are
|
||||
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
|
||||
|
||||
eval: EvalsEvalConfig
|
||||
@@ -81,6 +82,10 @@ class EvalsConfig(BaseConfig):
|
||||
online: OnlineConfig | None = None
|
||||
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
"""Weight transport for online evals. The ``sft`` launcher fills this from its
|
||||
resolved trainer transport. None uses filesystem reloads."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — rollout traces and logs are written as
|
||||
subdirectories. Shared with the trainer for online evals."""
|
||||
@@ -91,9 +96,9 @@ class EvalsConfig(BaseConfig):
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weights_dir(self):
|
||||
if self.online is not None and self.online.weights_dir is None:
|
||||
self.online.weights_dir = self.output_dir / "weights"
|
||||
def auto_setup_broadcasts_dir(self):
|
||||
if self.online is not None and self.online.broadcasts_dir is None:
|
||||
self.online.broadcasts_dir = self.output_dir / "broadcasts"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -23,11 +23,14 @@ from prime_rl.configs.trainer import (
|
||||
AdamWConfig,
|
||||
CheckpointConfig,
|
||||
ConstantSchedulerConfig,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
GCConfig,
|
||||
ModelConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
OptimizerConfig,
|
||||
SchedulerConfig,
|
||||
TokenizerConfig,
|
||||
WeightBroadcastConfig,
|
||||
validate_scheduler,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
@@ -173,9 +176,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
|
||||
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
|
||||
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
|
||||
from the trainer job: the handoff is weight checkpoints on the shared filesystem,
|
||||
so the eval job can outlive the trainer job (evals drain after training ends) and
|
||||
exits after evaluating the final checkpoint."""
|
||||
from the trainer job. The eval job can outlive the trainer job while it evaluates
|
||||
the final weight broadcast."""
|
||||
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
@@ -204,13 +206,16 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
eval: EvalsEvalConfig | None = None
|
||||
"""Online evaluation configuration: rollout-based evals against a live inference
|
||||
server that reloads the trainer's HF weight checkpoints from disk. If None, no
|
||||
online evals run."""
|
||||
server that receives the trainer's weight broadcasts. If None, no online evals run."""
|
||||
|
||||
inference: InferenceConfig | None = None
|
||||
"""Inference server for online evals. If None (with ``eval`` set), the launcher
|
||||
does not start a server and evals connect to ``eval.client.base_url``."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
"""Trainer-to-inference weight transport for online evals. Defaults to NCCL.
|
||||
LoRA and external inference use filesystem broadcast."""
|
||||
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
scheduler: SchedulerConfig = ConstantSchedulerConfig()
|
||||
@@ -350,29 +355,39 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_online_eval(self):
|
||||
"""Wire online evals: require weight checkpoints (the disk handoff to
|
||||
inference) and connect the eval client to the launcher-managed server."""
|
||||
"""Wire online evals and the trainer-to-inference weight transport."""
|
||||
if self.eval is None:
|
||||
if self.inference is not None:
|
||||
raise ValueError("[inference] is only used for online evals — add an [eval] block or remove it.")
|
||||
return self
|
||||
|
||||
# The trainer's HF weight checkpoints are how inference picks up new policies.
|
||||
if self.ckpt is None:
|
||||
self.ckpt = CheckpointConfig()
|
||||
if self.ckpt.weights is None or self.ckpt.skip_gather_master_weights:
|
||||
raise ValueError(
|
||||
"Online evals require HF weight checkpoints. Enable ckpt.weights and "
|
||||
"disable ckpt.skip_gather_master_weights."
|
||||
)
|
||||
# LoRA runs broadcast the raw adapter, which evals reload via /load_lora_adapter
|
||||
if self.model.lora is not None:
|
||||
if self.inference is not None:
|
||||
self.inference.vllm.enable_lora = True
|
||||
self.inference.vllm.max_lora_rank = self.model.lora.rank
|
||||
else:
|
||||
warnings.warn(
|
||||
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
|
||||
"make sure to set --enable_lora and --max-lora-rank.",
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
if self.ckpt.keep_last is not None or self.ckpt.keep_interval is not None:
|
||||
warnings.warn(
|
||||
"ckpt.keep_last / ckpt.keep_interval can delete a weight checkpoint before the "
|
||||
"evals consumes it when evals run slower than training - such steps are "
|
||||
"skipped with a warning instead of evaluated.",
|
||||
stacklevel=2,
|
||||
)
|
||||
if self.weight_broadcast is None:
|
||||
if self.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = FileSystemWeightBroadcastConfig()
|
||||
else:
|
||||
self.weight_broadcast = NCCLWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type != "filesystem":
|
||||
if self.weight_broadcast.type == "nixl":
|
||||
raise ValueError("NIXL weight broadcast is not supported for SFT online evals.")
|
||||
if self.model.lora is not None:
|
||||
raise ValueError(
|
||||
"LoRA training is not yet supported with in-memory weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
if self.eval.retrigger_on_resume:
|
||||
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
|
||||
|
||||
if self.deployment.type == "multi_node":
|
||||
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
|
||||
@@ -399,10 +414,11 @@ class SFTConfig(BaseConfig):
|
||||
f"deployment.gpus_per_node ({self.deployment.gpus_per_node}) must be divisible by "
|
||||
f"inference.vllm.tensor_parallel_size ({self.inference.vllm.tensor_parallel_size})."
|
||||
)
|
||||
if self.inference.weight_broadcast.type != "filesystem":
|
||||
raise ValueError(
|
||||
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
self.weight_broadcast.inference_world_size = (
|
||||
self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
)
|
||||
self.inference.weight_broadcast.type = self.weight_broadcast.type
|
||||
if self.max_steps is None:
|
||||
warnings.warn(
|
||||
"Online evals without max_steps: the evals process never sees a final checkpoint, "
|
||||
@@ -451,10 +467,9 @@ class SFTConfig(BaseConfig):
|
||||
vllm.data_parallel_size = num_infer_gpus // vllm.tensor_parallel_size
|
||||
if vllm.api_server_count < vllm.data_parallel_size and not vllm.enable_lora:
|
||||
vllm.api_server_count = vllm.data_parallel_size
|
||||
if self.inference.weight_broadcast.type != "filesystem":
|
||||
raise ValueError(
|
||||
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size
|
||||
self.inference.weight_broadcast.type = self.weight_broadcast.type
|
||||
|
||||
host = self.inference.server.host or "localhost"
|
||||
client = self.eval.client
|
||||
@@ -550,17 +565,6 @@ class SFTConfig(BaseConfig):
|
||||
validate_scheduler(self.scheduler, self.max_steps)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
lora_enabled = self.model and self.model.lora
|
||||
if not lora_enabled:
|
||||
raise ValueError(
|
||||
"save_adapter_separately=True requires LoRA to be enabled. "
|
||||
"Set model.lora or disable save_adapter_separately."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_opt_and_fsdp_offload(self):
|
||||
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
|
||||
|
||||
@@ -465,33 +465,13 @@ OptimizerConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class WeightCheckpointConfig(BaseConfig):
|
||||
save_sharded: bool = True
|
||||
"""Save the weight checkpoint in sharded format."""
|
||||
|
||||
save_format: Literal["safetensors", "torch"] = "safetensors"
|
||||
"""Weight checkpoint serialization format."""
|
||||
|
||||
save_adapter_separately: bool = False
|
||||
"""Save LoRA adapters separately before merging into full model weights."""
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
output_dir: Path | None = None
|
||||
"""Override directory for checkpoints and weights. If set, checkpoints and weight snapshots are written here instead of under the trainer ``output_dir`` — useful for writing large checkpoints to a separate storage volume."""
|
||||
"""Override directory for checkpoints. If set, checkpoints are written here instead of under the trainer ``output_dir`` — useful for writing large checkpoints to a separate storage volume."""
|
||||
|
||||
interval: int | None = Field(None, ge=1)
|
||||
"""Interval at which to save the training checkpoint. If None, only checkpoints at the end of training."""
|
||||
|
||||
weights: WeightCheckpointConfig | None = WeightCheckpointConfig()
|
||||
"""Weight-checkpoint sub-configuration. If None, no HF-compatible weight checkpoints are written."""
|
||||
|
||||
skip_gather_master_weights: bool = False
|
||||
"""Skip gathering and saving HF-compatible weight checkpoints. Useful for large models where the gather is expensive and only DCP checkpoints are needed."""
|
||||
|
||||
weights_only: bool = False
|
||||
"""Save only weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training."""
|
||||
|
||||
keep_last: int | None = Field(None, ge=1)
|
||||
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
|
||||
|
||||
@@ -572,12 +552,6 @@ class BaseWeightBroadcastConfig(BaseConfig):
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
save_sharded: bool = True
|
||||
"""Save the weight checkpoint in sharded format."""
|
||||
|
||||
save_format: Literal["safetensors", "torch"] = "safetensors"
|
||||
"""Weight checkpoint serialization format."""
|
||||
|
||||
|
||||
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
host: str = "localhost"
|
||||
@@ -750,17 +724,6 @@ class TrainerConfig(BaseConfig):
|
||||
validate_scheduler(self.scheduler, self.max_steps)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
lora_enabled = self.model and self.model.lora
|
||||
if not lora_enabled:
|
||||
raise ValueError(
|
||||
"save_adapter_separately=True requires LoRA to be enabled. "
|
||||
"Set model.lora or disable save_adapter_separately."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_opt_and_fsdp_offload(self):
|
||||
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
|
||||
|
||||
@@ -16,8 +16,8 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "qwen3_coder"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3"), "qwen3_coder"),
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
# Qwen3.5 and Qwen3-Coder use qwen3_coder — must be before the Qwen3 catch-all.
|
||||
(re.compile(r"^Qwen/Qwen3\.5-"), "qwen3_coder"),
|
||||
# Qwen3.5/3.6/3.8 and Qwen3-Coder use qwen3_coder — must be before the Qwen3 catch-all.
|
||||
(re.compile(r"^Qwen/Qwen3\.(5|6|8)-"), "qwen3_coder"),
|
||||
(re.compile(r"^Qwen/Qwen3-Coder"), "qwen3_coder"),
|
||||
(re.compile(r"^Qwen/Qwen3-"), "hermes"),
|
||||
]
|
||||
@@ -37,7 +37,7 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
# Only Qwen3 Thinking models reason — Instruct/base models do not.
|
||||
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
|
||||
(re.compile(r"^Qwen/Qwen3\.5-"), "qwen3"),
|
||||
(re.compile(r"^Qwen/Qwen3\.(5|6|8)-"), "qwen3"),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the run dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
|
||||
- `{run_dir}/configs/` — resolved configs, written as JSON so explicit None settings round-trip (`rl.json` has the full picture).
|
||||
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
|
||||
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
|
||||
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
|
||||
|
||||
### Logs
|
||||
|
||||
@@ -152,7 +152,7 @@ JSONL files of native `vf.Episode` records (training tensors excluded), one line
|
||||
curriculum-rejected work, and work that never enters a batch — so it is crash-durable.
|
||||
`effective` contains the admitted clean trainable traces grouped into their original episodes
|
||||
(eval: the non-errored trainable epoch cohort). Each record carries its provenance at the
|
||||
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group_id`,
|
||||
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
|
||||
and `run`. Training-run records discriminate train/eval work and include dispatch
|
||||
step plus an optional live-policy version span. Traces retain their own task,
|
||||
verifiers, agent, and runtime fields.
|
||||
|
||||
@@ -9,7 +9,7 @@ All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/t
|
||||
|
||||
## Run directories
|
||||
|
||||
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, weights, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
|
||||
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
|
||||
|
||||
## Config system at a glance
|
||||
|
||||
@@ -92,7 +92,7 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
|
||||
## `evals` — multi-env evals
|
||||
|
||||
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`weights_dir`, `max_steps`, `resume_step`): watch the weights dir for stable `step_{n}` HF checkpoints and evaluate each — the `sft` launcher writes this config for online evals.
|
||||
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -19,12 +18,10 @@ from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_all_ckpt_steps,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_log_dir,
|
||||
get_step_path,
|
||||
get_weights_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
@@ -66,7 +63,7 @@ def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
|
||||
|
||||
|
||||
def get_ckpt_base(config: SFTConfig) -> Path:
|
||||
"""Where checkpoints and weights live: ``ckpt.output_dir`` when set, else the run dir."""
|
||||
"""Where checkpoints live: ``ckpt.output_dir`` when set, else the run dir."""
|
||||
return (config.ckpt.output_dir if config.ckpt else None) or config.run_dir
|
||||
|
||||
|
||||
@@ -92,8 +89,9 @@ def build_evals_config(config: SFTConfig) -> EvalsConfig:
|
||||
return EvalsConfig(
|
||||
model=config.model.name,
|
||||
eval=eval_config,
|
||||
weight_broadcast=config.weight_broadcast,
|
||||
online=OnlineConfig(
|
||||
weights_dir=get_weights_dir(get_ckpt_base(config)),
|
||||
broadcasts_dir=get_broadcast_dir(config.run_dir),
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(config),
|
||||
),
|
||||
@@ -176,6 +174,11 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
use_nccl_broadcast=(
|
||||
config.eval is not None
|
||||
and config.weight_broadcast is not None
|
||||
and config.weight_broadcast.type == "nccl"
|
||||
),
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -226,6 +229,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -235,9 +239,8 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
def sft_slurm(config: SFTConfig):
|
||||
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
|
||||
trainer and the eval deployment (inference pool + evals) are two independent
|
||||
SLURM jobs: the handoff is weight checkpoints on the shared filesystem, so the
|
||||
trainer job releases its allocation when training finishes while the eval job
|
||||
keeps draining evals and exits after the final checkpoint."""
|
||||
SLURM jobs. The trainer publishes its rank-0 hostname through the shared run
|
||||
directory so the eval deployment can join its NCCL weight-broadcast group."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
@@ -252,7 +255,7 @@ def sft_slurm(config: SFTConfig):
|
||||
else {"slurm", "dry_run", "clean"}
|
||||
)
|
||||
if decoupled_eval:
|
||||
# The trainer job only needs [eval] for the weight-checkpoint cadence; the
|
||||
# The trainer job only needs [eval] for the weight-broadcast cadence; the
|
||||
# inference pool lives in the eval job.
|
||||
exclude = exclude | {"inference"}
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
@@ -298,9 +301,19 @@ def sft_slurm(config: SFTConfig):
|
||||
).removeprefix("Logs:\n")
|
||||
|
||||
if config.dry_run:
|
||||
submit = "\n".join(f" sbatch {path}" for path in script_paths)
|
||||
if decoupled_eval:
|
||||
trainer_submit = f" TRAIN_JOB_ID=$(sbatch --parsable {script_paths[0]} | cut -d';' -f1)"
|
||||
eval_submit = f" sbatch --dependency=after:$TRAIN_JOB_ID {script_paths[1]}"
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
eval_submit = (
|
||||
" sbatch --dependency=after:$TRAIN_JOB_ID "
|
||||
f"--export=ALL,TRAIN_JOB_ID=$TRAIN_JOB_ID {script_paths[1]}"
|
||||
)
|
||||
submit = "\n".join((trainer_submit, eval_submit))
|
||||
else:
|
||||
submit = f" sbatch {script_paths[0]}"
|
||||
note = (
|
||||
"\n\nSubmit the trainer job first — the evals process joins the W&B run the trainer creates."
|
||||
"\n\nSubmit the trainer job first. The eval job starts after the trainer allocation is ready."
|
||||
if decoupled_eval
|
||||
else ""
|
||||
)
|
||||
@@ -315,6 +328,8 @@ def sft_slurm(config: SFTConfig):
|
||||
if submitted_job_ids:
|
||||
# Hold the eval job until the trainer job has started (not finished).
|
||||
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
cmd.append(f"--export=ALL,TRAIN_JOB_ID={submitted_job_ids[-1]}")
|
||||
cmd.append(str(path))
|
||||
logger.info(f"Submitting: {' '.join(cmd)}")
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
@@ -535,29 +550,28 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
|
||||
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
|
||||
"""Remove eval artifacts a previous run left behind: weight checkpoints and rollout
|
||||
"""Remove eval artifacts a previous run left behind: weight broadcasts and rollout
|
||||
trace dirs — everything on a fresh start, steps past the resume step on resume.
|
||||
Without this the evals process would replay stale checkpoints (and then skip the
|
||||
Without this the evals process would replay stale broadcasts (and then skip the
|
||||
re-trained ones at the same steps), and the append-only trace files would mix two
|
||||
policies' rollouts under one step."""
|
||||
logger = setup_logger(config.log.level or "info")
|
||||
if os.environ.get("NEVER_CLEAN"):
|
||||
logger.warning("NEVER_CLEAN is set - keeping stale weight checkpoints; the evals process may replay them")
|
||||
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the evals process may replay them")
|
||||
return
|
||||
resume_step = resolve_resume_step(config)
|
||||
weights_dir = get_weights_dir(get_ckpt_base(config))
|
||||
stale_steps = [step for step in get_all_ckpt_steps(weights_dir) if resume_step is None or step > resume_step]
|
||||
if stale_steps:
|
||||
logger.info(
|
||||
f"Deleting {len(stale_steps)} stale weight checkpoint(s) in {weights_dir} "
|
||||
f"({','.join(map(str, stale_steps))})"
|
||||
)
|
||||
for step in stale_steps:
|
||||
shutil.rmtree(get_step_path(weights_dir, step), ignore_errors=True)
|
||||
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
|
||||
|
||||
|
||||
def sft(config: SFTConfig):
|
||||
# Launcher-only check: the trainer re-parses a sub-config with [inference] and
|
||||
# [deployment] stripped, so the model validator cannot enforce this.
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl" and config.inference is None:
|
||||
raise ValueError(
|
||||
"NCCL weight broadcast requires launcher-managed inference. "
|
||||
"Add an [inference] block or set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
|
||||
# The run identity is runtime-only, never sub-config: $PRL_RUN_ID / $PRL_RUN_NAME are
|
||||
# the vehicle for runtime info between processes, and every spawned process inherits
|
||||
# them. Components launched standalone have no run identity.
|
||||
|
||||
+77
-35
@@ -2,12 +2,11 @@
|
||||
|
||||
Standalone (no ``[online]``), it runs one epoch of every configured eval
|
||||
source against the weights the inference server currently serves, then exits.
|
||||
With ``[online]``, it watches a weights directory for new HF checkpoints —
|
||||
the trainer writes ``weights/step_{n}`` with a ``STABLE`` marker on
|
||||
completion — tells the inference server to reload each eligible checkpoint
|
||||
from disk (``/update_weights``, no NCCL rendezvous), and runs the configured
|
||||
evals against the updated weights, sequentially per checkpoint so every epoch
|
||||
measures exactly one policy version.
|
||||
With ``[online]``, it watches a broadcasts directory for new weight
|
||||
broadcasts — the trainer writes ``broadcasts/step_{n}`` with a ``STABLE``
|
||||
marker on completion — tells the inference server to receive each eligible
|
||||
broadcast, and runs the configured evals against the updated weights,
|
||||
sequentially per broadcast so every epoch measures exactly one policy version.
|
||||
|
||||
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
|
||||
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
|
||||
@@ -44,7 +43,7 @@ from prime_rl.orchestrator.patches import (
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import EvalBatch, Policy
|
||||
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.client import InferencePool, init_nccl_broadcast
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir, get_step_path
|
||||
@@ -54,16 +53,21 @@ from prime_rl.utils.utils import clean_exit
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
|
||||
# How often to re-scan the weights directory for new checkpoints.
|
||||
# How often to re-scan the broadcasts directory for new weight broadcasts.
|
||||
POLL_INTERVAL_S = 2.0
|
||||
|
||||
# Served model name for adapter broadcasts of LoRA runs. Reloading the same name
|
||||
# with fresh weights each step is supported (the server forces an in-place
|
||||
# reload, see /load_lora_adapter).
|
||||
LORA_NAME = "eval-adapter"
|
||||
|
||||
|
||||
class Evals:
|
||||
def __init__(self, config: EvalsConfig) -> None:
|
||||
self.config = config
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
mode = f"online (weights_dir={config.online.weights_dir})" if config.online is not None else "standalone"
|
||||
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
|
||||
get_logger().info(f"Starting evals ({mode})")
|
||||
|
||||
# The last weight-checkpoint step already handled (evaluated or skipped).
|
||||
@@ -104,6 +108,18 @@ class Evals:
|
||||
await self.pool.wait_for_ready(config.model)
|
||||
get_logger().success("Inference pool ready")
|
||||
|
||||
weight_broadcast = config.weight_broadcast
|
||||
if weight_broadcast is not None and weight_broadcast.type == "nccl":
|
||||
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
|
||||
await init_nccl_broadcast(
|
||||
self.pool.admin_clients,
|
||||
weight_broadcast.host,
|
||||
weight_broadcast.port,
|
||||
weight_broadcast.timeout,
|
||||
inference_world_size=weight_broadcast.inference_world_size,
|
||||
quantize_in_weight_transfer=weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
|
||||
is_resumed = config.online is not None and config.online.resume_step is not None
|
||||
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
|
||||
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
|
||||
@@ -221,7 +237,7 @@ class Evals:
|
||||
get_logger().success("Evals finished!")
|
||||
|
||||
async def watch(self) -> None:
|
||||
"""Online mode: evaluate each eligible weight checkpoint as it appears."""
|
||||
"""Online mode: evaluate each eligible weight broadcast as it appears."""
|
||||
config = self.config
|
||||
assert config.online is not None
|
||||
online = config.online
|
||||
@@ -233,39 +249,58 @@ class Evals:
|
||||
await self.maybe_run_evals(step=0)
|
||||
elif config.eval.retrigger_on_resume:
|
||||
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
|
||||
# evals). Requires the resume step's weights on disk. The final checkpoint
|
||||
# force-fires every env, exactly like the watch loop below.
|
||||
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
|
||||
await self.maybe_run_evals(step=online.resume_step, reload_weights=True, force=is_final)
|
||||
# evals). The trainer rebroadcasts the resumed policy on startup, but only
|
||||
# after loading the model — wait for that broadcast instead of checking
|
||||
# once. A newer stable broadcast means the resume step's was already
|
||||
# cleaned away (only the newest is kept) and can never reappear. The
|
||||
# final broadcast force-fires every env, exactly like the watch loop below.
|
||||
assert online.broadcasts_dir is not None and online.resume_step is not None
|
||||
while True:
|
||||
if (get_step_path(online.broadcasts_dir, online.resume_step) / "STABLE").exists():
|
||||
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
|
||||
await self.maybe_run_evals(step=online.resume_step, reload_weights=True, force=is_final)
|
||||
break
|
||||
newer_stable = any(
|
||||
step > online.resume_step and (get_step_path(online.broadcasts_dir, step) / "STABLE").exists()
|
||||
for step in get_all_ckpt_steps(online.broadcasts_dir)
|
||||
)
|
||||
if newer_stable:
|
||||
get_logger().warning(
|
||||
f"Broadcast for resume step {online.resume_step} was cleaned before it could be "
|
||||
"re-evaluated (broadcast cleaning outpaced the evals process) - skipping the retrigger"
|
||||
)
|
||||
break
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
get_logger().info(f"Watching {online.weights_dir} for new weight checkpoints (max_steps={online.max_steps})")
|
||||
get_logger().info(f"Watching {online.broadcasts_dir} for new weight broadcasts (max_steps={online.max_steps})")
|
||||
while True:
|
||||
assert online.weights_dir is not None # resolved by the config validator
|
||||
steps = get_all_ckpt_steps(online.weights_dir)
|
||||
stable = {step: (get_step_path(online.weights_dir, step) / "STABLE").exists() for step in steps}
|
||||
assert online.broadcasts_dir is not None # resolved by the config validator
|
||||
steps = get_all_ckpt_steps(online.broadcasts_dir)
|
||||
stable = {step: (get_step_path(online.broadcasts_dir, step) / "STABLE").exists() for step in steps}
|
||||
newest_stable = max((step for step in steps if stable[step]), default=None)
|
||||
# Also walk eval-due steps that are no longer on disk: checkpoint cleaning
|
||||
# (ckpt.keep_last / keep_interval) can delete a step before this scan sees
|
||||
# it, and a vanished step would otherwise be skipped without a trace.
|
||||
# Also walk eval-due steps that are no longer on disk: broadcast cleaning
|
||||
# (the trainer keeps only the newest broadcast) can delete a step before
|
||||
# this scan sees it, and a vanished step would otherwise be skipped
|
||||
# without a trace.
|
||||
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_stable)):
|
||||
if step <= self.last_step:
|
||||
continue
|
||||
if step not in stable:
|
||||
get_logger().warning(
|
||||
f"Weight checkpoint for eval step {step} was deleted before it could be "
|
||||
"evaluated (checkpoint cleaning outpaced the evals process) - skipping its evals"
|
||||
f"Weight broadcast for eval step {step} was deleted before it could be "
|
||||
"evaluated (broadcast cleaning outpaced the evals process) - skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
if not stable[step]:
|
||||
# The trainer writes checkpoints in ascending order, so a marker-less
|
||||
# The trainer writes broadcasts in ascending order, so a marker-less
|
||||
# step below a stable one is an abandoned partial write (e.g. a crash
|
||||
# mid-save), not one in progress — skip it instead of wedging on it.
|
||||
if newest_stable is None or newest_stable < step:
|
||||
break # still being written — later steps can't be ready either
|
||||
get_logger().warning(
|
||||
f"Weight checkpoint step {step} has no STABLE marker but newer stable "
|
||||
"checkpoints exist - treating it as abandoned and skipping its evals"
|
||||
f"Weight broadcast step {step} has no STABLE marker but newer stable "
|
||||
"broadcasts exist - treating it as abandoned and skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
@@ -276,9 +311,10 @@ class Evals:
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
|
||||
"""Eval-due steps up to the newest stable checkpoint that are missing from the
|
||||
weights dir — the trainer wrote them (it saves at every due step), so their
|
||||
absence means checkpoint cleaning removed them before they were evaluated."""
|
||||
"""Eval-due steps up to the newest stable broadcast that are missing from the
|
||||
broadcasts dir — the trainer wrote them (it broadcasts at every due step), so
|
||||
their absence means broadcast cleaning removed them before they were
|
||||
evaluated."""
|
||||
if newest_stable is None:
|
||||
return set()
|
||||
due = {
|
||||
@@ -292,10 +328,10 @@ class Evals:
|
||||
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
|
||||
reloading the inference weights first. No-op when no env is due."""
|
||||
if reload_weights:
|
||||
assert self.config.online is not None and self.config.online.weights_dir is not None
|
||||
weight_dir = get_step_path(self.config.online.weights_dir, step)
|
||||
if not (weight_dir / "STABLE").exists():
|
||||
get_logger().warning(f"No stable weight checkpoint for step {step} ({weight_dir}) - skipping eval")
|
||||
assert self.config.online is not None and self.config.online.broadcasts_dir is not None
|
||||
broadcast_dir = get_step_path(self.config.online.broadcasts_dir, step)
|
||||
if not (broadcast_dir / "STABLE").exists():
|
||||
get_logger().warning(f"No stable weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
|
||||
self.last_step = max(self.last_step, step)
|
||||
return
|
||||
|
||||
@@ -313,9 +349,12 @@ class Evals:
|
||||
)
|
||||
|
||||
if reload_weights:
|
||||
get_logger().info(f"Updating inference weights to checkpoint step {step} ({weight_dir})")
|
||||
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
|
||||
# LoRA runs broadcast the raw adapter; load it under a fixed adapter name
|
||||
# and serve the evals against that name (mirrors WeightWatcher).
|
||||
lora_name = LORA_NAME if (broadcast_dir / "adapter_config.json").exists() else None
|
||||
try:
|
||||
await self.pool.update_weights(weight_dir, step=step)
|
||||
await self.pool.update_weights(broadcast_dir, lora_name=lora_name, step=step)
|
||||
except Exception as exc:
|
||||
# Skip this step instead of killing the run; drain the queued examples
|
||||
# so they don't leak into a later epoch with the wrong eval_step.
|
||||
@@ -323,6 +362,9 @@ class Evals:
|
||||
pass
|
||||
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
|
||||
return
|
||||
if lora_name is not None:
|
||||
self.pool.update_model_name(lora_name)
|
||||
self.policy.model_name = lora_name
|
||||
|
||||
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
|
||||
# between the trigger above and the weight reload completing.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
|
||||
is — a bundle of sampling and the per-token training signal. This package
|
||||
turns the signal half into runtime objects (the sampling half is the env's
|
||||
:class:`~prime_rl.orchestrator.sampler.Sampler`):
|
||||
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
|
||||
|
||||
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
|
||||
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``) — each named class owns
|
||||
@@ -55,7 +55,7 @@ def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm
|
||||
cls = ALGORITHM_CLASSES[config.type]
|
||||
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
|
||||
# The Algorithm is the runtime of the algorithm config's training signal
|
||||
# (its sibling Sampler interprets the sampling half). Every algorithm is
|
||||
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
|
||||
# handed the live policy pool — opsd self-distills against it, others may
|
||||
# judge against it or ignore it. Other models (a frozen teacher, a hint
|
||||
# renderer) are built from the algorithm's own config in setup().
|
||||
|
||||
@@ -163,7 +163,7 @@ class Dispatcher:
|
||||
self.progress = progress
|
||||
self.train_envs = train_envs
|
||||
self.eval_envs = eval_envs
|
||||
# Train rollouts go to the env sampler's pool; eval always
|
||||
# Train rollouts go to the env's generation source; eval always
|
||||
# evaluates the policy.
|
||||
self.policy_pool = policy_pool
|
||||
self.train_source = train_source
|
||||
@@ -218,14 +218,14 @@ class Dispatcher:
|
||||
self.stopped = asyncio.Event()
|
||||
self.task: asyncio.Task | None = None
|
||||
|
||||
def _train_pool_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
|
||||
def _train_generation_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
|
||||
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
|
||||
the env sampler's pool. (Eval always uses the policy.)"""
|
||||
eval always uses the policy."""
|
||||
assert self.train_envs is not None # train groups only exist when train is configured
|
||||
sampler = self.train_envs.get(env_name).sampler
|
||||
if sampler.samples_from_live_policy:
|
||||
return sampler.pool, self.policy.model_name, True
|
||||
return sampler.pool, sampler.pool.model_name, False
|
||||
source = self.train_envs.get(env_name).generation_source
|
||||
if source.uses_live_policy:
|
||||
return source.pool, self.policy.model_name, True
|
||||
return source.pool, source.pool.model_name, False
|
||||
|
||||
@property
|
||||
def inflight_train_count(self) -> int:
|
||||
@@ -374,10 +374,10 @@ class Dispatcher:
|
||||
for meta in self.inflight.values():
|
||||
if meta.kind != "train":
|
||||
continue
|
||||
# Frozen-sourced rollouts never go stale — their sampler doesn't
|
||||
# Frozen-sourced rollouts never go stale — their generation source doesn't
|
||||
# change with policy updates.
|
||||
assert self.train_envs is not None
|
||||
if not self.train_envs.get(meta.env_name).sampler.samples_from_live_policy:
|
||||
if not self.train_envs.get(meta.env_name).generation_source.uses_live_policy:
|
||||
continue
|
||||
meta.off_policy_steps += 1
|
||||
if meta.off_policy_steps > self.max_off_policy_steps:
|
||||
@@ -490,7 +490,7 @@ class Dispatcher:
|
||||
ready, no permits). Returns True after issuing one task — the caller
|
||||
loops to keep scheduling.
|
||||
"""
|
||||
# Train rollouts use the env sampler's pool via the
|
||||
# Train rollouts use the env's generation source via the
|
||||
# renderer/token train client. Eval always evaluates the policy and
|
||||
# goes through the eval client (chat-completions) so eval scores stay
|
||||
# comparable.
|
||||
@@ -498,7 +498,7 @@ class Dispatcher:
|
||||
pool, model_name = self.policy_pool, self.policy.model_name
|
||||
live_sourced = True
|
||||
else:
|
||||
pool, model_name, live_sourced = self._train_pool_for(group.env_name)
|
||||
pool, model_name, live_sourced = self._train_generation_for(group.env_name)
|
||||
|
||||
if group.pinned_client is None:
|
||||
group.pinned_client = pool.eval_client if group.kind == "eval" else pool.train_client
|
||||
@@ -644,7 +644,7 @@ class Dispatcher:
|
||||
live_policy = meta.kind == "eval"
|
||||
if meta.kind == "train":
|
||||
assert self.train_envs is not None
|
||||
live_policy = self.train_envs.get(meta.env_name).sampler.samples_from_live_policy
|
||||
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
|
||||
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
|
||||
work: vf.WorkInfo = (
|
||||
vf.EvalWorkInfo(step=meta.step, policy=policy)
|
||||
|
||||
@@ -29,7 +29,7 @@ from verifiers.v1.serve import EnvClient
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
|
||||
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
|
||||
from prime_rl.orchestrator.sampler import Sampler
|
||||
from prime_rl.orchestrator.generation_source import GenerationSource
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# Max wait for the env server to answer health. Generous because the launcher spawns
|
||||
@@ -74,11 +74,11 @@ class Env:
|
||||
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
|
||||
taskset = vf.load_taskset(self.config.env.taskset)
|
||||
if type(taskset).INFINITE:
|
||||
self.tasks = iter(taskset.load())
|
||||
self.tasks = iter(taskset)
|
||||
self.num_tasks = None
|
||||
else:
|
||||
# Materialize off the event loop — load() may pull a dataset.
|
||||
materialized = await asyncio.to_thread(lambda: list(taskset.load()))
|
||||
# Materialize off the event loop — iterating may pull a dataset.
|
||||
materialized = await asyncio.to_thread(lambda: list(taskset))
|
||||
self.tasks = iter(materialized)
|
||||
self.num_tasks = len(materialized)
|
||||
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
|
||||
@@ -118,11 +118,17 @@ class Env:
|
||||
class TrainEnv(Env):
|
||||
config: TrainSourceConfig
|
||||
|
||||
def __init__(self, config: TrainSourceConfig, address: str, sampler: Sampler, algorithm: Algorithm):
|
||||
def __init__(
|
||||
self,
|
||||
config: TrainSourceConfig,
|
||||
address: str,
|
||||
generation_source: GenerationSource,
|
||||
algorithm: Algorithm,
|
||||
):
|
||||
super().__init__(config, address)
|
||||
self.sampler = sampler
|
||||
self.generation_source = generation_source
|
||||
self.algorithm = algorithm
|
||||
self.sampling_args = sampler.sampling_args(config.sampling.to_sampling_args())
|
||||
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
|
||||
|
||||
|
||||
class EvalEnv(Env):
|
||||
@@ -175,8 +181,8 @@ class Envs(Generic[EnvT]):
|
||||
|
||||
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
"""Collection of training environments, each paired with its rollout
|
||||
:class:`Sampler` and runtime :class:`Algorithm`, built from the env's
|
||||
"""Collection of training environments, each paired with its
|
||||
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
|
||||
resolved algorithm config."""
|
||||
|
||||
def __init__(
|
||||
@@ -193,7 +199,7 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
env = TrainEnv(
|
||||
config,
|
||||
addresses[("train", config.resolved_name)],
|
||||
Sampler(config.algo.sampling, policy_pool, renderer_config),
|
||||
GenerationSource(config.algo.sampling, policy_pool, renderer_config),
|
||||
build_algorithm(config.algo, policy_pool),
|
||||
)
|
||||
self._envs[env.name] = env
|
||||
|
||||
@@ -86,4 +86,8 @@ class EvalSink:
|
||||
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
|
||||
env_name, step = key
|
||||
episodes = self.pending_batches.pop(key, [])
|
||||
return EvalBatch(env_name=env_name, step=step, episodes=EvalEpisodes(episodes))
|
||||
return EvalBatch(
|
||||
env_name=env_name,
|
||||
step=step,
|
||||
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
|
||||
)
|
||||
|
||||
+6
-14
@@ -1,12 +1,4 @@
|
||||
"""How an env's train rollouts are produced — the sample strategy.
|
||||
|
||||
The algorithm (``algo/``) consumes finalized rollouts and compiles them into
|
||||
per-token loss-component weights; the sampler owns where those rollouts come
|
||||
from. Today that is one question — which model generates them — and its
|
||||
consequences (sampling logprobs, prefix-cache salting, and off-policy
|
||||
staleness are all liveness questions about the source). Future sampling
|
||||
strategies (replay buffers, branching) extend here, not the algorithm.
|
||||
"""
|
||||
"""Resolve the model source used to generate an env's train episodes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -21,8 +13,8 @@ if TYPE_CHECKING:
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
class Sampler:
|
||||
"""One env's rollout source.
|
||||
class GenerationSource:
|
||||
"""One env's generation model and inference pool.
|
||||
|
||||
``pool`` is the pool train rollouts are generated from: the policy pool,
|
||||
swapped for a connected frozen pool in :meth:`setup` when the source is an
|
||||
@@ -40,20 +32,20 @@ class Sampler:
|
||||
self.connected_pools: list[InferencePool] = [] # client pools connected in setup(); closed at shutdown
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Connect a client pool to a frozen sampling source and wait for
|
||||
"""Connect a client pool to a frozen generation source and wait for
|
||||
readiness. Must run before dispatching."""
|
||||
if isinstance(self.config.source, FrozenModelConfig):
|
||||
self.pool = await connect_frozen_pool(self.config.source, renderer_config=self.renderer_config)
|
||||
self.connected_pools.append(self.pool)
|
||||
|
||||
@property
|
||||
def samples_from_live_policy(self) -> bool:
|
||||
def uses_live_policy(self) -> bool:
|
||||
return self.config.source == "policy"
|
||||
|
||||
def sampling_args(self, args: dict) -> dict:
|
||||
"""Source-specific sampling-arg overrides. Sampling logprobs are only
|
||||
needed for importance ratios on policy-sampled tokens — frozen
|
||||
endpoints may reject the knob."""
|
||||
if not self.samples_from_live_policy:
|
||||
if not self.uses_live_policy:
|
||||
args.pop("logprobs", None)
|
||||
return args
|
||||
@@ -474,30 +474,19 @@ class TrainEpisodes(EpisodeCollection):
|
||||
class EvalEpisodes(EpisodeCollection):
|
||||
def __init__(
|
||||
self,
|
||||
episodes: list[vf.Episode] | None = None,
|
||||
episodes: list[vf.Episode],
|
||||
group_size: int,
|
||||
predicate: Callable[[TraceRecord], bool] | None = None,
|
||||
group_size: int | None = None,
|
||||
) -> None:
|
||||
super().__init__(episodes, predicate=predicate)
|
||||
self._group_size = group_size
|
||||
|
||||
@property
|
||||
def group_size(self) -> int:
|
||||
if self._group_size is not None:
|
||||
return self._group_size
|
||||
counts: dict = {}
|
||||
for record in self.records:
|
||||
if record.trace.agent.trainable:
|
||||
group_id = episode_group_id(record.episode)
|
||||
counts[group_id] = counts.get(group_id, 0) + 1
|
||||
return max(counts.values(), default=0)
|
||||
self.group_size = group_size
|
||||
|
||||
@property
|
||||
def effective(self) -> EvalEpisodes:
|
||||
return EvalEpisodes(
|
||||
self.episodes,
|
||||
self.group_size,
|
||||
predicate=lambda record: not record.trace.has_error and record.trace.agent.trainable,
|
||||
group_size=self.group_size,
|
||||
)
|
||||
|
||||
@property
|
||||
|
||||
@@ -270,10 +270,10 @@ class Orchestrator:
|
||||
get_logger().info("Waiting for policy inference pool to be ready")
|
||||
await self.policy_inference.wait_for_ready(config.model.name)
|
||||
get_logger().success("Policy inference pool ready")
|
||||
# Build + ready pools for each env's frozen sampling source and the
|
||||
# Build + ready pools for each env's frozen generation source and the
|
||||
# algorithm's frozen reference model
|
||||
await asyncio.gather(
|
||||
*(env.sampler.setup() for env in self.train_envs),
|
||||
*(env.generation_source.setup() for env in self.train_envs),
|
||||
*(env.algorithm.setup() for env in self.train_envs),
|
||||
)
|
||||
|
||||
@@ -965,7 +965,7 @@ class Orchestrator:
|
||||
await self.policy_inference.stop()
|
||||
if self.train_envs is not None:
|
||||
for env in self.train_envs:
|
||||
for pool in (*env.sampler.connected_pools, *env.algorithm.connected_pools):
|
||||
for pool in (*env.generation_source.connected_pools, *env.algorithm.connected_pools):
|
||||
await pool.stop()
|
||||
|
||||
task = asyncio.create_task(teardown())
|
||||
|
||||
@@ -62,6 +62,11 @@ export MASTER_ADDR="${HOSTNAMES[0]}"
|
||||
export MASTER_PORT=29500
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
echo "MASTER_PORT=${MASTER_PORT}"
|
||||
{% if use_nccl_broadcast %}
|
||||
# The eval job has a separate allocation. Publish the trainer's NCCL host through
|
||||
# the shared run directory under this job ID.
|
||||
printf '%s\n' "$MASTER_ADDR" > "$OUTPUT_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
{% endif %}
|
||||
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
@@ -155,5 +160,8 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.sft.train \
|
||||
@ $CONFIG_PATH \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host 0.0.0.0 \
|
||||
{%- endif %}
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
LAUNCH_SH
|
||||
|
||||
@@ -23,9 +23,8 @@
|
||||
|
||||
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
|
||||
# DP rank behind a single router) plus the evals process and its env servers. The trainer
|
||||
# runs in a separate SLURM job and hands weights over via checkpoints on the shared
|
||||
# filesystem, so this job outlives the trainer and exits after evaluating the final
|
||||
# checkpoint (max_steps).
|
||||
# runs in a separate SLURM job. This job exits after evaluating the final weight
|
||||
# broadcast (max_steps).
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
@@ -71,6 +70,14 @@ export WANDB_PROGRAM="uv run sft"
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
{% if use_nccl_broadcast %}
|
||||
: "${TRAIN_JOB_ID:?TRAIN_JOB_ID is required for NCCL weight broadcast}"
|
||||
TRAIN_HOST_FILE="$OUTPUT_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
|
||||
until [ -s "$TRAIN_HOST_FILE" ]; do sleep 1; done
|
||||
export TRAIN_HOST=$(<"$TRAIN_HOST_FILE")
|
||||
rm -f "$TRAIN_HOST_FILE"
|
||||
echo "TRAIN_HOST=${TRAIN_HOST}"
|
||||
{% endif %}
|
||||
|
||||
# Single global router on node 0 fronts every per-rank endpoint; admin ops
|
||||
# (pause/update_weights/resume) bypass it and hit each rank directly.
|
||||
@@ -214,8 +221,8 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
# The evals process watches the trainer's weights dir on the shared filesystem and
|
||||
# drives the pool: data plane through the router, admin ops per rank.
|
||||
# The evals process watches trainer broadcast markers and drives the pool:
|
||||
# data plane through the router, admin ops per rank.
|
||||
{%- for key, value in evals_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
@@ -223,6 +230,9 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
@ $CONFIG_DIR/evals.json \
|
||||
--eval.client.base-url $INFER_URLS \
|
||||
--eval.client.admin-base-url $ADMIN_URLS \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host $TRAIN_HOST \
|
||||
{%- endif %}
|
||||
2>&1 | tee $OUTPUT_DIR/logs/evals.log &
|
||||
EVALS_PID=$!
|
||||
else
|
||||
|
||||
@@ -2,37 +2,27 @@ import bisect
|
||||
import gc
|
||||
import shutil
|
||||
import time
|
||||
import warnings
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from torch import Tensor, nn
|
||||
from torch import nn
|
||||
from torch.distributed.checkpoint.state_dict import get_state_dict, set_model_state_dict, set_state_dict
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
from torch.distributed.checkpoint.state_dict_saver import save as dcp_save
|
||||
from torch.distributed.checkpoint.stateful import Stateful
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.nn import Module
|
||||
from torch.optim.lr_scheduler import LRScheduler
|
||||
from torch.optim.optimizer import Optimizer
|
||||
from torchdata.stateful_dataloader import StatefulDataLoader
|
||||
from transformers.processing_utils import ProcessorMixin
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.shared import ResumeConfig
|
||||
from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
|
||||
from prime_rl.trainer.lora import get_lora_state, has_lora_layers, save_lora_config
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.configs.trainer import CheckpointConfig
|
||||
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
|
||||
from prime_rl.trainer.weights import (
|
||||
gather_weights_on_master,
|
||||
save_state_dict,
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path, get_weights_dir
|
||||
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -174,12 +164,6 @@ class CheckpointManager:
|
||||
"""Get the path to write the trainer checkpoint for a given step."""
|
||||
return get_step_path(self.ckpt_dir, step) / "trainer"
|
||||
|
||||
def mark_stable(self, step: int) -> None:
|
||||
"""Write STABLE file to indicate checkpoint is complete (for eval to safely read)."""
|
||||
if self.world.is_master:
|
||||
step_path = get_step_path(self.ckpt_dir, step)
|
||||
(step_path / "STABLE").touch()
|
||||
|
||||
def save_to_path(
|
||||
self,
|
||||
path: Path,
|
||||
@@ -322,229 +306,12 @@ class CheckpointManager:
|
||||
self.ckpt_steps = [step for step in self.ckpt_steps if step in steps_to_keep]
|
||||
|
||||
|
||||
class WeightCheckpointManager:
|
||||
"""Utility class to save HF-compatible weight checkpoints."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
output_dir: Path,
|
||||
config: WeightCheckpointConfig,
|
||||
lora_config: LoRAConfig | None = None,
|
||||
save_async: bool = False,
|
||||
keep_last: int | None = None,
|
||||
keep_interval: int | None = None,
|
||||
resume: ResumeConfig | None = None,
|
||||
):
|
||||
self.weights_dir = get_weights_dir(output_dir)
|
||||
self.config = config
|
||||
self.lora_config = lora_config
|
||||
self.logger = get_logger()
|
||||
self.world = get_world()
|
||||
if self.world.is_master:
|
||||
all_steps = get_all_ckpt_steps(self.weights_dir)
|
||||
if resume is not None and resume.step is not None:
|
||||
self.ckpt_steps = [s for s in all_steps if s <= resume.step]
|
||||
else:
|
||||
self.ckpt_steps = all_steps
|
||||
else:
|
||||
self.ckpt_steps = []
|
||||
self.keep_last = keep_last
|
||||
self.keep_interval = keep_interval
|
||||
|
||||
def get_step_path(self, step: int) -> Path:
|
||||
"""Get the path to write the weight checkpoint for a given step."""
|
||||
return get_step_path(self.weights_dir, step)
|
||||
|
||||
def mark_stable(self, step: int) -> None:
|
||||
"""Write STABLE file to indicate weight checkpoint is complete."""
|
||||
if self.world.is_master:
|
||||
step_path = self.get_step_path(step)
|
||||
(step_path / "STABLE").touch()
|
||||
|
||||
def get_run_adapter_state_dict(self) -> dict[str, Tensor]:
|
||||
lora_state_dict = {
|
||||
f"base_model.model.{key}": (value.full_tensor() if isinstance(value, DTensor) else value).to(
|
||||
"cpu", non_blocking=False
|
||||
)
|
||||
for key, value in get_lora_state().adapter_state_dict().items()
|
||||
}
|
||||
|
||||
if not lora_state_dict:
|
||||
raise ValueError("The LoRA state dict is empty. Something went wrong.")
|
||||
|
||||
return lora_state_dict
|
||||
|
||||
def save_to_path(
|
||||
self,
|
||||
path: Path,
|
||||
state_dict: dict[str, Tensor],
|
||||
lora_state_dict: dict[str, Tensor] | None,
|
||||
model,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
processor: ProcessorMixin | None = None,
|
||||
):
|
||||
"""Save HF-compatible weight checkpoint to a given path."""
|
||||
if self.world.is_master:
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
start_time = time.perf_counter()
|
||||
|
||||
self.logger.debug(f"Saving weight checkpoint to {path}")
|
||||
# Suppress torch.distributed warnings during checkpoint saving
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
|
||||
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
|
||||
|
||||
# Save weights
|
||||
save_state_dict(state_dict, path, self.config.save_format, self.config.save_sharded)
|
||||
|
||||
# Save model config, generation arguments and tokenizer
|
||||
model.config.save_pretrained(path)
|
||||
if model.generation_config:
|
||||
# training sets use_cache=False which can conflict with
|
||||
# cache_implementation — save with use_cache=True without
|
||||
# mutating the model's config
|
||||
from copy import deepcopy
|
||||
|
||||
gen_config = deepcopy(model.generation_config)
|
||||
gen_config.use_cache = True
|
||||
gen_config.save_pretrained(path)
|
||||
# Processor first: it saves its own (unmodified) tokenizer, which the
|
||||
# configured tokenizer (pad token, custom chat template) must override.
|
||||
if processor is not None:
|
||||
processor.save_pretrained(path)
|
||||
tokenizer.save_pretrained(path)
|
||||
|
||||
if lora_state_dict is not None:
|
||||
adapter_path = path / "lora_adapters"
|
||||
adapter_path.mkdir(parents=True, exist_ok=True)
|
||||
save_state_dict(
|
||||
lora_state_dict, adapter_path, self.config.save_format, save_sharded=False, adapter=True
|
||||
)
|
||||
if self.lora_config:
|
||||
save_lora_config(
|
||||
model,
|
||||
adapter_path,
|
||||
rank=self.lora_config.rank,
|
||||
alpha=self.lora_config.alpha,
|
||||
dropout=self.lora_config.dropout,
|
||||
)
|
||||
self.logger.debug(f"Saved weight checkpoint to {path} in {time.perf_counter() - start_time:.2f} seconds")
|
||||
|
||||
def save(
|
||||
self,
|
||||
step: int,
|
||||
model: nn.Module,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
processor: ProcessorMixin | None = None,
|
||||
):
|
||||
"""Save a HF-compatible weight-only checkpoint for a given step."""
|
||||
step_path = self.get_step_path(step)
|
||||
# Master-only mkdir + barrier: concurrent mkdir from every rank can
|
||||
# re-raise FileExistsError on a parallel FS (EEXIST + stale is_dir()).
|
||||
if self.world.is_master:
|
||||
step_path.mkdir(parents=True, exist_ok=True)
|
||||
torch.distributed.barrier()
|
||||
|
||||
# Gather all weights on master rank
|
||||
self.logger.debug("Gathering weights on master rank for weight checkpoint")
|
||||
start_time = time.perf_counter()
|
||||
state_dict = gather_weights_on_master(model, self.world.is_master, dtype=torch.bfloat16)
|
||||
self.logger.debug(f"Gathered weights on master rank in {time.perf_counter() - start_time:.2f} seconds")
|
||||
|
||||
# Remove tied weight keys to match original model format
|
||||
if getattr(model.config, "tie_word_embeddings", False):
|
||||
for key in getattr(model, "_tied_weights_keys", []):
|
||||
state_dict.pop(key, None)
|
||||
|
||||
if has_lora_layers(model) and self.config.save_adapter_separately:
|
||||
self.logger.debug("Getting run adapter state dict for weight checkpoint")
|
||||
start_time = time.perf_counter()
|
||||
lora_state_dict = self.get_run_adapter_state_dict()
|
||||
self.logger.debug(f"Got run adapter state dict in {time.perf_counter() - start_time:.2f} seconds")
|
||||
else:
|
||||
lora_state_dict = None
|
||||
|
||||
# Convert to HF hub format if needed
|
||||
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(state_dict):
|
||||
self.logger.debug("Converting PrimeRL format to HF format for weight checkpoint")
|
||||
start_time = time.perf_counter()
|
||||
model.convert_to_hf(state_dict)
|
||||
self.logger.debug(
|
||||
f"Converted PrimeRL format to HF format in {time.perf_counter() - start_time:.2f} seconds"
|
||||
)
|
||||
else:
|
||||
from transformers.core_model_loading import revert_weight_conversion
|
||||
|
||||
self.logger.debug("Reverting transformers internal format to HF hub format for weight checkpoint")
|
||||
start_time = time.perf_counter()
|
||||
state_dict = revert_weight_conversion(model, state_dict)
|
||||
self.logger.debug(f"Reverted to HF hub format in {time.perf_counter() - start_time:.2f} seconds")
|
||||
|
||||
# Save weight checkpoint on master rank
|
||||
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer, processor)
|
||||
self.mark_stable(step)
|
||||
bisect.insort(self.ckpt_steps, step)
|
||||
|
||||
def maybe_clean(self) -> None:
|
||||
"""Deletes past checkpoints based on keep_last and keep_interval policies. No-op if both are None."""
|
||||
if self.keep_last is None and self.keep_interval is None:
|
||||
return
|
||||
|
||||
# Get all the checkpoint steps to delete
|
||||
assert list(self.ckpt_steps) == sorted(self.ckpt_steps)
|
||||
|
||||
# Determine which steps to keep
|
||||
steps_to_keep = set()
|
||||
|
||||
# Always keep the newest weight checkpoint — it is the current policy. With
|
||||
# keep_interval-only cleaning, a freshly saved non-aligned final checkpoint would
|
||||
# otherwise be deleted immediately, and the online evals would wait for the
|
||||
# max_steps checkpoint forever.
|
||||
if self.ckpt_steps:
|
||||
steps_to_keep.add(self.ckpt_steps[-1])
|
||||
|
||||
# Keep the most recent keep_last steps
|
||||
if self.keep_last is not None:
|
||||
steps_to_keep.update(self.ckpt_steps[-self.keep_last :])
|
||||
|
||||
# Keep steps at keep_interval intervals
|
||||
if self.keep_interval is not None:
|
||||
for step in self.ckpt_steps:
|
||||
if step % self.keep_interval == 0:
|
||||
steps_to_keep.add(step)
|
||||
|
||||
# Delete steps not in steps_to_keep (only master rank deletes to avoid race condition)
|
||||
ckpt_steps_to_delete = [step for step in self.ckpt_steps if step not in steps_to_keep]
|
||||
if self.world.is_master:
|
||||
for ckpt_step in ckpt_steps_to_delete:
|
||||
ckpt_path = self.get_step_path(ckpt_step)
|
||||
if ckpt_path.exists():
|
||||
self.logger.debug(f"Removing past checkpoint for step {ckpt_step} ({ckpt_path})")
|
||||
_try_rmtree(ckpt_path, self.logger)
|
||||
|
||||
# Update checkpoint steps
|
||||
self.ckpt_steps = [step for step in self.ckpt_steps if step in steps_to_keep]
|
||||
|
||||
|
||||
def setup_ckpt_managers(
|
||||
def setup_ckpt_manager(
|
||||
output_dir: Path,
|
||||
ckpt_config: CheckpointConfig | None,
|
||||
lora_config: LoRAConfig | None = None,
|
||||
resume: ResumeConfig | None = None,
|
||||
) -> tuple[CheckpointManager, WeightCheckpointManager | None]:
|
||||
) -> CheckpointManager:
|
||||
"""The checkpoint manager always exists: ``resume`` decides whether it loads,
|
||||
``ckpt`` whether it saves (a resume without ``ckpt`` loads but saves nothing)."""
|
||||
ckpt_output_dir = (ckpt_config.output_dir if ckpt_config else None) or output_dir
|
||||
ckpt_manager = CheckpointManager(ckpt_output_dir, ckpt_config or CheckpointConfig(), resume)
|
||||
if ckpt_config and ckpt_config.weights and not ckpt_config.skip_gather_master_weights:
|
||||
weight_ckpt_manager = WeightCheckpointManager(
|
||||
ckpt_output_dir,
|
||||
ckpt_config.weights,
|
||||
lora_config=lora_config,
|
||||
keep_last=ckpt_config.keep_last,
|
||||
keep_interval=ckpt_config.keep_interval,
|
||||
resume=resume,
|
||||
)
|
||||
else:
|
||||
weight_ckpt_manager = None
|
||||
return ckpt_manager, weight_ckpt_manager
|
||||
return CheckpointManager(ckpt_output_dir, ckpt_config or CheckpointConfig(), resume)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import re
|
||||
from typing import Callable, Dict, List
|
||||
from typing import Callable, List
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
@@ -328,23 +328,6 @@ def has_lora_layers(model: nn.Module) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def clean_lora_state_dict(state_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
|
||||
"""Remove LoRA parameters and fix LoRA base layer key names for HF compatibility."""
|
||||
clean_state_dict = {}
|
||||
|
||||
for key, value in state_dict.items():
|
||||
if "lora_A" in key or "lora_B" in key:
|
||||
continue
|
||||
|
||||
if ".base_layer." in key:
|
||||
new_key = key.replace(".base_layer.", ".")
|
||||
clean_state_dict[new_key] = value
|
||||
else:
|
||||
clean_state_dict[key] = value
|
||||
|
||||
return clean_state_dict
|
||||
|
||||
|
||||
def save_lora_config(model: nn.Module, save_path, rank: int, alpha: float, dropout: float) -> None:
|
||||
"""
|
||||
Save LoRA configuration as JSON for adapter portability.
|
||||
|
||||
@@ -57,16 +57,16 @@ from prime_rl.trainer.models.layers.moe import LatentMoE, MoE, TokenChoiceTopKRo
|
||||
from prime_rl.trainer.models.layers.mxfp8_grouped_gemm import apply_mxfp8_moe_grouped_gemm
|
||||
from prime_rl.trainer.models.layers.mxfp8_linear import replace_linear_with_mxfp8_linear
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.weights import (
|
||||
load_state_dict,
|
||||
load_state_dict_keys,
|
||||
save_state_dict,
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
from prime_rl.utils.utils import format_time
|
||||
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
|
||||
from prime_rl.utils.weights import (
|
||||
load_state_dict,
|
||||
load_state_dict_keys,
|
||||
save_state_dict,
|
||||
)
|
||||
|
||||
|
||||
def pre_download_model(model_name: str, *, skip_weights: bool = False) -> None:
|
||||
@@ -601,11 +601,6 @@ def get_model(
|
||||
|
||||
is_vlm_training = config.vlm is not None
|
||||
|
||||
if "Qwen3.5" in config.name or "qwen3_5" in config.name.lower():
|
||||
_patch_qwen3_5_text_position_ids()
|
||||
_patch_qwen3_5_moe_conversion_mapping()
|
||||
_patch_qwen3_5_linear_attn_varlen()
|
||||
|
||||
model_config = cast(
|
||||
PretrainedConfig,
|
||||
AutoConfig.from_pretrained(
|
||||
@@ -636,8 +631,8 @@ def get_model(
|
||||
|
||||
_hub_kernels._kernels_enabled = True
|
||||
|
||||
# Fallback Qwen3.5 patch detection from loaded config model_type
|
||||
if getattr(model_config, "model_type", "").startswith("qwen3_5_moe"):
|
||||
# Qwen3.6 and Qwen3.8 reuse the Qwen3.5 architecture, so match on model_type, not repo name.
|
||||
if getattr(model_config, "model_type", "").startswith("qwen3_5"):
|
||||
_patch_qwen3_5_text_position_ids()
|
||||
_patch_qwen3_5_moe_conversion_mapping()
|
||||
_patch_qwen3_5_linear_attn_varlen()
|
||||
@@ -970,16 +965,15 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
model.to_empty(device=device)
|
||||
torch.distributed.barrier()
|
||||
|
||||
def _init_buffers_post_meta():
|
||||
if isinstance(model, PreTrainedModelPrimeRL):
|
||||
model.init_buffers_post_meta()
|
||||
else:
|
||||
fix_model_post_empty(model)
|
||||
# Must run before any weight loading: reinit can zero persistent buffers that ship in checkpoints
|
||||
if isinstance(model, PreTrainedModelPrimeRL):
|
||||
model.init_buffers_post_meta()
|
||||
else:
|
||||
fix_model_post_empty(model)
|
||||
|
||||
logger = get_logger()
|
||||
if config.debug.random_init:
|
||||
logger.warning("Randomly initializing model. Skipping loading weights from HF.")
|
||||
_init_buffers_post_meta()
|
||||
_move_buffers_to_cuda(model, config)
|
||||
return
|
||||
|
||||
@@ -1047,7 +1041,6 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
# Restore weight tying broken by to_empty() for HF models
|
||||
if not isinstance(model, PreTrainedModelPrimeRL) and model.config.tie_word_embeddings:
|
||||
model.tie_weights()
|
||||
_init_buffers_post_meta()
|
||||
|
||||
_move_buffers_to_cuda(model, config)
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ from prime_rl.utils.act_offloading import maybe_activation_offloading
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch.profiler import profile, ProfilerActivity, record_function
|
||||
from prime_rl.trainer.ckpt import Progress, setup_ckpt_managers
|
||||
from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.trainer.optim import setup_optimizer
|
||||
from prime_rl.trainer.scheduler import setup_scheduler
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
@@ -39,7 +39,6 @@ from prime_rl.trainer.rl.token_export import setup_token_exporter
|
||||
from prime_rl.trainer.model import (
|
||||
forward,
|
||||
get_full_offload_dtype_policy,
|
||||
setup_tokenizer,
|
||||
setup_model,
|
||||
is_tt_moe_model,
|
||||
get_load_balance_stats,
|
||||
@@ -128,10 +127,8 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Check for checkpoint to resume from
|
||||
checkpoint_step = None
|
||||
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
|
||||
ckpt_manager, weight_ckpt_manager = setup_ckpt_managers(
|
||||
config.output_dir, config.ckpt, config.model.lora, resume=config.resume
|
||||
)
|
||||
logger.info(f"Initializing checkpoint manager ({config.ckpt})")
|
||||
ckpt_manager = setup_ckpt_manager(config.output_dir, config.ckpt, resume=config.resume)
|
||||
|
||||
if config.resume is not None:
|
||||
if config.resume.dir is not None:
|
||||
@@ -146,9 +143,6 @@ def train(config: TrainerConfig):
|
||||
loading_from_ckpt_later = checkpoint_step is not None
|
||||
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
|
||||
|
||||
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
|
||||
raise ValueError("Packed multimodal training requires model support")
|
||||
|
||||
@@ -611,23 +605,12 @@ def train(config: TrainerConfig):
|
||||
and not is_last_step
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
|
||||
@@ -742,16 +725,10 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Write final checkpoint
|
||||
if config.ckpt is not None:
|
||||
if not config.ckpt.weights_only:
|
||||
logger.info("Writing final checkpoint")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
logger.info("Writing final checkpoint")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info("Writing final weight checkpoint")
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
|
||||
if gradient_manager is not None:
|
||||
gradient_manager.close()
|
||||
|
||||
|
||||
@@ -17,10 +17,12 @@ from prime_rl.trainer.models.layers.attn import substitute_ring_attn
|
||||
from prime_rl.utils.act_offloading import maybe_activation_offloading
|
||||
import torch
|
||||
from torch.profiler import profile, ProfilerActivity, record_function
|
||||
from prime_rl.trainer.ckpt import Progress, setup_ckpt_managers
|
||||
from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.utils.pathing import resolve_latest_ckpt_step
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.trainer import CheckpointConfig
|
||||
from prime_rl.transports.weights import setup_weight_broadcast
|
||||
from prime_rl.transports.weights.filesystem import FileSystemWeightBroadcast
|
||||
from prime_rl.utils.cp import setup_cp_params, shard_for_cp
|
||||
from prime_rl.trainer.lora import get_lora_state
|
||||
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
|
||||
@@ -137,10 +139,8 @@ def train(config: SFTConfig):
|
||||
from prime_rl.utils.cp import setup_model_cp, setup_sparse_mla_cp
|
||||
|
||||
# Set up checkpoint manager
|
||||
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
|
||||
ckpt_manager, weight_ckpt_manager = setup_ckpt_managers(
|
||||
config.run_dir, config.ckpt, config.model.lora, resume=config.resume
|
||||
)
|
||||
logger.info(f"Initializing checkpoint manager ({config.ckpt})")
|
||||
ckpt_manager = setup_ckpt_manager(config.run_dir, config.ckpt, resume=config.resume)
|
||||
|
||||
checkpoint_step = None
|
||||
if config.resume is not None:
|
||||
@@ -396,14 +396,35 @@ def train(config: SFTConfig):
|
||||
|
||||
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
|
||||
|
||||
# Online evals reload the trainer's HF weight checkpoints from disk, so a weight
|
||||
# checkpoint must land at every step an eval env is due (deterministic from the
|
||||
# config — all ranks agree on the collective save).
|
||||
# A broadcast must land at every step an online eval env is due. The schedule is
|
||||
# deterministic, so all ranks agree when to enter the transport collective.
|
||||
online_eval_intervals = sorted({source.interval for source in config.eval.source}) if config.eval else []
|
||||
|
||||
def is_online_eval_step(step: int) -> bool:
|
||||
return any(step % interval == 0 for interval in online_eval_intervals)
|
||||
|
||||
weight_broadcast = None
|
||||
if online_eval_intervals:
|
||||
assert config.weight_broadcast is not None
|
||||
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
weight_broadcast = setup_weight_broadcast(
|
||||
config.run_dir,
|
||||
config.weight_broadcast,
|
||||
parallel_dims,
|
||||
config.model.lora,
|
||||
)
|
||||
if (
|
||||
checkpoint_step is not None
|
||||
and isinstance(weight_broadcast, FileSystemWeightBroadcast)
|
||||
and not weight_broadcast.is_stable(checkpoint_step)
|
||||
):
|
||||
# Rebroadcast the resumed policy so the evals process can re-trigger at
|
||||
# the resume step (older broadcasts may have been cleaned). Skipped when
|
||||
# the previous run's broadcast survived: rewriting the same dir in place
|
||||
# would race an evals process already reloading it.
|
||||
weight_broadcast.broadcast_weights(model, step=checkpoint_step)
|
||||
weight_broadcast.clean_older(checkpoint_step)
|
||||
|
||||
logger.info(f"Starting training loop (max_steps={config.max_steps or 'infinite'})")
|
||||
max_memory = torch.cuda.mem_get_info()[1] / 1024**3 # GiB
|
||||
is_first_step = True
|
||||
@@ -534,30 +555,26 @@ def train(config: SFTConfig):
|
||||
scheduler.step()
|
||||
|
||||
# Checkpoint the step we just finished. The last step's checkpoint is written once after
|
||||
# the loop, so skip it here to avoid a double-save. Weight checkpoints additionally land
|
||||
# at online-eval steps — they are how the inference server picks up the new policy.
|
||||
# the loop, so skip it here to avoid a double-save. Weight broadcasts land at
|
||||
# online-eval steps — they are how the inference server picks up the new policy.
|
||||
save_ckpt_time = 0
|
||||
is_ckpt_step = bool(config.ckpt and config.ckpt.interval) and progress.step % config.ckpt.interval == 0
|
||||
if ckpt_manager is not None and is_ckpt_step and not is_last_step:
|
||||
if not config.ckpt.weights_only:
|
||||
# Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
if (
|
||||
weight_ckpt_manager is not None
|
||||
and not is_last_step
|
||||
and (is_ckpt_step or is_online_eval_step(progress.step))
|
||||
):
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer, processor)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
broadcast_weights_time = 0
|
||||
if weight_broadcast is not None and not is_last_step and is_online_eval_step(progress.step):
|
||||
logger.info(f"Broadcasting weights at step {progress.step}")
|
||||
broadcast_start_time = time.perf_counter()
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step)
|
||||
if isinstance(weight_broadcast, FileSystemWeightBroadcast):
|
||||
weight_broadcast.clean_older(progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_start_time
|
||||
|
||||
# Optionally, dump memory snapshot
|
||||
if memory_profiler is not None:
|
||||
@@ -648,6 +665,7 @@ def train(config: SFTConfig):
|
||||
time_metrics = {
|
||||
"time/step": step_time,
|
||||
"time/save_ckpt": save_ckpt_time,
|
||||
"time/broadcast_weights": broadcast_weights_time,
|
||||
"time/forward_backward": forward_backward_time,
|
||||
"step": progress.step,
|
||||
}
|
||||
@@ -682,16 +700,16 @@ def train(config: SFTConfig):
|
||||
|
||||
# Write final checkpoint
|
||||
if config.ckpt is not None:
|
||||
if not config.ckpt.weights_only:
|
||||
logger.info("Writing final checkpoint")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
logger.info("Writing final checkpoint")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Write final weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info("Writing final weight checkpoint")
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer, processor)
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
# Broadcast the final weights so the evals process can run its forced final epoch
|
||||
if weight_broadcast is not None:
|
||||
logger.info("Broadcasting final weights")
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step)
|
||||
if isinstance(weight_broadcast, FileSystemWeightBroadcast):
|
||||
weight_broadcast.clean_older(progress.step)
|
||||
|
||||
if gradient_manager is not None:
|
||||
gradient_manager.close()
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
import json
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Literal, cast
|
||||
|
||||
import torch
|
||||
from huggingface_hub import split_torch_state_dict_into_shards
|
||||
from safetensors import safe_open
|
||||
from safetensors.torch import save_file
|
||||
from torch import Tensor, nn
|
||||
from torch.distributed.checkpoint.state_dict import _get_fqns as get_fqns
|
||||
from torch.distributed.tensor import DTensor
|
||||
from transformers.utils import (
|
||||
ADAPTER_SAFE_WEIGHTS_NAME,
|
||||
ADAPTER_WEIGHTS_NAME,
|
||||
SAFE_WEIGHTS_INDEX_NAME,
|
||||
SAFE_WEIGHTS_NAME,
|
||||
WEIGHTS_INDEX_NAME,
|
||||
WEIGHTS_NAME,
|
||||
)
|
||||
|
||||
from prime_rl.trainer.lora import (
|
||||
clean_lora_state_dict,
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def load_state_dict_keys(save_dir: Path) -> list[str]:
|
||||
"""Load only the key names from safetensor files without reading tensor data."""
|
||||
keys: list[str] = []
|
||||
for safetensor_path in save_dir.glob("*.safetensors"):
|
||||
with safe_open(safetensor_path, framework="pt", device="cpu") as f:
|
||||
keys.extend(f.keys())
|
||||
return keys
|
||||
|
||||
|
||||
def load_state_dict(save_dir: Path) -> dict[str, Tensor]:
|
||||
"""Load a state dict from a local directory with safetensor files."""
|
||||
safetensors_paths = list(save_dir.glob("*.safetensors"))
|
||||
state_dict = {}
|
||||
for safetensor_path in safetensors_paths:
|
||||
with safe_open(safetensor_path, framework="pt", device="cpu") as f:
|
||||
for key in f.keys():
|
||||
state_dict[key] = f.get_tensor(key)
|
||||
return state_dict
|
||||
|
||||
|
||||
def save_state_dict(
|
||||
state_dict: dict[str, Tensor],
|
||||
save_dir: Path,
|
||||
save_format: Literal["torch", "safetensors"] = "safetensors",
|
||||
save_sharded: bool = True,
|
||||
adapter: bool = False,
|
||||
):
|
||||
"""Save a state dict to a local directory in safetensors or torch format."""
|
||||
logger = get_logger()
|
||||
if adapter:
|
||||
weights_name = ADAPTER_SAFE_WEIGHTS_NAME if save_format == "safetensors" else ADAPTER_WEIGHTS_NAME
|
||||
else:
|
||||
weights_name = SAFE_WEIGHTS_NAME if save_format == "safetensors" else WEIGHTS_NAME
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
if save_sharded:
|
||||
filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors")
|
||||
state_dict_split = split_torch_state_dict_into_shards(
|
||||
state_dict,
|
||||
filename_pattern=filename_pattern,
|
||||
)
|
||||
if state_dict_split.is_sharded:
|
||||
filenames = state_dict_split.filename_to_tensors.keys()
|
||||
logger.debug(f"Saving sharded weights to {len(filenames)} files: ({', '.join(filenames)})")
|
||||
else:
|
||||
logger.debug(f"Saving unsharded weights to {weights_name}")
|
||||
|
||||
# Save weights (https://github.com/huggingface/transformers/blob/cd74917ffc3e8f84e4a886052c5ab32b7ac623cc/src/transformers/modeling_utils.py#L4252)
|
||||
filename_to_tensors = state_dict_split.filename_to_tensors.items()
|
||||
for shard_file, tensors in filename_to_tensors:
|
||||
shard = {}
|
||||
for tensor in tensors:
|
||||
assert isinstance(state_dict[tensor], Tensor)
|
||||
shard[tensor] = state_dict[tensor].contiguous()
|
||||
# delete reference, see https://github.com/huggingface/transformers/pull/34890
|
||||
del state_dict[tensor]
|
||||
if save_format == "safetensors":
|
||||
save_file(shard, save_dir / shard_file, metadata={"format": "pt"})
|
||||
else:
|
||||
torch.save(shard, save_dir / shard_file)
|
||||
del state_dict
|
||||
|
||||
# Save index (https://github.com/huggingface/transformers/blob/cd74917ffc3e8f84e4a886052c5ab32b7ac623cc/src/transformers/modeling_utils.py#L4301)
|
||||
if state_dict_split.is_sharded:
|
||||
index = {
|
||||
"metadata": {**state_dict_split.metadata},
|
||||
"weight_map": state_dict_split.tensor_to_filename,
|
||||
}
|
||||
save_index_file = SAFE_WEIGHTS_INDEX_NAME if save_format == "safetensors" else WEIGHTS_INDEX_NAME
|
||||
save_index_file = save_dir / save_index_file
|
||||
# Save the index as well
|
||||
with open(save_index_file, "w", encoding="utf-8") as f:
|
||||
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
|
||||
f.write(content)
|
||||
else:
|
||||
if save_format == "safetensors":
|
||||
save_file(state_dict, save_dir / weights_name, metadata={"format": "pt"})
|
||||
else:
|
||||
torch.save(state_dict, save_dir / weights_name)
|
||||
|
||||
|
||||
def gather_weights_on_master(
|
||||
model: nn.Module, is_master: bool, dtype: torch.dtype = torch.bfloat16
|
||||
) -> dict[str, Tensor]:
|
||||
"""Gather distributed weights on CPU on master rank."""
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
|
||||
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
|
||||
|
||||
cpu_state = {}
|
||||
for key, value in model.state_dict().items():
|
||||
if isinstance(value, DTensor):
|
||||
# only gather after the downcast to dtype as it will be faster
|
||||
value = cast(DTensor, value.to(dtype)).full_tensor()
|
||||
|
||||
if is_master:
|
||||
key = get_fqns(model, key)
|
||||
assert len(key) == 1
|
||||
key = next(iter(key))
|
||||
# TODO(Sami) Blocking to avoid race condition, should make non-blocking long-term tho
|
||||
cpu_state[key] = value.to("cpu", non_blocking=False)
|
||||
torch.distributed.barrier()
|
||||
|
||||
# Always clean up the state dict for HF compatibility
|
||||
if any(".base_layer." in key or "lora_A" in key or "lora_B" in key for key in cpu_state.keys()):
|
||||
cpu_state = clean_lora_state_dict(cpu_state)
|
||||
|
||||
return cpu_state
|
||||
@@ -1,21 +1,23 @@
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig, LoRAConfig
|
||||
from prime_rl.trainer.lora import get_lora_state, save_lora_config
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.utils import maybe_clean
|
||||
from prime_rl.trainer.weights import (
|
||||
gather_weights_on_master,
|
||||
save_state_dict,
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.transports.weights.base import WeightBroadcast
|
||||
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
|
||||
from prime_rl.utils.utils import get_all_ckpt_steps, get_broadcast_dir, get_step_path
|
||||
from prime_rl.utils.weights import (
|
||||
convert_state_dict_to_hf,
|
||||
gather_weights_parallel,
|
||||
save_state_dict,
|
||||
save_state_dict_parallel,
|
||||
)
|
||||
|
||||
|
||||
class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
@@ -25,12 +27,8 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
self, output_dir: Path, config: FileSystemWeightBroadcastConfig, lora_config: LoRAConfig | None = None
|
||||
):
|
||||
super().__init__(output_dir, lora_config)
|
||||
self.save_format: Literal["safetensors", "torch"] = config.save_format
|
||||
self.save_sharded = config.save_sharded if lora_config is None else False
|
||||
self.world = get_world()
|
||||
self.logger.debug(
|
||||
f"Filesystem broadcast initialized (save_format={config.save_format}, save_sharded={self.save_sharded})"
|
||||
)
|
||||
self.logger.debug("Filesystem broadcast initialized")
|
||||
|
||||
def broadcast_weights(self, model: nn.Module, step: int) -> None:
|
||||
"""Broadcast weights by saving a HF-compatible checkpoint to shared filesystem and notifies the orchestrator."""
|
||||
@@ -38,6 +36,10 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
start_time = time.perf_counter()
|
||||
adapter_only = self.lora_config is not None
|
||||
|
||||
save_dir = get_step_path(get_broadcast_dir(self.output_dir), step)
|
||||
if self.world.is_master:
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if adapter_only:
|
||||
# All ranks must participate in DTensor gathering, but only master saves
|
||||
state_dict = get_lora_state().adapter_state_dict()
|
||||
@@ -46,22 +48,9 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
value = value.full_tensor()
|
||||
if self.world.is_master:
|
||||
state_dict[key] = value.to("cpu", non_blocking=False)
|
||||
else:
|
||||
state_dict = gather_weights_on_master(model, is_master=self.world.is_master)
|
||||
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(state_dict):
|
||||
model.convert_to_hf(state_dict)
|
||||
else:
|
||||
from transformers.core_model_loading import revert_weight_conversion
|
||||
|
||||
state_dict = revert_weight_conversion(model, state_dict)
|
||||
|
||||
if self.world.is_master:
|
||||
save_dir = get_step_path(get_broadcast_dir(self.output_dir), step)
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self.logger.debug(f"Saving weights to {save_dir}")
|
||||
save_state_dict(state_dict, save_dir, self.save_format, self.save_sharded, adapter=adapter_only)
|
||||
if adapter_only:
|
||||
if self.world.is_master:
|
||||
self.logger.debug(f"Saving weights to {save_dir}")
|
||||
save_state_dict(state_dict, save_dir, save_sharded=False, adapter=True)
|
||||
save_lora_config(
|
||||
model,
|
||||
save_dir,
|
||||
@@ -69,7 +58,14 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
alpha=self.lora_config.alpha,
|
||||
dropout=self.lora_config.dropout,
|
||||
)
|
||||
else:
|
||||
dist.barrier()
|
||||
state_dict = gather_weights_parallel(model)
|
||||
state_dict = convert_state_dict_to_hf(model, state_dict)
|
||||
self.logger.debug(f"Saving weights to {save_dir}")
|
||||
save_state_dict_parallel(state_dict, save_dir)
|
||||
|
||||
if self.world.is_master:
|
||||
self._notify_orchestrator(save_dir)
|
||||
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
|
||||
|
||||
@@ -80,3 +76,16 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
|
||||
def maybe_clean(self, step: int, interval_to_keep: int | None):
|
||||
maybe_clean(get_broadcast_dir(self.output_dir), step, interval_to_keep)
|
||||
|
||||
def is_stable(self, step: int) -> bool:
|
||||
"""Whether a complete broadcast for ``step`` is already on disk."""
|
||||
return (get_step_path(get_broadcast_dir(self.output_dir), step) / "STABLE").exists()
|
||||
|
||||
def clean_older(self, step: int) -> None:
|
||||
"""Remove all broadcast dirs older than ``step``, keeping only the newest."""
|
||||
if not self.world.is_master:
|
||||
return
|
||||
broadcast_dir = get_broadcast_dir(self.output_dir)
|
||||
for old_step in get_all_ckpt_steps(broadcast_dir):
|
||||
if old_step < step:
|
||||
shutil.rmtree(get_step_path(broadcast_dir, old_step), ignore_errors=True)
|
||||
|
||||
@@ -98,10 +98,6 @@ def get_ckpt_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "checkpoints"
|
||||
|
||||
|
||||
def get_weights_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "weights"
|
||||
|
||||
|
||||
def get_rollout_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "rollouts"
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ from prime_rl.utils.pathing import (
|
||||
get_log_dir,
|
||||
get_rollout_dir,
|
||||
get_step_path,
|
||||
get_weights_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
sync_wait_for_path,
|
||||
wait_for_path,
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import json
|
||||
import re
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from huggingface_hub import split_torch_state_dict_into_shards
|
||||
from safetensors import safe_open
|
||||
from safetensors.torch import save_file
|
||||
from torch import Tensor, nn
|
||||
from torch.distributed.checkpoint.state_dict import _get_fqns as get_fqns
|
||||
from torch.distributed.tensor import DTensor
|
||||
from transformers.utils import (
|
||||
ADAPTER_SAFE_WEIGHTS_NAME,
|
||||
SAFE_WEIGHTS_INDEX_NAME,
|
||||
SAFE_WEIGHTS_NAME,
|
||||
)
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def load_state_dict_keys(save_dir: Path) -> list[str]:
|
||||
"""Load only the key names from safetensor files without reading tensor data."""
|
||||
keys: list[str] = []
|
||||
for safetensor_path in save_dir.glob("*.safetensors"):
|
||||
with safe_open(safetensor_path, framework="pt", device="cpu") as f:
|
||||
keys.extend(f.keys())
|
||||
return keys
|
||||
|
||||
|
||||
def load_state_dict(save_dir: Path) -> dict[str, Tensor]:
|
||||
"""Load a state dict from a local directory with safetensor files."""
|
||||
safetensors_paths = list(save_dir.glob("*.safetensors"))
|
||||
state_dict = {}
|
||||
for safetensor_path in safetensors_paths:
|
||||
with safe_open(safetensor_path, framework="pt", device="cpu") as f:
|
||||
for key in f.keys():
|
||||
state_dict[key] = f.get_tensor(key)
|
||||
return state_dict
|
||||
|
||||
|
||||
def save_state_dict(
|
||||
state_dict: dict[str, Tensor],
|
||||
save_dir: Path,
|
||||
save_sharded: bool = True,
|
||||
adapter: bool = False,
|
||||
):
|
||||
"""Save a state dict to a local directory as safetensors."""
|
||||
logger = get_logger()
|
||||
weights_name = ADAPTER_SAFE_WEIGHTS_NAME if adapter else SAFE_WEIGHTS_NAME
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
if save_sharded:
|
||||
filename_pattern = weights_name.replace(".safetensors", "{suffix}.safetensors")
|
||||
state_dict_split = split_torch_state_dict_into_shards(
|
||||
state_dict,
|
||||
filename_pattern=filename_pattern,
|
||||
)
|
||||
if state_dict_split.is_sharded:
|
||||
filenames = state_dict_split.filename_to_tensors.keys()
|
||||
logger.debug(f"Saving sharded weights to {len(filenames)} files: ({', '.join(filenames)})")
|
||||
else:
|
||||
logger.debug(f"Saving unsharded weights to {weights_name}")
|
||||
|
||||
# Save weights (https://github.com/huggingface/transformers/blob/cd74917ffc3e8f84e4a886052c5ab32b7ac623cc/src/transformers/modeling_utils.py#L4252)
|
||||
filename_to_tensors = state_dict_split.filename_to_tensors.items()
|
||||
for shard_file, tensors in filename_to_tensors:
|
||||
shard = {}
|
||||
for tensor in tensors:
|
||||
assert isinstance(state_dict[tensor], Tensor)
|
||||
shard[tensor] = state_dict[tensor].contiguous()
|
||||
# delete reference, see https://github.com/huggingface/transformers/pull/34890
|
||||
del state_dict[tensor]
|
||||
save_file(shard, save_dir / shard_file, metadata={"format": "pt"})
|
||||
del state_dict
|
||||
|
||||
# Save index (https://github.com/huggingface/transformers/blob/cd74917ffc3e8f84e4a886052c5ab32b7ac623cc/src/transformers/modeling_utils.py#L4301)
|
||||
if state_dict_split.is_sharded:
|
||||
index = {
|
||||
"metadata": {**state_dict_split.metadata},
|
||||
"weight_map": state_dict_split.tensor_to_filename,
|
||||
}
|
||||
save_index_file = save_dir / SAFE_WEIGHTS_INDEX_NAME
|
||||
# Save the index as well
|
||||
with open(save_index_file, "w", encoding="utf-8") as f:
|
||||
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
|
||||
f.write(content)
|
||||
else:
|
||||
save_file(state_dict, save_dir / weights_name, metadata={"format": "pt"})
|
||||
|
||||
|
||||
def convert_state_dict_to_hf(model: nn.Module, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""Convert a (possibly rank-partial) training-format state dict to HF hub format.
|
||||
|
||||
Format detection uses the model's full key set, so a partial dict (one rank's
|
||||
slice) converts the same way as the full state dict would.
|
||||
"""
|
||||
full_keys = dict.fromkeys(resolve_fqn(model, key) for key in model.state_dict().keys())
|
||||
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(full_keys):
|
||||
# PrimeRL custom model holding weights in prime format: apply the model's
|
||||
# declarative prime->HF conversion chain (renames, expert stack/unstack).
|
||||
return model.convert_to_hf(state_dict)
|
||||
else:
|
||||
# Plain transformers model: undo the key renames transformers applied when
|
||||
# it loaded the HF checkpoint.
|
||||
from transformers.core_model_loading import revert_weight_conversion
|
||||
|
||||
return revert_weight_conversion(model, state_dict)
|
||||
|
||||
|
||||
def resolve_fqn(model: nn.Module, key: str) -> str:
|
||||
"""Resolve a state-dict key to the parameter's canonical fully-qualified name.
|
||||
|
||||
Strips wrapper prefixes that training composes onto module paths, e.g. with
|
||||
``torch.compile`` the key ``model._orig_mod.layers.0.self_attn.q_proj.weight``
|
||||
resolves to ``model.layers.0.self_attn.q_proj.weight`` — the name the tensor
|
||||
has in the HF checkpoint.
|
||||
"""
|
||||
fqns = get_fqns(model, key)
|
||||
assert len(fqns) == 1
|
||||
return next(iter(fqns))
|
||||
|
||||
|
||||
_LAYER_RE = re.compile(r"^(.*?\blayers\.\d+)\.")
|
||||
|
||||
|
||||
def partition_weights(state_dict: dict[str, Tensor], world_size: int, dtype: torch.dtype) -> dict[str, int]:
|
||||
"""Assign each state-dict key an owner rank, balanced by byte size.
|
||||
|
||||
All keys of one decoder layer share an owner, so per-rank prime->HF conversion
|
||||
(which stacks/unstacks tensors within a layer) always sees complete layers.
|
||||
"""
|
||||
key_to_unit: dict[str, str] = {}
|
||||
unit_bytes: dict[str, int] = {}
|
||||
for key, value in state_dict.items():
|
||||
match = _LAYER_RE.match(key)
|
||||
unit = match.group(1) if match else ""
|
||||
key_to_unit[key] = unit
|
||||
itemsize = dtype.itemsize if isinstance(value, DTensor) else value.element_size()
|
||||
unit_bytes[unit] = unit_bytes.get(unit, 0) + value.numel() * itemsize
|
||||
loads = [0] * world_size
|
||||
unit_owner: dict[str, int] = {}
|
||||
for unit in sorted(unit_bytes, key=lambda unit: (-unit_bytes[unit], unit)):
|
||||
owner = min(range(world_size), key=lambda rank: loads[rank])
|
||||
unit_owner[unit] = owner
|
||||
loads[owner] += unit_bytes[unit]
|
||||
return {key: unit_owner[unit] for key, unit in key_to_unit.items()}
|
||||
|
||||
|
||||
def gather_weights_parallel(model: nn.Module, dtype: torch.dtype = torch.bfloat16) -> dict[str, Tensor]:
|
||||
"""Gather distributed weights cooperatively, each rank keeping a slice on CPU.
|
||||
|
||||
Every rank participates in the per-tensor all-gathers (a ``full_tensor`` call is
|
||||
collective and materializes the full tensor on all ranks anyway), but instead of
|
||||
only the master keeping everything, each rank copies its owned slice to CPU —
|
||||
so the D2H traffic and the shard writes are split across ranks. The copies are
|
||||
plain blocking transfers; no stream-ordering assumptions.
|
||||
"""
|
||||
world = get_world()
|
||||
owners = partition_weights(model.state_dict(), world.world_size, dtype)
|
||||
partial: dict[str, Tensor] = {}
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
|
||||
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
|
||||
|
||||
for key, value in model.state_dict().items():
|
||||
if isinstance(value, DTensor):
|
||||
# only gather after the downcast to dtype as it will be faster
|
||||
value = cast(DTensor, value.to(dtype)).full_tensor()
|
||||
if owners[key] != world.rank:
|
||||
continue
|
||||
partial[resolve_fqn(model, key)] = value.to("cpu")
|
||||
dist.barrier()
|
||||
|
||||
if any(".base_layer." in key or "lora_A" in key or "lora_B" in key for key in partial.keys()):
|
||||
raise ValueError("gather_weights_parallel does not support LoRA state dicts")
|
||||
|
||||
return partial
|
||||
|
||||
|
||||
def save_state_dict_parallel(state_dict: dict[str, Tensor], save_dir: Path) -> None:
|
||||
"""Cooperatively save a rank-partitioned state dict as sharded safetensors.
|
||||
|
||||
Each rank splits its slice into <=5GB shards and writes them under temporary
|
||||
names, shard maps are exchanged, and every rank renames its own files into the
|
||||
global numbering (non-POSIX shared filesystems cannot reliably rename another
|
||||
rank's unpublished writes). Master writes the index last, after the barrier, so
|
||||
a complete index implies complete shards.
|
||||
"""
|
||||
logger = get_logger()
|
||||
world = get_world()
|
||||
|
||||
# Master-only mkdir + barrier: concurrent mkdir from every rank can re-raise
|
||||
# FileExistsError on a parallel FS (EEXIST + stale is_dir()).
|
||||
if world.is_master:
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
dist.barrier()
|
||||
|
||||
tmp_pattern = f"tmp-rank{world.rank}{{suffix}}.safetensors"
|
||||
split = split_torch_state_dict_into_shards(state_dict, filename_pattern=tmp_pattern)
|
||||
local_shards: list[tuple[str, dict[str, int]]] = []
|
||||
for tmp_name, tensor_names in split.filename_to_tensors.items():
|
||||
if not tensor_names:
|
||||
continue
|
||||
shard = {name: state_dict[name].contiguous() for name in tensor_names}
|
||||
save_file(shard, save_dir / tmp_name, metadata={"format": "pt"})
|
||||
local_shards.append((tmp_name, {name: shard[name].nbytes for name in tensor_names}))
|
||||
|
||||
all_shards: list[list[tuple[str, dict[str, int]]] | None] = [None] * world.world_size
|
||||
dist.all_gather_object(all_shards, local_shards)
|
||||
flat = [(rank, tmp_name, sizes) for rank, shards in enumerate(all_shards) for tmp_name, sizes in shards]
|
||||
|
||||
num_shards = len(flat)
|
||||
weight_map: dict[str, str] = {}
|
||||
for index, (rank, tmp_name, sizes) in enumerate(flat, start=1):
|
||||
if num_shards == 1:
|
||||
final_name = SAFE_WEIGHTS_NAME
|
||||
else:
|
||||
final_name = SAFE_WEIGHTS_NAME.replace(".safetensors", f"-{index:05d}-of-{num_shards:05d}.safetensors")
|
||||
for name in sizes:
|
||||
weight_map[name] = final_name
|
||||
if rank == world.rank:
|
||||
(save_dir / tmp_name).rename(save_dir / final_name)
|
||||
logger.debug(f"Saved {num_shards} weight shards across {world.world_size} ranks")
|
||||
|
||||
dist.barrier()
|
||||
if world.is_master and num_shards > 1:
|
||||
total_size = sum(size for _, _, sizes in flat for size in sizes.values())
|
||||
index_json = {"metadata": {"total_size": total_size}, "weight_map": weight_map}
|
||||
with open(save_dir / SAFE_WEIGHTS_INDEX_NAME, "w", encoding="utf-8") as f:
|
||||
f.write(json.dumps(index_json, indent=2, sort_keys=True) + "\n")
|
||||
@@ -1,8 +1,9 @@
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch.distributed.checkpoint.format_utils import dcp_to_torch_save
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_loss_goes_down, strip_escape_codes
|
||||
@@ -150,19 +151,22 @@ def test_loss_goes_down_resume(sft_resume_process: ProcessResult, run_dir: Path)
|
||||
def test_full_offload_model_only_resume_preserves_weights(
|
||||
sft_full_offload_model_only_resume_process: ProcessResult,
|
||||
run_dir: Path,
|
||||
tmp_path: Path,
|
||||
):
|
||||
assert sft_full_offload_model_only_resume_process.returncode == 0, (
|
||||
f"Process has non-zero return code ({sft_full_offload_model_only_resume_process})"
|
||||
)
|
||||
before_dir = run_dir / "weights" / "step_5"
|
||||
after_dir = run_dir / "weights" / "step_6"
|
||||
before_files = sorted(before_dir.glob("*.safetensors"))
|
||||
after_files = sorted(after_dir.glob("*.safetensors"))
|
||||
assert before_files
|
||||
assert [path.name for path in before_files] == [path.name for path in after_files]
|
||||
for before, after in zip(before_files, after_files):
|
||||
with before.open("rb") as before_handle, after.open("rb") as after_handle:
|
||||
assert (
|
||||
hashlib.file_digest(before_handle, "sha256").digest()
|
||||
== hashlib.file_digest(after_handle, "sha256").digest()
|
||||
)
|
||||
|
||||
def model_state(step: int) -> dict[str, torch.Tensor]:
|
||||
torch_save_path = tmp_path / f"step_{step}.pt"
|
||||
dcp_to_torch_save(run_dir / "checkpoints" / f"step_{step}" / "trainer", torch_save_path)
|
||||
return torch.load(torch_save_path, map_location="cpu", weights_only=False)["app"]["model"]
|
||||
|
||||
before, after = model_state(5), model_state(6)
|
||||
assert before.keys() == after.keys()
|
||||
# The runs train in different compute dtypes (fp32 vs bf16 under full offload),
|
||||
# so compare in the dtype the resumed model actually loaded.
|
||||
for key in before:
|
||||
assert torch.equal(before[key].to(torch.bfloat16), after[key].to(torch.bfloat16)), (
|
||||
f"Weight mismatch after model-only resume: {key}"
|
||||
)
|
||||
|
||||
@@ -3,7 +3,6 @@ from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from prime_rl.trainer.weights import load_state_dict
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_loss_goes_down, strip_escape_codes
|
||||
|
||||
@@ -20,15 +19,6 @@ def run_dir(output_dir: Path) -> Path:
|
||||
TIMEOUT = 300 # 5 minutes
|
||||
|
||||
|
||||
def assert_adapter_checkpoint(adapter_dir: Path) -> None:
|
||||
assert (adapter_dir / "adapter_config.json").exists()
|
||||
state_dict = load_state_dict(adapter_dir)
|
||||
assert state_dict
|
||||
assert all(".0.weight" not in key for key in state_dict)
|
||||
assert any(key.endswith("lora_A.weight") for key in state_dict)
|
||||
assert all(key.startswith("base_model.model.") for key in state_dict)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for SFT LoRA CI integration tests."""
|
||||
@@ -110,12 +100,6 @@ def test_loss_goes_down(sft_lora_process: ProcessResult, run_dir: Path):
|
||||
check_loss_goes_down(trainer_stdout)
|
||||
|
||||
|
||||
def test_adapter_checkpoint_written(sft_lora_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the adapter checkpoint is written with valid PEFT-compatible keys."""
|
||||
adapter_dir = run_dir / "weights" / "step_5" / "lora_adapters"
|
||||
assert_adapter_checkpoint(adapter_dir)
|
||||
|
||||
|
||||
def test_no_error_resume(sft_lora_resume_process: ProcessResult):
|
||||
"""Tests that the SFT LoRA resume process does not fail."""
|
||||
assert sft_lora_resume_process.returncode == 0, f"Process has non-zero return code ({sft_lora_resume_process})"
|
||||
@@ -128,9 +112,3 @@ def test_loss_goes_down_resume(sft_lora_resume_process: ProcessResult, run_dir:
|
||||
with open(trainer_log_path, "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_loss_goes_down(trainer_stdout)
|
||||
|
||||
|
||||
def test_adapter_checkpoint_written_resume(sft_lora_resume_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the adapter checkpoint is written after resuming with valid PEFT-compatible keys."""
|
||||
adapter_dir = run_dir / "weights" / "step_10" / "lora_adapters"
|
||||
assert_adapter_checkpoint(adapter_dir)
|
||||
|
||||
@@ -270,22 +270,34 @@ def test_train_only_metrics_absent_from_eval():
|
||||
assert out["train/agg/all/agent/is_trainable/mean"] == 0.5
|
||||
assert out["train/agg/all/agent/is_admitted/mean"] == 0.5
|
||||
assert "train/agg/all/is_trainable/mean" not in out # pipeline verdicts are per-trace
|
||||
eval_out = EvalEpisodes(rollouts).metrics.to_wandb(prefix="eval/x", subset="all")
|
||||
eval_out = EvalEpisodes(rollouts, group_size=2).metrics.to_wandb(prefix="eval/x", subset="all")
|
||||
assert not any("is_trainable" in key or "is_admitted" in key for key in eval_out)
|
||||
|
||||
|
||||
def test_eval_avg_at_k_and_pass_k():
|
||||
binary = EvalEpisodes([mk(reward=1.0, group_id="g0"), mk(reward=0.0, group_id="g0")])
|
||||
binary = EvalEpisodes([mk(reward=1.0, group_id="g0"), mk(reward=0.0, group_id="g0")], group_size=2)
|
||||
eff = binary.effective.metrics.to_wandb(prefix="eval/x", subset="effective")
|
||||
assert eff["eval/x/effective/agent/avg@2"] == 0.5 # mean reward under avg@<k> (k from the groups)
|
||||
assert eff["eval/x/effective/agent/avg@2"] == 0.5 # k is the configured episode group size
|
||||
assert "eval/x/effective/avg@2" not in eff # scores are per-agent, never pooled
|
||||
assert eff["eval/x/effective/agent/pass@1"] == 0.5 and eff["eval/x/effective/agent/pass^2"] == 0.0
|
||||
all_out = binary.metrics.to_wandb(prefix="eval/x", subset="all")
|
||||
assert all_out["eval/x/all/agent/avg@2"] == 0.5
|
||||
assert not any("pass@" in k or "pass^" in k for k in all_out) # pass@k effective-only
|
||||
non_binary = EvalEpisodes([mk(reward=0.5, group_id="g0"), mk(reward=1.0, group_id="g0")])
|
||||
non_binary = EvalEpisodes([mk(reward=0.5, group_id="g0"), mk(reward=1.0, group_id="g0")], group_size=2)
|
||||
assert not any("pass@" in k for k in non_binary.effective.metrics.to_wandb(prefix="eval/x", subset="effective"))
|
||||
|
||||
multi_agent = EvalEpisodes(
|
||||
[
|
||||
combine(mk(agent_name="proposer"), mk(agent_name="solver"), mk(agent_name="solver")),
|
||||
combine(mk(agent_name="proposer"), mk(agent_name="solver"), mk(agent_name="solver")),
|
||||
],
|
||||
group_size=2,
|
||||
)
|
||||
multi_agent_out = multi_agent.metrics.to_wandb(prefix="eval/x", subset="all")
|
||||
assert "eval/x/all/proposer/avg@2" in multi_agent_out
|
||||
assert "eval/x/all/solver/avg@2" in multi_agent_out
|
||||
assert not any("avg@4" in key for key in multi_agent_out)
|
||||
|
||||
|
||||
def test_compute_pass_metrics_matches_closed_form():
|
||||
out = compute_pass_metrics([1.0, 1.0, 0.0, 0.0]) # n=4, c=2
|
||||
|
||||
@@ -89,6 +89,13 @@ EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
|
||||
("Qwen/Qwen3.5-35B-A3B", "qwen3_coder", "qwen3"),
|
||||
("Qwen/Qwen3.5-122B-A10B", "qwen3_coder", "qwen3"),
|
||||
("Qwen/Qwen3.5-397B-A17B", "qwen3_coder", "qwen3"),
|
||||
# Qwen3.6
|
||||
("Qwen/Qwen3.6-35B-A3B", "qwen3_coder", "qwen3"),
|
||||
# Qwen3.8
|
||||
("Qwen/Qwen3.8-27B", "qwen3_coder", "qwen3"),
|
||||
("Qwen/Qwen3.8-27B-FP8", "qwen3_coder", "qwen3"),
|
||||
("Qwen/Qwen3.8-2.4T-A95B", "qwen3_coder", "qwen3"),
|
||||
("Qwen/Qwen3.8-2.4T-A95B-FP8", "qwen3_coder", "qwen3"),
|
||||
# Unknown model
|
||||
("some/unknown-model", None, None),
|
||||
]
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.trainer.model import load_dcp_from_hf
|
||||
from prime_rl.trainer.models.laguna.configuration_laguna import LagunaConfig
|
||||
from prime_rl.trainer.models.laguna.modeling_laguna import LagunaForCausalLM
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def model() -> LagunaForCausalLM:
|
||||
config = LagunaConfig(
|
||||
vocab_size=64,
|
||||
hidden_size=32,
|
||||
intermediate_size=64,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=8,
|
||||
moe_intermediate_size=16,
|
||||
shared_expert_intermediate_size=16,
|
||||
num_experts_per_tok=2,
|
||||
num_experts=4,
|
||||
sliding_window=None,
|
||||
layer_types=["full_attention", "full_attention"],
|
||||
)
|
||||
with torch.device("meta"):
|
||||
return LagunaForCausalLM(config)
|
||||
|
||||
|
||||
def test_load_dcp_from_hf_keeps_checkpoint_expert_bias(model, tmp_path, monkeypatch):
|
||||
"""Checkpoint values for the persistent `expert_bias` buffer must survive loading."""
|
||||
expected = torch.tensor([0.1, 0.2, 0.3, 0.4])
|
||||
|
||||
def fake_dcp_load(state_dict, storage_reader=None):
|
||||
buffer = state_dict["model.layers.1.mlp.expert_bias"]
|
||||
buffer.copy_(expected.to(device=buffer.device, dtype=buffer.dtype))
|
||||
|
||||
monkeypatch.setattr("prime_rl.trainer.model.dcp_load", fake_dcp_load)
|
||||
monkeypatch.setattr("prime_rl.trainer.model.load_state_dict_keys", lambda path: model.state_dict().keys())
|
||||
monkeypatch.setattr("torch.distributed.barrier", lambda *args, **kwargs: None)
|
||||
|
||||
load_dcp_from_hf(model, ModelConfig(name=str(tmp_path)), parallel_dims=MagicMock())
|
||||
|
||||
expert_bias = model.model.layers[1].mlp.expert_bias
|
||||
torch.testing.assert_close(expert_bias.cpu(), expected.to(expert_bias.dtype))
|
||||
Reference in New Issue
Block a user