Compare commits

...
Author SHA1 Message Date
289562d2ec feat: remove multi-tenant (#3189)
* feat(client): single-string base_url, remove elastic inference pool

The data plane is now a single endpoint (put a router in front for
multi-replica deployments); admin_base_url stays a list for per-server
admin operations (weight updates, health checks, NCCL rank offsets).
Removes ElasticInferencePool (DNS discovery + per-tenant adapter sync),
the InferencePool protocol/factory, and client-side load balancing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: orchestrator-side packing, single-tenant trainer, flat output dir

Removes the multi-tenant infrastructure:

- Bin-packing moves into the orchestrator (BatchPacker), which now ships
  per-DP-rank micro batches directly to the trainer — one transport hop
  instead of two (the rank-0 packer and its second filesystem write are
  gone). ZMQ data moves to port, READY barrier to port+1; the transport
  binds in the orchestrator process.
- MultiRunManager, run discovery, eviction, the control/orch.toml
  handshake, MultiPacker, MultiCheckpointManager, MultiLoRAOptimizer,
  MultiLoRAScheduler, per-run metrics, and trainer.max_concurrent_runs
  are deleted. A slim LoRAState in trainer/lora.py keeps single-tenant
  LoRA (RL + SFT) working: module registry, adapter state dicts, resets,
  and the shared lora_num_tokens/scaling tensors (n_adapters=1).
- The run_default nesting is gone: orchestrator.output_dir equals
  trainer.output_dir, with rollouts, broadcasts, checkpoints, and token
  exports in one flat experiment dir.
- RL LoRA optimizers now include modules_to_save params (matching SFT).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: always broadcast step-0 weights at startup

The trainer's startup broadcast of the incoming policy (v0 from scratch,
v{resume_step} on resume) now runs for every transport, not just the
in-memory ones, and the orchestrator's startup weight sync is
unconditional to match. This validates the broadcast path at startup
instead of after the first optimizer step and aligns fresh starts with
the restart flow. The orchestrator always waits for the startup weight
directory (default 1200s; ckpt.wait_for_weights_timeout overrides).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: assign base_url as str in auto_setup_inference_client

Leftover list assignment from before the base_url list[str] -> str
migration; pydantic doesn't validate assignment, so the list survived
until rl_local's urlparse crashed on it (sft-distill path only).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 19:49:42 -07:00
74 changed files with 752 additions and 4951 deletions
-3
View File
@@ -84,9 +84,6 @@ jobs:
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: reverse_text_multi_run
runner: 4xa6000
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
+1 -1
View File
@@ -218,7 +218,7 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA, multi-tenant training
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
- [**Development**](docs/development.md) - Test suite, pre-commit hooks, adding a new model
## Contributing
@@ -1,10 +0,0 @@
# Env server for the multi-run RL integration test: one per orchestrator, each bound at
# its run's base port (the test passes --serve.address).
[env.taskset]
id = "reverse-text-v1"
[env.agent.harness]
id = "null"
[env.agent.runtime]
type = "subprocess"
@@ -1,11 +0,0 @@
# Inference config for multi-run RL integration test
[vllm]
model = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
max_model_len = 2048
enable_lora = true
max_lora_rank = 8
max_loras = 4
gpu_memory_utilization = 0.7
[weight_broadcast]
type = "filesystem"
@@ -1,39 +0,0 @@
# Orchestrator config for multi-run RL integration test
# model.lora.name and output_dir are set via CLI
batch_size = 128
group_size = 16
seq_len = 2048
max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[optim]
lr = 3e-5
[train.sampling]
max_completion_tokens = 128
[[train.source]]
name = "reverse-text"
[train.source.env.taskset]
id = "reverse-text-v1"
[train.source.env.agent.harness]
id = "null"
[train.source.env.agent.runtime]
type = "subprocess"
[ckpt]
interval = 10
resume_step = -1
[weight_broadcast]
type = "filesystem"
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[renderer]
name = "prime-qwen3"
@@ -1,21 +0,0 @@
# Trainer config for multi-run RL integration test
max_concurrent_runs = 2
enable_token_export = true
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 65536
fused_lm_head_token_chunk_size = 8192
optim_cpu_offload = false
[model.lora]
rank = 8
[model.ac]
freq = 1
[model.compile]
fullgraph = false
[weight_broadcast]
type = "filesystem"
@@ -29,7 +29,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
[orchestrator.renderer]
name = "prime-qwen3"
@@ -30,7 +30,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
+1 -1
View File
@@ -60,7 +60,7 @@ type = "opd"
[orchestrator.train.source.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
[orchestrator.eval]
interval = 5
+1 -1
View File
@@ -24,7 +24,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
+1 -1
View File
@@ -24,7 +24,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
+1 -1
View File
@@ -25,7 +25,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
+1 -1
View File
@@ -25,7 +25,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
+1 -8
View File
@@ -1,6 +1,6 @@
# Advanced
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, multi-tenant training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
## Table of Contents
@@ -11,7 +11,6 @@ This page covers the specialized features layered on top of the core training st
- [Enabling VLM Mode](#enabling-vlm-mode)
- [Limitations](#limitations)
- [LoRA Training](#lora-training)
- [Multi-Tenant Training](#multi-tenant-training)
- [Disaggregated Prefill/Decode Inference](#disaggregated-prefilldecode-inference)
## Custom Modeling
@@ -123,12 +122,6 @@ LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** su
save_adapter_separately = true
```
LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — each tenant gets its own adapter and the backbone is shared across all of them in trainer memory.
## Multi-Tenant Training
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
## Disaggregated Prefill/Decode Inference
For large MoE serving, splitting prefill and decode onto separate vLLM groups can substantially improve throughput. Pick the prefill:decode ratio based on workload shape:
+2 -2
View File
@@ -35,7 +35,7 @@ A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, wh
1. **Sampling** (`algo.sampling`) — how train rollouts are produced: which model generates them. `source` is a [model reference](#model-references): `"policy"` (the live policy, the default) or an inline frozen hosted model. Group sizing stays on the env config (`group_size`).
2. **The per-token training signal** — credit assignment and loss routing, fused; the algorithm's own parameters sit directly on `algo`. One mapping from a finalized rollout to per-token *(loss component, weight)* pairs — the credit a token gets and the loss that consumes it are two coordinates of the same output. Group-relative algorithms compute credit on the orchestrator and ship per-token advantage streams; reference-KL algorithms query a reference model at batch-ship time (bounded concurrency) and ship its prefill logprobs for the trainer to evaluate against the live policy. The `type` determines which loss component consumes the action tokens (`rl` / `ce` / `ref_kl`) and what happens to env-provided observation tokens in multi-turn rollouts (masked out by default; `echo` trains on them with weighted CE).
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, packer, or trainer hot path.
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, batch packing, or trainer hot path.
### Model References
@@ -47,7 +47,7 @@ type = "opd"
[orchestrator.algo.teacher] # opd's teacher: the frozen model it scores against
name = "Qwen/Qwen3-32B"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
```
Model *roles* are algorithm-local vocabulary — each algorithm names its reference on the field where the model is actually used, and there is no shared `teacher` slot. `opd` declares a `teacher` field (the frozen model whose reverse KL the policy distills toward); `sft`'s teacher *is* its `sampling.source` (the frozen model it imitates); `opsd` self-distills against the live policy and names no model at all. No role exists outside the algorithm that declares it: the dispatcher, sink, and trainer branch on liveness alone, never on what an algorithm calls a model.
+1 -1
View File
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_multi_run`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
+2 -2
View File
@@ -10,7 +10,7 @@ A `prime-rl` RL run is three cooperating processes:
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/inference/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, and LoRA. You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses ZMQ, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
@@ -41,5 +41,5 @@ The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into
- **[Inference](inference.md)** — vLLM-backed server (or fleet) holding the current policy.
- **[Scaling](scaling.md)** — Single-GPU through multi-node clusters via FSDP / EP / CP and SLURM.
- **[Algorithms](algorithms.md)** — Async semantics, loss / advantage / filter plugins, trajectory merging.
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, multi-tenant, P/D inference.
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, P/D inference.
- **[Development](development.md)** — Test suite, pre-commit hooks, adding a new model.
+1 -1
View File
@@ -144,7 +144,7 @@ Offloading optimizer states to CPU is enabled by default (`optim_cpu_offload = t
optim_cpu_offload = true # already the default
```
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training) — set `optim_cpu_offload = false` for multi-run. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
Mutually exclusive with `fsdp_cpu_offload`. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
### LM Head Chunking
+1 -1
View File
@@ -11,7 +11,7 @@ image:
orchestrator:
enabled: true
autoStart: true
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs/run_default --client.base-url $INFERENCE_URL ; sleep infinity"
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL ; sleep infinity"
resources:
requests:
memory: "1Gi"
+6 -8
View File
@@ -59,9 +59,6 @@ spec:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.orchestrator.replicas }}"
- name: HEADLESS_SERVICE
value: "{{ .Release.Name }}-orchestrator-headless.{{ .Values.namespace }}.svc.cluster.local"
- name: INFERENCE_URL
{{- $releaseName := .Release.Name }}
{{- $namespace := .Values.namespace }}
{{- $port := int .Values.inference.service.port }}
@@ -71,6 +68,9 @@ spec:
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
{{- $urls = append $urls $url }}
{{- end }}
- name: INFERENCE_URL
value: {{ first $urls | quote }}
- name: ADMIN_INFERENCE_URLS
value: {{ $urls | join "," | quote }}
{{- with .Values.orchestrator.env }}
{{- toYaml . | nindent 8 }}
@@ -163,8 +163,6 @@ spec:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.inference.replicas }}"
- name: HEADLESS_SERVICE
value: "{{ .Release.Name }}-inference-headless.{{ .Values.namespace }}.svc.cluster.local"
{{- with .Values.inference.env }}
{{- toYaml . | nindent 8 }}
{{- end }}
@@ -294,13 +292,10 @@ spec:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.trainer.replicas }}"
- name: HEADLESS_SERVICE
value: "{{ .Release.Name }}-trainer-headless.{{ .Values.namespace }}.svc.cluster.local"
{{- if .Values.trainer.pytorchCudaAllocConf }}
- name: PYTORCH_CUDA_ALLOC_CONF
value: {{ .Values.trainer.pytorchCudaAllocConf | quote }}
{{- end }}
- name: INFERENCE_URL
{{- $releaseName := .Release.Name }}
{{- $namespace := .Values.namespace }}
{{- $port := int .Values.inference.service.port }}
@@ -310,6 +305,9 @@ spec:
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
{{- $urls = append $urls $url }}
{{- end }}
- name: INFERENCE_URL
value: {{ first $urls | quote }}
- name: ADMIN_INFERENCE_URLS
value: {{ $urls | join "," | quote }}
{{- with .Values.trainer.env }}
{{- toYaml . | nindent 8 }}
+6 -3
View File
@@ -28,9 +28,12 @@ orchestrator:
# Auto-start configuration (set to false to use sleep infinity for debugging)
autoStart: false
# Example command - use $INFERENCE_URL directly (comma-separated list of all inference server URLs)
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs/run_default --client.base-url $INFERENCE_URL'
# $INFERENCE_URL is auto-set to: 'http://<release>-inference-0...:8000/v1,http://<release>-inference-1...:8000/v1,...'
# Example command - use $INFERENCE_URL directly (the first inference server URL)
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL'
# $INFERENCE_URL is auto-set to 'http://<release>-inference-0...:8000/v1'. With more than one
# inference replica, put a router in front and point --client.base-url at it; admin operations
# (weight updates, health checks) fan out to every replica via
# --client.admin-base-url $ADMIN_INFERENCE_URLS (comma-separated list of all replica URLs).
resources:
requests:
@@ -58,7 +58,7 @@ class FrozenModelConfig(ClientConfig):
@model_validator(mode="after")
def require_explicit_endpoint(self):
if "base_url" not in self.model_fields_set and not self.is_elastic:
if "base_url" not in self.model_fields_set:
raise ValueError(
"a frozen model reference needs base_url — frozen models are externally "
"hosted; prime-rl only ever hosts the trainable policy."
@@ -25,11 +25,6 @@ from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig
class OptimizerConfig(BaseConfig):
lr: float = Field(1e-4, ge=0)
"""Learning rate for this run (per-run override for multi-run training)."""
class LoRAConfig(BaseConfig):
name: str | None = None
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
@@ -338,7 +333,7 @@ class CheckpointConfig(BaseConfig):
"""Step to resume the orchestrator from. None starts from scratch; ``-1`` resumes from the latest checkpoint available."""
wait_for_weights_timeout: int | None = Field(None, ge=1)
"""When resuming, wait up to this many seconds for the weight directory to appear. Useful when the orchestrator restarts while the trainer is still saving weights. If None, fail immediately when weights are not found."""
"""Wait up to this many seconds for the startup weight directory to appear (the trainer broadcasts the incoming policy — v0 from scratch, v{resume_step} on resume — before the first step). If None, fall back to a default timeout. Raise this for large models on slow shared filesystems."""
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."""
@@ -461,9 +456,6 @@ class OrchestratorConfig(BaseConfig):
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. RL/OPD roll out through the renderer
client; SFT uses it to backfill tokens for its chat-completions teacher."""
optim: OptimizerConfig = OptimizerConfig()
"""Per-run optimizer configuration for multi-run training."""
eval: EvalConfig | None = None
"""Evaluation configuration."""
@@ -512,8 +504,8 @@ class OrchestratorConfig(BaseConfig):
rollout_transport: TransportConfig = ZMQTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
output_dir: Path = Path("outputs/run_default")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Rate limit per environment worker, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. With multiple workers, the effective total rate is ``workers × this value``. None disables rate limiting."""
@@ -539,9 +531,11 @@ class OrchestratorConfig(BaseConfig):
seq_len: int = 2048
"""Training sequence length. Shorter samples are padded; longer samples are truncated."""
# TODO(Mika): This should be automatic from the number of ZMQ connections
num_train_workers: int = Field(1, ge=1)
"""Training workers to use."""
"""Trainer data-parallel world size (trainer world size // cp). The orchestrator packs one micro-batch list per DP rank, so this must match the trainer topology. Auto-filled by the ``rl`` entrypoint; set explicitly for standalone orchestrator runs."""
pad_to_multiple_of: int = Field(1, ge=1)
"""Pad each packed micro batch to a multiple of this value (the trainer's cp degree). Auto-filled by the ``rl`` entrypoint; set explicitly for standalone orchestrator runs with cp > 1."""
max_steps: int | None = None
"""Maximum training steps. If None, runs indefinitely."""
@@ -222,7 +222,7 @@ class RLConfig(BaseConfig):
orchestrator: OrchestratorConfig
inference: InferenceConfig | None = None
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."""
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for manually started servers)."""
env_vars: EnvVars = {}
"""Extra environment variables for every launched RL component. Component-specific env_vars override these."""
@@ -603,6 +603,7 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_deployment(self):
self.orchestrator.pad_to_multiple_of = self.trainer.model.cp
if self.deployment.type == "single_node": # single-node
# set num_train_workers to the number of data replicas
non_data_parallel_size = self.trainer.model.cp
@@ -625,7 +626,9 @@ class RLConfig(BaseConfig):
self.inference.vllm.api_server_count = dp
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node
self.orchestrator.num_train_workers = (
self.deployment.num_train_nodes * self.deployment.gpus_per_node // self.trainer.model.cp
)
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
@@ -756,7 +759,7 @@ class RLConfig(BaseConfig):
if not self.orchestrator.any_policy_sourced and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
client.base_url = [f"http://{host}:{port}/v1"]
client.base_url = f"http://{host}:{port}/v1"
if (
self.deployment.type == "single_node"
and self.inference.router is not None
@@ -108,23 +108,12 @@ class BaseModelConfig(BaseConfig):
"""VLM configuration. Setting this enables vision-language model support."""
class ElasticConfig(BaseConfig):
hostname: str
"""DNS hostname that resolves to inference server IPs."""
port: int = 8000
"""Port that inference servers listen on."""
sync_interval: float = 5.0
"""Seconds between server discovery checks."""
class ClientConfig(BaseConfig):
wait_for_ready_timeout: int = 1800
"""Seconds to wait at startup for the inference pool to become ready. Applies to both the static health check and elastic DNS-based discovery."""
"""Seconds to wait at startup for the inference pool to become ready."""
base_url: list[str] = ["http://localhost:8000/v1"]
"""Base URLs for the OpenAI API. With more than one URL, the client round-robins (chat) completion requests across all servers. Ignored when ``elastic`` is set."""
base_url: str = "http://localhost:8000/v1"
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
api_key_var: str = "VLLM_API_KEY"
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
@@ -142,18 +131,7 @@ class ClientConfig(BaseConfig):
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
admin_base_url: list[str] | None = None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in disaggregated P/D deployments where the router must not handle admin traffic."""
elastic: ElasticConfig | None = None
"""Elastic inference pool config for DNS-based service discovery. When set, ``base_url`` is ignored and inference servers are discovered dynamically via DNS."""
router_url: str | None = None
"""vllm-router URL for load-aware inference routing. With elastic mode, inference requests go through the router while admin ops still hit discovered pods directly."""
@property
def is_elastic(self) -> bool:
"""Check if elastic mode is enabled."""
return self.elastic is not None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
class LogConfig(BaseConfig):
@@ -625,9 +625,6 @@ class TrainerConfig(BaseConfig):
metrics_server: MetricsServerConfig | None = None
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
max_concurrent_runs: int = Field(1, ge=1)
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
enable_token_export: bool = False
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
@@ -702,12 +699,6 @@ class TrainerConfig(BaseConfig):
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def validate_optim_cpu_offload_single_run(self):
if self.model.optim_cpu_offload and self.max_concurrent_runs > 1:
raise ValueError("Optimizer CPU offload is not supported with max_concurrent_runs > 1")
return self
@model_validator(mode="after")
def validate_lora_broadcast(self):
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
@@ -138,21 +138,7 @@ def propagate_shared_fields(data: Any) -> Any:
# pass (the per-rank inference.toml drops slurm, so each rank still runs locally).
propagate("slurm", "inference.slurm")
# output_dir: orchestrator gets a ``/run_default`` subdir so trainer +
# orchestrator nest under the same experiment root without colliding.
# Conflicts are reported against the *transformed* sub-config value, not
# the raw shared path, so the materialized config round-trips cleanly.
output_dir = get("output_dir")
if output_dir is not None:
expected = {
"trainer.output_dir": output_dir,
"orchestrator.output_dir": f"{output_dir}/run_default",
}
for sub, expected_value in expected.items():
sub_value = get(sub)
if sub_value is not None and sub_value != expected_value:
conflicts.append(("output_dir", sub))
fill(sub, expected_value)
propagate("output_dir", "trainer.output_dir", "orchestrator.output_dir")
# Cascade trainer.tokenizer.chat_template → inference.vllm.chat_template
# (vLLM ``--chat-template``). Read trainer's value *after* the shared
@@ -243,9 +229,10 @@ def validate_shared_output_dir(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.output_dir != orchestrator.output_dir.parent:
if trainer.output_dir != orchestrator.output_dir:
raise ValueError(
f"Trainer outputs directory ({trainer.output_dir}) and orchestrator outputs directory parent ({orchestrator.output_dir.parent}) are not the same. Please specify the same outputs directory for both."
f"Trainer outputs directory ({trainer.output_dir}) and orchestrator outputs directory ({orchestrator.output_dir}) are not the same. "
"Please specify the same outputs directory for both (the orchestrator no longer nests under a run_default subdirectory)."
)
+1 -1
View File
@@ -90,7 +90,7 @@ In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
enable_token_export = true
+1 -1
View File
@@ -162,7 +162,7 @@ jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
```
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{output_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the trace subtrees.
### Common failure modes
+4 -7
View File
@@ -170,9 +170,8 @@ def rl_local(config: RLConfig):
}
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.model.client.is_elastic:
base_url = config.orchestrator.model.client.base_url[0]
parsed = urlparse(base_url)
if config.inference is not None:
parsed = urlparse(config.orchestrator.model.client.base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
@@ -238,7 +237,7 @@ def rl_local(config: RLConfig):
"No [inference] block configured - the policy inference server will not be started here. "
"Every algorithm requires a policy inference pool for evals + weight sync; "
"make sure one is running at orchestrator.model.client.base_url "
f"({', '.join(config.orchestrator.model.client.base_url)}), otherwise the orchestrator "
f"({config.orchestrator.model.client.base_url}), otherwise the orchestrator "
"will hang waiting for it."
)
@@ -248,7 +247,7 @@ def rl_local(config: RLConfig):
assert algo is not None, "TrainSourceConfig.algo must be resolved before launch (inherit_env_algorithms)"
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
if isinstance(ref, FrozenModelConfig):
frozen_endpoints.append(f"{ref.name} ({', '.join(ref.base_url)})")
frozen_endpoints.append(f"{ref.name} ({ref.base_url})")
if frozen_endpoints:
endpoints = ", ".join(dict.fromkeys(frozen_endpoints))
logger.info(
@@ -483,7 +482,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
is_disaggregated=True,
config_dir=config_dir,
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
nodes_per_infer_replica=infer_deploy.num_nodes,
@@ -524,7 +522,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
is_disaggregated=False,
config_dir=config_dir, # TODO: should prob have each subconfig path separately
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes,
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
+4 -4
View File
@@ -65,15 +65,15 @@ async def connect_frozen_pool(
(sft), so the rollout carries tokens. Left as plain chat-completions
otherwise (opd/opsd read teacher logprobs via prefill, where the train
client type is moot)."""
from prime_rl.utils.client import setup_inference_pool
from prime_rl.utils.client import InferencePool
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={', '.join(config.base_url)})")
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
pool = await setup_inference_pool(
pool = InferencePool(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
pool = await setup_inference_pool(config, model_name=config.name)
pool = InferencePool(config, model_name=config.name)
await pool.wait_for_ready(config.name)
return pool
+2 -6
View File
@@ -5,7 +5,6 @@ from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import OPDAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.utils.client import StaticInferencePool
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
@@ -29,13 +28,10 @@ class OPDAlgorithm(Algorithm):
def __init__(self, config: OPDAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
self.teacher = config.teacher
self.teacher_pool: StaticInferencePool | None = None # static teacher endpoint, connected in setup()
self.teacher_pool: InferencePool | None = None # frozen teacher endpoint, connected in setup()
async def setup(self) -> None:
pool = await self.connect(self.teacher)
if not isinstance(pool, StaticInferencePool):
raise TypeError("opd teacher must be a static endpoint — prefill scoring needs fixed endpoints")
self.teacher_pool = pool
self.teacher_pool = await self.connect(self.teacher)
async def score_rollout(self, rollout: Rollout) -> None:
pool = self.teacher_pool
+4 -15
View File
@@ -28,7 +28,7 @@ from __future__ import annotations
import asyncio
import uuid
from collections import Counter, defaultdict
from collections import defaultdict
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Literal
@@ -47,7 +47,7 @@ from prime_rl.orchestrator.types import (
RolloutKind,
)
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
from prime_rl.utils.client import InferencePool, client_identity
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import get_logger
@@ -413,20 +413,9 @@ class RolloutDispatcher:
else:
pool, model_name, live_sourced = self._train_pool_for(group.env_name)
# Pin a single client per group to keep prefix-cache hits
if group.pinned_client is None:
if group.kind == "eval":
client = await pool.get_eval_client()
else:
load = Counter(
client_identity(m.client_config) for m in self.inflight.values() if m.client_config is not None
)
client = await pool.select_train_client(load)
if group_id not in self.groups:
return False
group.pinned_client = client
else:
client = group.pinned_client
group.pinned_client = pool.eval_client if group.kind == "eval" else pool.train_client
client = group.pinned_client
env_collection = self.train_envs if group.kind == "train" else self.eval_envs
if env_collection is None:
+32 -14
View File
@@ -37,7 +37,7 @@ if TYPE_CHECKING:
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.orchestrator.ckpt import CheckpointManager
from prime_rl.transport.base import TrainingBatchSender
from prime_rl.transport.base import MicroBatchSender
from prime_rl.utils.client import InferencePool
from prime_rl.utils.monitor.base import Monitor
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
@@ -49,6 +49,7 @@ from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.filters import setup_filters
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.packing import BatchPacker
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
@@ -74,7 +75,7 @@ from prime_rl.orchestrator.utils import (
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
from prime_rl.transport import setup_micro_batch_sender
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
from prime_rl.utils.config import to_toml_dict
@@ -129,7 +130,8 @@ class Orchestrator:
tokenizer: PreTrainedTokenizer
policy_inference: InferencePool
monitor: Monitor
sender: TrainingBatchSender
sender: MicroBatchSender | None
packer: BatchPacker
train_envs: TrainEnvs
train_source: TrainSource
train_sink: TrainSink
@@ -218,8 +220,7 @@ class Orchestrator:
# references are external endpoints — each env's Algorithm builds its
# own pools in ``setup()`` below.
get_logger().info(
f"Initializing policy inference pool (base_url={', '.join(config.model.client.base_url)}, "
f"model={config.model.name})"
f"Initializing policy inference pool (base_url={config.model.client.base_url}, model={config.model.name})"
)
self.renderer, self.policy_inference = await setup_policy_inference_pool(
config=config, tokenizer=self.tokenizer
@@ -333,9 +334,6 @@ class Orchestrator:
self.model_express.publish()
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
get_logger().info(f"Initializing training batch sender ({config.rollout_transport})")
self.sender = setup_training_batch_sender(config.output_dir, config.rollout_transport)
self.lora_name = config.model.lora.name if config.model.lora else None
self.train_source = TrainSource(self.train_envs)
@@ -350,16 +348,31 @@ class Orchestrator:
else:
get_logger().info("Training from scratch")
# Sync inference to the incoming policy before the first step when resuming or when using
# an in-memory transport, which rendezvouses with the trainer's startup broadcast.
if self.resume_step is not None or config.weight_broadcast.type in ("nccl", "nixl"):
self.packer = BatchPacker(config)
if config.bench:
# Bench runs have no trainer: nothing consumes shipped batches, and the
# ZMQ sender's READY barrier would block forever.
self.sender = None
else:
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
self.sender = setup_micro_batch_sender(
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
)
# Sync inference to the incoming policy before the first step, rendezvousing
# with the trainer's startup broadcast (v{resume_step} on resume, v0 from
# scratch). Bench runs have no trainer, so there is no broadcast to wait for.
if not config.bench:
sync_version = self.resume_step if self.resume_step is not None else 0
if config.weight_broadcast.type == "nixl":
weights_path = None
else:
check_exists = config.weight_broadcast.type == "filesystem"
# Without a ckpt block, fall back to a default timeout instead of not waiting at all.
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
# The trainer's startup broadcast is always coming, so wait for it
# rather than failing immediately when the directory is not there yet.
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
STARTUP_WEIGHT_WAIT_TIMEOUT_S
)
weights_path = get_weight_dir(
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
)
@@ -645,7 +658,11 @@ class Orchestrator:
records = [r.to_record() for r in effective]
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
pack_start_time = time.perf_counter()
micro_batch_grid = await asyncio.to_thread(self.packer.pack, batch.samples)
pack_time = time.perf_counter() - pack_start_time
if self.sender is not None:
await self.sender.send(micro_batch_grid)
self.progress.step += 1
self.update_dispatch_gate()
# Checkpoint the step we just shipped (resume point: continue at step + 1).
@@ -679,6 +696,7 @@ class Orchestrator:
"progress/total_rollouts": self.progress.total_samples,
"progress/total_tasks": self.progress.total_problems,
"time/step": step_time,
"time/pack": pack_time,
"time/save_ckpt": save_ckpt_time,
"time/wait_for_policy": self.wait_for_policy_time,
"step": step,
+35
View File
@@ -0,0 +1,35 @@
from transformers import AutoConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
from prime_rl.transport.types import MicroBatch, TrainingSample
from prime_rl.utils.logger import get_logger
class BatchPacker:
"""Bin-packs a step's training samples into one micro-batch list per trainer DP rank."""
def __init__(self, config: OrchestratorConfig):
self.seq_len = config.seq_len
self.num_train_workers = config.num_train_workers
self.pad_to_multiple_of = config.pad_to_multiple_of
try:
model_config = AutoConfig.from_pretrained(
config.model.name, trust_remote_code=config.tokenizer.trust_remote_code
)
except Exception as e:
get_logger().warning(
f"Could not load model config for {config.model.name} ({e}) - "
"packing balances by token count instead of estimated FLOPs"
)
model_config = None
self.bin_cost = build_bin_cost(model_config)
def pack(self, samples: list[TrainingSample]) -> list[list[MicroBatch]]:
return prepare_batch(
rollouts=samples,
seq_len=self.seq_len,
num_train_workers=self.num_train_workers,
bin_cost=self.bin_cost,
pad_to_multiple_of=self.pad_to_multiple_of,
)
+2 -2
View File
@@ -10,7 +10,7 @@ from pathlib import Path
import orjson
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.utils.client import setup_inference_pool
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import InterceptHandler, get_logger, setup_logger
from prime_rl.utils.utils import (
get_broadcast_dir,
@@ -39,7 +39,7 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
get_logger().info("Using direct renderer rollout client")
else:
get_logger().info("No policy-sourced train env — renderer kept for client-side tokenization only")
inference_pool = await setup_inference_pool(
inference_pool = InferencePool(
client_config,
model_name=model_name,
train_client_type="renderer",
+14 -8
View File
@@ -58,7 +58,6 @@ export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parall
export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
export ORCHESTRATOR_OUTPUT_DIR={{ orchestrator_output_dir }}
mkdir -p $OUTPUT_DIR/logs/trainer $OUTPUT_DIR/logs/inference
rm -f $OUTPUT_DIR/logs/inference/*.log
ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
@@ -125,6 +124,15 @@ export MASTER_PORT=29500
echo "MASTER_ADDR=${MASTER_ADDR}"
echo "MASTER_PORT=${MASTER_PORT}"
# The orchestrator runs on trainer rank 0's node (SLURM_PROCID == NUM_INFER_NODES) by
# default; with orchestrator_on_inference it moves to the last inference node (a decode
# node) to keep its rollout buffer + env workers off host-RAM-saturated trainer nodes.
# The ZMQ rollout transport binds in the orchestrator process, so both sides must
# address the orchestrator's node.
{% if num_infer_nodes > 0 and orchestrator_on_inference %}ORCH_PROCID=$((NUM_INFER_NODES - 1)){% else %}ORCH_PROCID=$NUM_INFER_NODES{% endif %}
export ORCH_ADDR="${HOSTNAMES[$ORCH_PROCID]}"
echo "ORCH_ADDR=${ORCH_ADDR}"
# Setup environment
cd $PROJECT_DIR
[ -f .env ] && source .env
@@ -398,15 +406,13 @@ else
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.toml \
{% if use_zmq_transport %}--rollout_transport.host $MASTER_ADDR \
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
{% if num_infer_nodes > 0 %} fi{% endif %}
{% if num_infer_nodes > 0 %}
# Launch the orchestrator on one node. Default is trainer rank 0 (SLURM_PROCID ==
# NUM_INFER_NODES). With orchestrator_on_inference it moves to the last inference node
# (a decode node) to keep its rollout buffer + env workers off host-RAM-saturated
# trainer nodes. Top-level (after the role if/else) so the wait -n teardown covers it.
{% if orchestrator_on_inference %}ORCH_PROCID=$((NUM_INFER_NODES - 1)){% else %}ORCH_PROCID=$NUM_INFER_NODES{% endif %}
# Launch the orchestrator on the node ORCH_ADDR points at (see the ORCH_PROCID
# computation above). Top-level (after the role if/else) so the wait -n teardown
# covers it.
if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --model.client.base-url $INFER_URLS"
@@ -438,7 +444,7 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
{%- endif %}
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $MASTER_ADDR"
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
fi
+275 -57
View File
@@ -1,10 +1,11 @@
import copy
import heapq
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import Any
import numpy as np
from prime_rl.trainer.utils import balanced_partition
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
# Backfill value per component weight stream when a packed sample doesn't
@@ -13,6 +14,241 @@ from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, T
STREAM_FILL = {"rl_weights": 1.0, "ce_weights": 0.0, "ref_kl_weights": 0.0}
def _text_config(model_config: Any) -> Any:
"""Unwrap a multimodal model's text config, else return the config unchanged."""
return getattr(model_config, "text_config", model_config)
def _is_mla(config: Any) -> bool:
return bool(getattr(config, "multi_latent_attention", False) or hasattr(config, "q_lora_rank"))
def _kv_channels(config: Any) -> int:
return getattr(config, "kv_channels", getattr(config, "head_dim", config.hidden_size // config.num_attention_heads))
def _qkv_projection_flops_per_token(config: Any) -> int:
"""Linear-in-seqlen FLOPs of the Q/K/V projections (per token)."""
hidden_size = config.hidden_size
num_attention_heads = config.num_attention_heads
kv_channels = _kv_channels(config)
is_mla = _is_mla(config)
qk_head_dim = getattr(config, "qk_head_dim", 0)
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
if is_mla and getattr(config, "q_lora_rank", None) is not None:
q_flops = 2 * config.q_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim))
else:
q_head_dim = (qk_head_dim + qk_pos_emb_head_dim) if is_mla else kv_channels
q_flops = 2 * hidden_size * num_attention_heads * q_head_dim
if is_mla and getattr(config, "kv_lora_rank", None) is not None:
v_head_dim = getattr(config, "v_head_dim", 0)
kv_flops = 2 * (
config.kv_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + v_head_dim))
+ hidden_size * qk_pos_emb_head_dim
)
else:
num_query_groups = getattr(
config, "num_query_groups", getattr(config, "num_key_value_heads", num_attention_heads)
)
kv_flops = 4 * hidden_size * num_query_groups * kv_channels
return q_flops + kv_flops
def _attention_flops_per_token_squared(config: Any) -> int:
"""Quadratic-in-seqlen FLOPs of the attention scores and values (per token^2)."""
num_attention_heads = config.num_attention_heads
kv_channels = _kv_channels(config)
if _is_mla(config):
qk_head_dim = getattr(config, "qk_head_dim", 0)
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
v_head_dim = getattr(config, "v_head_dim", kv_channels)
return num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim) + num_attention_heads * v_head_dim
return 2 * num_attention_heads * kv_channels
def _ffn_flops_per_token(hidden_size: int, ffn_hidden_size: int) -> int:
return 6 * hidden_size * ffn_hidden_size
def _dense_ffn_hidden_size(config: Any) -> int:
return getattr(
config, "ffn_hidden_size", getattr(config, "intermediate_size", getattr(config, "moe_intermediate_size", 0))
)
def _moe_ffn_hidden_size(config: Any) -> int:
"""Effective FFN width of an MoE layer: routed experts (topk) plus shared experts."""
dense_ffn = _dense_ffn_hidden_size(config)
routed_topk = getattr(config, "moe_router_topk", getattr(config, "num_experts_per_tok", 1))
moe_ffn = getattr(config, "moe_ffn_hidden_size", getattr(config, "moe_intermediate_size", dense_ffn))
return moe_ffn * routed_topk + (getattr(config, "moe_shared_expert_intermediate_size", None) or 0)
def _count_dense_and_moe_layers(config: Any) -> tuple[int, int]:
"""Split the model's layers into (dense, moe) counts."""
num_experts = getattr(config, "num_experts", getattr(config, "n_routed_experts", None))
if num_experts is None:
return config.num_hidden_layers, 0
moe_layer_freq = getattr(config, "moe_layer_freq", None)
if isinstance(moe_layer_freq, list):
num_dense = sum(1 for freq in moe_layer_freq if freq == 0)
num_moe = sum(1 for freq in moe_layer_freq if freq > 0)
elif isinstance(moe_layer_freq, int):
num_dense = sum(1 for i in range(config.num_hidden_layers) if i % moe_layer_freq != 0)
num_moe = config.num_hidden_layers - num_dense
elif getattr(config, "first_k_dense_replace", None) is not None:
num_dense = config.first_k_dense_replace
num_moe = config.num_hidden_layers - num_dense
else:
num_dense = 0
num_moe = config.num_hidden_layers
return num_dense, num_moe
def _packing_cost_coeffs(config: Any) -> tuple[int, int]:
"""Return the (linear, quadratic) coefficients of the per-sequence forward FLOPs."""
hidden_size = config.hidden_size
num_dense_layers, num_moe_layers = _count_dense_and_moe_layers(config)
qkv_per_token = _qkv_projection_flops_per_token(config)
attn_per_token_squared = _attention_flops_per_token_squared(config)
def layer_linear(ffn_hidden_size: int) -> int:
return qkv_per_token + 2 * hidden_size * hidden_size + _ffn_flops_per_token(hidden_size, ffn_hidden_size)
linear = (
num_dense_layers * layer_linear(_dense_ffn_hidden_size(config))
+ num_moe_layers * layer_linear(_moe_ffn_hidden_size(config))
+ 2 * hidden_size * config.vocab_size
)
quadratic = (num_dense_layers + num_moe_layers) * attn_per_token_squared
return linear, quadratic
def build_bin_cost(model_config: Any | None) -> Callable[[Sequence[int]], int]:
"""Build a closure scoring a packed bin by estimated forward compute.
With ``model_config=None`` the linear/quadratic coefficients are ``(1, 0)``, so
the cost reduces to the token count and balancing falls back to sequence length.
"""
if model_config is None:
linear, quadratic = 1, 0
else:
linear, quadratic = _packing_cost_coeffs(_text_config(model_config))
def bin_cost(seqlens: Sequence[int]) -> int:
return linear * sum(seqlens) + quadratic * sum(n * n for n in seqlens)
return bin_cost
@dataclass
class _WeightedSet:
total: int = 0
items: list[int] = field(default_factory=list)
def add(self, idx: int, weight: int) -> None:
self.items.append(idx)
self.total += weight
def merge(self, other: "_WeightedSet") -> None:
self.items.extend(other.items)
self.total += other.total
def __lt__(self, other: "_WeightedSet") -> bool:
if self.total != other.total:
return self.total < other.total
return self.items < other.items
class _KKState:
def __init__(self, items: list[tuple[int, int]], k: int):
self.sets = [_WeightedSet() for _ in range(k)]
for set_idx, (idx, weight) in enumerate(items):
self.sets[set_idx].add(idx, weight)
self.sets.sort(reverse=True)
@property
def spread(self) -> int:
return self.sets[0].total - self.sets[-1].total
def merge(self, other: "_KKState") -> None:
k = len(self.sets)
for i in range(k):
self.sets[i].merge(other.sets[k - 1 - i])
self.sets.sort(reverse=True)
def partitions(self) -> list[list[int]]:
return [sorted(weighted_set.items) for weighted_set in self.sets]
def __lt__(self, other: "_KKState") -> bool:
if self.spread != other.spread:
return self.spread > other.spread
return self.sets[0] > other.sets[0]
def _karmarkar_karp(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
assert len(weights) >= num_partitions
assert len(weights) % num_partitions == 0
weighted_indices = sorted((weight, idx) for idx, weight in enumerate(weights))
states: list[_KKState] = []
for offset in range(0, len(weighted_indices), num_partitions):
items = [(idx, weight) for weight, idx in weighted_indices[offset : offset + num_partitions]]
heapq.heappush(states, _KKState(items, num_partitions))
while len(states) > 1:
state = heapq.heappop(states)
state.merge(heapq.heappop(states))
heapq.heappush(states, state)
return states[0].partitions()
def _partition_loads(weights: Sequence[int], partitions: list[list[int]]) -> list[int]:
return [sum(weights[i] for i in partition) for partition in partitions]
def _refine_by_swapping(weights: Sequence[int], partitions: list[list[int]]) -> list[list[int]]:
partitions = [list(partition) for partition in partitions]
loads = _partition_loads(weights, partitions)
while True:
best_swap = None
best_score = (max(loads), max(loads) - min(loads))
for left_rank in range(len(partitions)):
for right_rank in range(left_rank + 1, len(partitions)):
for left_pos, left_idx in enumerate(partitions[left_rank]):
for right_pos, right_idx in enumerate(partitions[right_rank]):
new_left = loads[left_rank] - weights[left_idx] + weights[right_idx]
new_right = loads[right_rank] - weights[right_idx] + weights[left_idx]
new_loads = list(loads)
new_loads[left_rank] = new_left
new_loads[right_rank] = new_right
score = (max(new_loads), max(new_loads) - min(new_loads))
if score < best_score:
best_score = score
best_swap = (left_rank, right_rank, left_pos, right_pos, new_loads)
if best_swap is None:
return partitions
left_rank, right_rank, left_pos, right_pos, loads = best_swap
partitions[left_rank][left_pos], partitions[right_rank][right_pos] = (
partitions[right_rank][right_pos],
partitions[left_rank][left_pos],
)
def balanced_partition(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
"""Partition item indices into ``num_partitions`` groups of near-equal total weight.
Requires ``len(weights)`` to be a positive multiple of ``num_partitions``.
"""
partitions = _karmarkar_karp(weights, num_partitions)
return _refine_by_swapping(weights, partitions)
def _copy_routed_experts(routed_experts: RoutedExperts) -> RoutedExperts:
return RoutedExperts(
data=routed_experts.data,
@@ -229,32 +465,28 @@ def _is_multimodal_sample(sample: MicroBatch) -> bool:
@dataclass
class _MicroBatchBin:
samples: list[tuple[int, MicroBatch]]
samples: list[MicroBatch]
length: int
@classmethod
def from_sample(cls, lora_idx: int, sample: MicroBatch) -> "_MicroBatchBin":
return cls(samples=[(lora_idx, sample)], length=len(sample.input_ids))
def from_sample(cls, sample: MicroBatch) -> "_MicroBatchBin":
return cls(samples=[sample], length=len(sample.input_ids))
@property
def first_sample(self) -> MicroBatch:
return self.samples[0][1]
@property
def first_lora_idx(self) -> int:
return self.samples[0][0]
return self.samples[0]
@property
def first_multimodal_sample(self) -> MicroBatch | None:
for _, sample in self.samples:
for sample in self.samples:
if _is_multimodal_sample(sample):
return sample
return None
def can_add(self, sample: MicroBatch, max_seq_len: int, lora_idx: int) -> bool:
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
# Loss routing is per token (component weight streams), so samples of
# different loss types pack together freely. Multimodal packing is still
# constrained by modality sidecars, length, routed experts, and LoRA/run.
# constrained by modality sidecars, length, and routed experts.
first_sample = self.first_sample
if self.length + len(sample.input_ids) > max_seq_len:
return False
@@ -263,10 +495,6 @@ class _MicroBatchBin:
sample_is_mm = _is_multimodal_sample(sample)
existing_mm_sample = self.first_multimodal_sample
if existing_mm_sample is None and not sample_is_mm:
return True
if self.first_lora_idx != lora_idx:
return False
if existing_mm_sample is not None and sample_is_mm:
dst = existing_mm_sample.mm_kwargs
src = sample.mm_kwargs
@@ -280,39 +508,39 @@ class _MicroBatchBin:
)
return True
def add(self, lora_idx: int, sample: MicroBatch) -> None:
self.samples.append((lora_idx, sample))
def add(self, sample: MicroBatch) -> None:
self.samples.append(sample)
self.length += len(sample.input_ids)
def workload(self, bin_cost: Callable[[Sequence[int]], int]) -> int:
return bin_cost([len(sample.input_ids) for _, sample in self.samples])
return bin_cost([len(sample.input_ids) for sample in self.samples])
def split_by_workload(self, bin_cost: Callable[[Sequence[int]], int]) -> tuple["_MicroBatchBin", "_MicroBatchBin"]:
# Greedily place the heaviest sample on the currently lighter side (longest-processing-time).
ranked = sorted(self.samples, key=lambda pair: -bin_cost([len(pair[1].input_ids)]))
left: list[tuple[int, MicroBatch]] = []
right: list[tuple[int, MicroBatch]] = []
ranked = sorted(self.samples, key=lambda sample: -bin_cost([len(sample.input_ids)]))
left: list[MicroBatch] = []
right: list[MicroBatch] = []
left_workload = right_workload = 0
for lora_idx, sample in ranked:
for sample in ranked:
sample_workload = bin_cost([len(sample.input_ids)])
if left_workload <= right_workload:
left.append((lora_idx, sample))
left.append(sample)
left_workload += sample_workload
else:
right.append((lora_idx, sample))
right.append(sample)
right_workload += sample_workload
return (
_MicroBatchBin(left, sum(len(sample.input_ids) for _, sample in left)),
_MicroBatchBin(right, sum(len(sample.input_ids) for _, sample in right)),
_MicroBatchBin(left, sum(len(sample.input_ids) for sample in left)),
_MicroBatchBin(right, sum(len(sample.input_ids) for sample in right)),
)
def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
has_ref_logprobs = any(sample.ref_logprobs is not None for _, sample in bin_content.samples)
has_mm_token_type_ids = any(sample.mm_token_type_ids is not None for _, sample in bin_content.samples)
def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
has_ref_logprobs = any(sample.ref_logprobs is not None for sample in bin_content.samples)
has_mm_token_type_ids = any(sample.mm_token_type_ids is not None for sample in bin_content.samples)
# A weight stream materializes as soon as one packed sample carries it; the
# samples that lack it get the stream's identity fill (STREAM_FILL).
has_stream = {name: any(getattr(s, name) is not None for _, s in bin_content.samples) for name in STREAM_FILL}
has_stream = {name: any(getattr(s, name) is not None for s in bin_content.samples) for name in STREAM_FILL}
input_ids: list[int] = []
loss_mask: list[bool] = []
@@ -327,9 +555,8 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
seq_lens: list[int] = []
routed_experts: RoutedExperts | None = None
lora_num_tokens = [0] * num_loras
for lora_idx, sample in bin_content.samples:
for sample in bin_content.samples:
sample_len = len(sample.input_ids)
input_ids.extend(sample.input_ids)
loss_mask.extend(sample.loss_mask)
@@ -365,9 +592,8 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
mm_kwargs[key].data += sample.mm_kwargs[key].data
mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0]
seq_lens.extend(sample.seq_lens)
lora_num_tokens[lora_idx] += sample_len
sequence_lengths = [len(sample.input_ids) for _, sample in bin_content.samples]
sequence_lengths = [len(sample.input_ids) for sample in bin_content.samples]
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
assert sum(seq_lens) == len(input_ids), (seq_lens, len(input_ids))
@@ -380,7 +606,6 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
sequence_lengths=sequence_lengths,
ref_logprobs=ref_logprobs,
temperatures=temperatures,
lora_num_tokens=lora_num_tokens,
routed_experts=routed_experts,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
@@ -410,9 +635,8 @@ def _expand_bins_by_splitting(
def packed_samples_into_micro_bs(
samples: list[tuple[int, MicroBatch]],
samples: list[MicroBatch],
max_seq_len: int,
num_loras: int,
num_train_workers: int,
bin_cost: Callable[[Sequence[int]], int],
) -> list[MicroBatch]:
@@ -421,24 +645,24 @@ def packed_samples_into_micro_bs(
We follow the First Fit Decreasing algorithm to pack the samples into bins and minimize potential padding while never truncating.
With per-token temperatures, samples can be packed together regardless of their temperature values.
Multimodal samples pack with text spans from the same run/LoRA and with
compatible eager ``mm_kwargs`` samples. Packed batches preserve sample
boundaries in ``seq_lens``.
Multimodal samples pack with text spans and with compatible eager
``mm_kwargs`` samples. Packed batches preserve sample boundaries in
``seq_lens``.
"""
# Sort by (lora_idx, -length) for packing efficiency
samples.sort(key=lambda x: (x[0], -len(x[1].input_ids)))
# Sort by decreasing length for packing efficiency
samples.sort(key=lambda sample: -len(sample.input_ids))
bins: list[_MicroBatchBin] = []
for idx, sample in samples:
for sample in samples:
# Try to find a bin that can fit this sequence. Multimodal samples only
# pack when their sidecar tensors are compatible.
for bin_content in bins:
if bin_content.can_add(sample, max_seq_len, idx):
bin_content.add(idx, sample)
if bin_content.can_add(sample, max_seq_len):
bin_content.add(sample)
break
else:
bins.append(_MicroBatchBin.from_sample(idx, sample))
bins.append(_MicroBatchBin.from_sample(sample))
if num_train_workers > 1:
target_count = max(
@@ -447,7 +671,7 @@ def packed_samples_into_micro_bs(
)
_expand_bins_by_splitting(bins, target_count, bin_cost)
return [_materialize_bin(bin_content, num_loras) for bin_content in bins]
return [_materialize_bin(bin_content) for bin_content in bins]
def _distribute_group(
@@ -505,10 +729,6 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
stream = getattr(micro_batch, stream_name)
if stream is not None:
stream.extend([0.0] * padding_size)
if micro_batch.lora_num_tokens is not None:
micro_batch.lora_num_tokens[-1] += (
padding_size # We send padding to the last lora so that tokens have ascending lora idx
)
if micro_batch.mm_token_type_ids is not None:
micro_batch.mm_token_type_ids.extend([0] * padding_size)
if micro_batch.routed_experts is not None:
@@ -577,8 +797,6 @@ def prepare_batch(
rollouts: list[TrainingSample],
seq_len: int,
num_train_workers: int,
idxs: list[int],
num_loras: int,
bin_cost: Callable[[Sequence[int]], int],
pad_to_multiple_of: int = 1,
) -> list[list[MicroBatch]]:
@@ -591,9 +809,9 @@ def prepare_batch(
a text-only batch, the all-gather will hang. We separate micro batches by modality
and distribute them so that at each step index, all ranks see the same modality.
"""
all_samples = [(idx, prepare_sample(rollout, seq_len)) for idx, rollout in zip(idxs, rollouts)]
all_samples = [prepare_sample(rollout, seq_len) for rollout in rollouts]
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras, num_train_workers, bin_cost)
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_train_workers, bin_cost)
micro_batches = [pad_micro_batch(micro_batch, pad_to_multiple_of) for micro_batch in micro_batches]
# Separate by modality so each step index has uniform modality across all ranks
+10 -4
View File
@@ -3,7 +3,7 @@ import gc
import shutil
import time
import warnings
from dataclasses import asdict
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
@@ -22,10 +22,9 @@ from transformers.processing_utils import ProcessorMixin
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
from prime_rl.trainer.lora import has_lora_layers, save_lora_config
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.trainer.optim import CPUOffloadOptimizer
from prime_rl.trainer.runs import Progress, get_multi_run_manager
from prime_rl.trainer.weights import (
gather_weights_on_master,
save_state_dict,
@@ -35,6 +34,13 @@ 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
@dataclass
class Progress:
step: int = 1
total_tokens: int = 0
total_samples: int = 0
def _try_rmtree(path: Path, logger) -> None:
"""Remove a directory tree, logging and skipping on failure."""
try:
@@ -363,7 +369,7 @@ class WeightCheckpointManager:
f"base_model.model.{key}": (value.full_tensor() if isinstance(value, DTensor) else value).to(
"cpu", non_blocking=False
)
for key, value in get_multi_run_manager().get_state_dict_for_run(0).items()
for key, value in get_lora_state().adapter_state_dict().items()
}
if not lora_state_dict:
+96 -10
View File
@@ -1,21 +1,107 @@
import re
from typing import Dict, List
from typing import Callable, Dict, List
import torch
import torch.nn as nn
from prime_rl.configs.trainer import LoRAConfig
from prime_rl.trainer.models.layers.lora import MultiLoRALinear, MultiLoRAModule
from prime_rl.trainer.models.layers.lora import (
MultiLoRALinear,
MultiLoRAModule,
get_lora_num_tokens,
get_multilora_scaling,
set_lora_num_tokens,
set_multilora_scaling,
)
from prime_rl.trainer.models.layers.lora.multi_moe import (
MultiLoRAGptOssGroupedExperts,
MultiLoRAGroupedExperts,
MultiLoRANonGatedGroupedExperts,
)
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts, GroupedExperts, NonGatedGroupedExperts
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
class LoRAState:
"""Module registry + shared tensors for the single LoRA adapter.
Owns the canonical ``lora_num_tokens`` / ``scaling_factors`` tensors the
LoRA layers read (the layers capture references at construction, so this
must exist before ``apply_lora_to_model`` builds them) and the registry of
adapted modules used for optimizer setup, adapter state dicts, and
parameter resets."""
def __init__(self, config: LoRAConfig, device: torch.device):
set_lora_num_tokens(None, reset_reference=True)
set_multilora_scaling(None, reset_reference=True)
set_lora_num_tokens(torch.zeros(1, dtype=torch.int32, device=device), reset_reference=True)
set_multilora_scaling(
torch.full((1,), config.alpha / config.rank, dtype=torch.bfloat16, device=device),
reset_reference=True,
)
self.lora_num_tokens = get_lora_num_tokens()
self.scaling_factors = get_multilora_scaling()
self._modules: list[tuple[str, MultiLoRAModule]] = []
self._adapter_state_dict_converter: Callable[[dict[str, torch.Tensor]], dict[str, torch.Tensor]] | None = None
def register_adapter_state_dict_converter(
self, converter: Callable[[dict[str, torch.Tensor]], dict[str, torch.Tensor]]
) -> None:
"""Register a converter applied to adapter state dicts (e.g. model.convert_adapter_to_hf)."""
self._adapter_state_dict_converter = converter
def register_module(self, prefix: str, module: MultiLoRAModule) -> None:
"""Register an adapted module with its FQN prefix (e.g. "model.layers.0.self_attn.q_proj")."""
self._modules.append((prefix, module))
def named_adapter_parameters(self) -> list[tuple[str, nn.Parameter]]:
"""Named parameters of the adapter across all registered modules."""
params = []
for prefix, module in self._modules:
for name, param in module.named_parameters_for_adapter(0):
params.append((f"{prefix}.{name}.weight", param))
return params
def adapter_state_dict(self) -> dict[str, torch.Tensor]:
"""Adapter-only state dict, converted for HF compatibility when a converter is registered."""
state_dict = {}
for prefix, module in self._modules:
# MoE modules expose a custom state_dict_for_adapter returning the
# vLLM-compatible per-expert format
if hasattr(module, "state_dict_for_adapter"):
for name, tensor in module.state_dict_for_adapter(0).items():
state_dict[f"{prefix}.{name}"] = tensor.detach()
else:
for name, param in module.named_parameters_for_adapter(0):
state_dict[f"{prefix}.{name}.weight"] = param.detach()
if self._adapter_state_dict_converter is not None:
state_dict = self._adapter_state_dict_converter(state_dict)
return state_dict
def reset_adapter_parameters(self) -> None:
"""Reset the adapter to fresh initialization across all registered modules."""
for _, module in self._modules:
module.reset_parameters(0)
_LORA_STATE: LoRAState | None = None
def get_lora_state() -> LoRAState:
"""Returns the LoRAState singleton. Initialized by ``apply_lora_to_model``."""
if _LORA_STATE is None:
raise RuntimeError("LoRAState not initialized. Apply LoRA to the model first (`apply_lora_to_model`).")
return _LORA_STATE
def setup_lora_state(config: LoRAConfig, device: torch.device) -> LoRAState:
global _LORA_STATE
_LORA_STATE = LoRAState(config, device)
return _LORA_STATE
def strip_lora_from_state_dict(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
"""Strip LoRA from the state dict."""
new_state_dict = {}
@@ -143,9 +229,9 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
logger = get_logger()
from prime_rl.trainer.models import PreTrainedModelPrimeRL
lora_state = setup_lora_state(config, torch.device("cuda", get_world().local_rank))
if isinstance(model, PreTrainedModelPrimeRL):
get_multi_run_manager().register_adapter_state_dict_converter(type(model).convert_adapter_to_hf)
n_loras = get_multi_run_manager().max_runs
lora_state.register_adapter_state_dict_converter(type(model).convert_adapter_to_hf)
from torch.distributed.fsdp import FSDPModule
@@ -172,7 +258,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
lora_module = MultiLoRALinear(
base_layer=base_module,
rank=config.rank,
n_adapters=n_loras,
n_adapters=1,
alpha=config.alpha,
dropout=config.dropout,
)
@@ -181,7 +267,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
lora_module = MultiLoRAGroupedExperts(
base_layer=base_module,
rank=config.rank,
n_adapters=n_loras,
n_adapters=1,
alpha=config.alpha,
dropout=config.dropout,
)
@@ -190,7 +276,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
lora_module = MultiLoRANonGatedGroupedExperts(
base_layer=base_module,
rank=config.rank,
n_adapters=n_loras,
n_adapters=1,
alpha=config.alpha,
dropout=config.dropout,
)
@@ -199,7 +285,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
lora_module = MultiLoRAGptOssGroupedExperts(
base_layer=base_module,
rank=config.rank,
n_adapters=n_loras,
n_adapters=1,
alpha=config.alpha,
dropout=config.dropout,
)
@@ -210,7 +296,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
)
continue
lora_module.register_with_runs(get_multi_run_manager(), module_name)
lora_state.register_module(module_name, lora_module)
_set_module_by_name(model, module_name, lora_module)
freeze_all_except_lora_and_specified(model, config)
@@ -1,12 +1,9 @@
from abc import abstractmethod
from typing import TYPE_CHECKING, Any
from typing import Any
import torch
from torch import nn
if TYPE_CHECKING:
from prime_rl.trainer.runs import MultiRunManager
_LORA_PREFIX = "base_layer."
# Global state for multilora - initialized once in train.py, referenced by modules
@@ -123,24 +120,6 @@ class MultiLoRAModule(nn.Module):
"""
...
def register_with_runs(self, runs: "MultiRunManager", prefix: str) -> None:
"""Register this module with the MultiRunManager system.
This method should be called after FSDP/compile/AC setup as these
transformations may change the underlying parameters while preserving
the module.
The MultiRunManager class will use this registration to:
- Get named parameters for specific run indices (for optimizer setup)
- Reset parameters when new runs are created
- Construct sliced state dicts for weight broadcast
Args:
runs: The MultiRunManager instance to register with
prefix: The module's name/prefix in the model (e.g., "model.layers.0.self_attn.q_proj")
"""
runs.register_module(prefix, self)
def __getattr__(self, name: str) -> Any:
"""Forward missing attributes to wrapped module."""
try:
-233
View File
@@ -1,233 +0,0 @@
"""Multi-run checkpointing for RL training.
MultiCheckpointManager owns per-run CheckpointManagers and AppStates,
each saving to its own run directory.
"""
import shutil
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Any
import torch
import torch.distributed as dist
from torch.distributed.checkpoint.stateful import Stateful
from prime_rl.configs.trainer import CheckpointConfig
from prime_rl.trainer.ckpt import CheckpointManager
from prime_rl.trainer.runs import Progress, get_multi_run_manager
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_stable_ckpt_steps
if TYPE_CHECKING:
from prime_rl.trainer.optim import MultiLoRAOptimizer
from prime_rl.trainer.scheduler import MultiLoRAScheduler
class RunState(Stateful):
"""Per-run state wrapper - just like AppState but for adapter weights."""
def __init__(
self,
model_state_dict: dict[str, Any],
optimizer,
scheduler,
progress: Progress,
):
self.model_state_dict = model_state_dict
self.optimizer = optimizer
self.scheduler = scheduler
self.progress = progress
def state_dict(self) -> dict[str, Any]:
state = {
"model": self.model_state_dict,
"progress": asdict(self.progress),
}
if self.optimizer is not None:
state["optimizer"] = self.optimizer.state_dict()
if self.scheduler is not None:
state["scheduler"] = self.scheduler.state_dict()
return state
@torch.no_grad()
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
# Load adapter weights
for key, value in state_dict["model"].items():
if key in self.model_state_dict:
self.model_state_dict[key].copy_(value)
# Load optimizer
if "optimizer" in state_dict and self.optimizer is not None:
self.optimizer.load_state_dict(state_dict["optimizer"])
# Load scheduler
if "scheduler" in state_dict and self.scheduler is not None:
self.scheduler.load_state_dict(state_dict["scheduler"])
# Don't load progress because it resets packers count
# There will be a step issue if we load progress
class MultiCheckpointManager:
"""Owns per-run CheckpointManagers and AppStates."""
def __init__(self, output_dir: Path):
self.output_dir = output_dir
self.multi_run_manager = get_multi_run_manager()
self.world = get_world()
self.logger = get_logger()
self.managers: list[CheckpointManager | None] = [None] * self.multi_run_manager.max_runs
self.multi_run_manager.register_deletion_hook(self._run_deletion_hook)
self.multi_run_manager.register_creation_hook(self._run_creation_hook)
def _run_deletion_hook(self, idx: int, run_id: str) -> None:
self.managers[idx] = None
def _run_creation_hook(self, idx: int, run_id: str) -> None:
self.managers[idx] = self._maybe_create_manager(idx)
def _maybe_create_manager(self, idx: int) -> CheckpointManager | None:
ckpt_config = self.multi_run_manager.config[idx].ckpt
if ckpt_config is None:
return None
config = CheckpointConfig(
interval=ckpt_config.interval,
keep_last=ckpt_config.keep_last,
keep_interval=ckpt_config.keep_interval,
)
run_dir = self.multi_run_manager.get_run_dir(idx)
manager = CheckpointManager(run_dir, config)
self.managers[idx] = manager
return manager
def _should_save(self, idx: int, step: int) -> bool:
"""Determine if a checkpoint should be saved for a given run and step."""
ckpt_config = self.multi_run_manager.config[idx].ckpt
if ckpt_config is None or ckpt_config.interval is None:
return False
if step <= 0 or step % ckpt_config.interval != 0:
return False
# Check if already saved this step
return step not in self.managers[idx].ckpt_steps
def save(
self,
optimizer: "MultiLoRAOptimizer",
scheduler: "MultiLoRAScheduler",
) -> None:
for idx in self.multi_run_manager.used_idxs:
# pack() already advanced progress to the next step, so the step just finished
# (and its broadcasts/step_{step} weights) is progress - 1.
step = self.multi_run_manager.progress[idx].step - 1
if not self._should_save(idx, step):
continue
manager = self.managers[idx]
# We have a very wide try-except because we dont want to crash the trainer over one run having issues
try:
model_state_dict = {
k: v.data.detach().clone() for k, v in self.multi_run_manager.get_named_parameters_for_run(idx)
}
run_state = RunState(
model_state_dict,
optimizer.optimizers[idx],
scheduler.schedulers[idx],
self.multi_run_manager.progress[idx],
)
ckpt_path = manager.get_ckpt_path(step)
ckpt_path.mkdir(parents=True, exist_ok=True)
self.logger.info(
f"Saving checkpoint for run {idx} at step {step} to {ckpt_path / f'rank_{self.world.rank}.pt'}"
)
torch.save(run_state.state_dict(), ckpt_path / f"rank_{self.world.rank}.pt")
# Copy broadcast folder to checkpoint
# This way, we only need to save the checkpoint folder
if self.world.is_master:
run_dir = self.multi_run_manager.get_run_dir(idx)
broadcast_src = run_dir / "broadcasts" / f"step_{step}"
weight_dst = run_dir / "checkpoints" / f"step_{step}" / "weight"
try:
shutil.copytree(broadcast_src, weight_dst)
except FileNotFoundError:
self.logger.error(
f"Broadcast folder not found for run {idx} at step {step}. Looking for it in {broadcast_src}"
)
dist.barrier()
manager.mark_stable(step)
manager.ckpt_steps.append(step)
except FileNotFoundError:
self.logger.warning(f"Run {idx} deleted during checkpoint, skipping")
except Exception as e:
self.logger.error(f"Error checkpointing run {idx}: {e}")
dist.barrier()
# If the run is deleted, remove the run directory
# This is avoid the creation of zombie runs when the directory is deleted while we are checkpointing which recreates the directory
# Ideally we move this to discover but lets have here for now
if (
self.multi_run_manager.get_orchestrator_config(self.multi_run_manager.idx_2_id[idx]) is None
and self.world.is_master
):
try:
self.logger.warning(f"Run {idx} deleted during checkpoint, removing run directory")
shutil.rmtree(self.multi_run_manager.get_run_dir(idx))
except Exception as e:
self.logger.error(f"Error removing run directory for run {idx}: {e}")
dist.barrier()
def load_run(
self,
idx: int,
optimizer: "MultiLoRAOptimizer",
scheduler: "MultiLoRAScheduler",
) -> bool:
if (
self.multi_run_manager.config[idx].ckpt is None
or self.multi_run_manager.config[idx].ckpt.resume_step is None
):
return False
manager = self.managers[idx]
if manager is None:
return False
step = self.multi_run_manager.config[idx].ckpt.resume_step
if step == -1:
stable_steps = get_stable_ckpt_steps(manager.ckpt_dir)
if not stable_steps:
return False
step = max(stable_steps)
try:
model_state_dict = dict(self.multi_run_manager.get_named_parameters_for_run(idx))
run_state = RunState(
model_state_dict,
optimizer.optimizers[idx],
scheduler.schedulers[idx],
self.multi_run_manager.progress[idx],
)
ckpt_path = manager.get_ckpt_path(step)
if not ckpt_path.exists():
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
self.logger.info(f"Loading checkpoint from {ckpt_path}")
state_dict = torch.load(ckpt_path / f"rank_{self.world.rank}.pt", weights_only=False)
run_state.load_state_dict(state_dict)
self.logger.info(f"Resumed run {self.multi_run_manager.idx_2_id[idx]} from step {step}")
return True
except Exception as e:
self.logger.error(f"Error loading checkpoint for run {idx}: {e}")
return False
def maybe_clean(self) -> None:
if not self.world.is_master:
return
for idx in self.multi_run_manager.used_idxs:
if self.managers[idx] is None:
continue
self.managers[idx].maybe_clean()
def setup_multi_checkpoint_manager(output_dir: Path) -> tuple[MultiCheckpointManager, None]:
return MultiCheckpointManager(output_dir), None
-72
View File
@@ -1,5 +1,4 @@
import copy
from typing import Callable
import torch
from dion import Muon
@@ -9,7 +8,6 @@ from torch.optim import SGD, AdamW, Optimizer
from prime_rl.configs.trainer import OptimizerConfig
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.sign_sgd import SignSGD
from prime_rl.utils.logger import get_logger
@@ -112,16 +110,8 @@ def setup_optimizer(
config: OptimizerConfig,
named_params: list[tuple[str, nn.Parameter]],
parallel_dims: ParallelDims,
lora: bool = False,
cpu_offload: bool = False,
) -> Optimizer | CPUOffloadOptimizer:
if lora:
# Wait for run 0 to be created in the multi run manager
# Otherwise, the creation will reset the parameters
multi_run_manager = get_multi_run_manager()
multi_run_manager.wait_for_run(0)
named_params = multi_run_manager.get_named_parameters_for_run(0)
optimizer = _create_optimizer(config, named_params, parallel_dims)
if cpu_offload:
@@ -252,65 +242,3 @@ def _create_muon_optimizer(
fsdp_mesh_dim=1 if parallel_dims.dp_replicate_enabled else 0,
)
return optimizer
class MultiLoRAOptimizer:
def __init__(self, config: OptimizerConfig, parallel_dims: ParallelDims):
self.config = config
self.parallel_dims = parallel_dims
self.multi_run_manager = get_multi_run_manager()
self.logger = get_logger()
self.optimizers: list[Optimizer | None] = [None] * self.multi_run_manager.max_runs
self._post_creation_callbacks: list[Callable[[Optimizer, int], None]] = []
# Register creation hook for optimizer setup
# The MultiRunManager class handles parameter reset internally when new runs are created
self.multi_run_manager.register_creation_hook(self.optimizer_creation_hook)
def register_post_creation_callback(
self, callback: Callable[[Optimizer, int], None], index: int | None = None
) -> None:
"""Register a callback to be called after an optimizer is created.
Args:
callback: A callable that takes (optimizer: Optimizer, idx: int) as arguments.
index: Optional index to insert at. If None, appends to end.
"""
if index is None:
self._post_creation_callbacks.append(callback)
else:
self._post_creation_callbacks.insert(index, callback)
def optimizer_creation_hook(self, idx: int, run_id: str) -> None:
# Get named parameters for this run from the MultiRunManager system
named_params = self.multi_run_manager.get_named_parameters_for_run(idx)
lr = self.multi_run_manager.config[idx].optim.lr
self.optimizers[idx] = _create_optimizer(self.config, named_params, self.parallel_dims, lr)
# Call post-creation callbacks in order
for callback in self._post_creation_callbacks:
callback(self.optimizers[idx], idx)
def step(self):
for idx in self.multi_run_manager.ready_to_update_idxs:
self.optimizers[idx].step()
def zero_grad(self):
for idx in self.multi_run_manager.ready_to_update_idxs:
self.optimizers[idx].zero_grad()
def get_current_lr(self, idx: int | None = None) -> float:
if idx is None:
for idx in self.multi_run_manager.ready_to_update_idxs:
return self.optimizers[idx].param_groups[0]["lr"]
else:
self.logger.warning("No runs are ready to update. Returning 0.0 for current learning rate.")
return 0.0
else:
return self.optimizers[idx].param_groups[0]["lr"]
def setup_multi_optimizer(config: OptimizerConfig, parallel_dims: ParallelDims) -> MultiLoRAOptimizer:
return MultiLoRAOptimizer(config, parallel_dims)
+27 -64
View File
@@ -1,4 +1,3 @@
import shutil
import time
from pathlib import Path
from typing import Literal
@@ -7,10 +6,9 @@ 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 save_lora_config
from prime_rl.trainer.lora import get_lora_state, save_lora_config
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.utils import maybe_clean
from prime_rl.trainer.weights import (
gather_weights_on_master,
@@ -30,7 +28,6 @@ class FileSystemWeightBroadcast(WeightBroadcast):
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.multi_run_manager = get_multi_run_manager()
self.logger.debug(
f"Filesystem broadcast initialized (save_format={config.save_format}, save_sharded={self.save_sharded})"
)
@@ -41,7 +38,15 @@ class FileSystemWeightBroadcast(WeightBroadcast):
start_time = time.perf_counter()
adapter_only = self.lora_config is not None
if not adapter_only:
if adapter_only:
# All ranks must participate in DTensor gathering, but only master saves
state_dict = get_lora_state().adapter_state_dict()
for key, value in state_dict.items():
if isinstance(value, DTensor):
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)
@@ -50,59 +55,22 @@ class FileSystemWeightBroadcast(WeightBroadcast):
state_dict = revert_weight_conversion(model, state_dict)
for idx in self.multi_run_manager.ready_to_update_idxs:
self.logger.debug(
f"Broadcasting weights for run {idx} (ready_to_update={self.multi_run_manager.ready_to_update[idx]})"
)
if adapter_only:
# For adapter-only, MultiRunManager creates state dict directly for each run
# All ranks must participate in DTensor gathering, but only master saves
state_dict = self.multi_run_manager.get_state_dict_for_run(idx)
for key, value in state_dict.items():
if isinstance(value, DTensor):
value = value.full_tensor()
if self.world.is_master:
state_dict[key] = value.to("cpu", non_blocking=False)
# TODO: Broadcast ready to update in sync, then we dont need to gather on not ready
if self.world.is_master:
try:
# pack() already advanced progress to the next step, so the model we just
# trained — policy v(step-1) — broadcasts to broadcasts/step_{step-1}.
save_dir = get_step_path(
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
self.multi_run_manager.progress[idx].step - 1,
)
save_dir.mkdir(parents=True, exist_ok=True)
self.logger.debug(f"Saving weights for run {idx} to {save_dir}")
save_state_dict(state_dict, save_dir, self.save_format, self.save_sharded, adapter=adapter_only)
if adapter_only:
orch_lora = self.multi_run_manager.config[idx].model.lora
save_lora_config(
model,
save_dir,
rank=orch_lora.rank,
alpha=orch_lora.alpha,
dropout=self.lora_config.dropout,
)
self._notify_orchestrator(save_dir)
# If the run is deleted, remove the run directory
# This is avoid the creation of zombie runs when the directory is deleted while we are broadcasting which recreates the directory
if self.multi_run_manager.get_orchestrator_config(self.multi_run_manager.idx_2_id[idx]) is None:
shutil.rmtree(self.multi_run_manager.get_run_dir(idx))
except FileNotFoundError:
self.logger.warning(f"Run {idx} is deleted, skipping")
except Exception as e:
self.logger.error(f"Error broadcasting weights for run {idx}: {e}")
finally:
self.multi_run_manager.ready_to_update[idx] = False
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:
save_lora_config(
model,
save_dir,
rank=self.lora_config.rank,
alpha=self.lora_config.alpha,
dropout=self.lora_config.dropout,
)
self._notify_orchestrator(save_dir)
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
def _notify_orchestrator(self, save_dir: Path):
@@ -110,10 +78,5 @@ class FileSystemWeightBroadcast(WeightBroadcast):
stable_file = save_dir / "STABLE"
stable_file.touch()
def maybe_clean(self, interval_to_keep: int | None):
for idx in self.multi_run_manager.used_idxs:
maybe_clean(
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
self.multi_run_manager.progress[idx].step - 1,
interval_to_keep,
)
def maybe_clean(self, step: int, interval_to_keep: int | None):
maybe_clean(get_broadcast_dir(self.output_dir), step, interval_to_keep)
+13 -56
View File
@@ -15,7 +15,6 @@ from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.utils import get_world
from prime_rl.utils.client import NCCL_READY_MARKER
from prime_rl.utils.logger import get_logger
@@ -181,7 +180,6 @@ class NCCLWeightBroadcast(WeightBroadcast):
super().__init__(output_dir)
self.logger = get_logger()
self.world = get_world()
self.multi_run_manager = get_multi_run_manager()
self.nccl_broadcast_sender = NCCLWeightBroadcastSender(
config.host,
config.port,
@@ -198,70 +196,29 @@ class NCCLWeightBroadcast(WeightBroadcast):
"""Broadcast the state dict of a model into the inference pool using NCCL and notifies the orchestrator."""
self.logger.debug("Starting broadcasting weights to inference engine via NCCL")
start_time = time.perf_counter()
# `_compute_notified_runs` is a pure function of SPMD-replicated state on
# multi_run_manager, so every trainer rank derives the same list. Only
# the master touches the filesystem to notify the orchestrator, but all
# Only the master touches the filesystem to notify the orchestrator, but all
# ranks must wait for the inference pool before entering the broadcast path:
# the broadcast preparation (DTensor resolution, quantization) enqueues
# collectives on non-master ranks, and if those ranks start prep before
# the orchestrator has paused inference, the collectives sit unmatched
# until NCCL's watchdog kills the process after 10 min.
notified_runs = self._compute_notified_runs()
save_dir = get_step_path(get_broadcast_dir(self.output_dir), step)
if self.world.is_master:
self._notify_orchestrator(notified_runs)
self._wait_for_nccl_ready(notified_runs)
self._notify_orchestrator(save_dir)
self._wait_for_nccl_ready(save_dir)
if self.world.world_size > 1:
dist.barrier()
self.nccl_broadcast_sender.broadcast_weights(model, step)
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
def _compute_notified_runs(self) -> list[tuple[int, Path]]:
"""Derive the list of (run_idx, save_dir) pairs that need broadcasting.
def _notify_orchestrator(self, save_dir: Path) -> None:
"""Create the STABLE marker the orchestrator's weight watcher polls for."""
save_dir.mkdir(parents=True, exist_ok=True)
(save_dir / "STABLE").touch()
Pure function of `multi_run_manager` state, which is replicated across
trainer ranks (SPMD). Returns the same list on every rank so master and
non-master ranks agree on which NCCL_READY markers to wait for.
"""
notified_runs: list[tuple[int, Path]] = []
for idx in self.multi_run_manager.used_idxs:
if not self.multi_run_manager.ready_to_update[idx]:
continue
try:
# pack() already advanced progress to the next step, so the model we just
# trained — policy v(step-1) — broadcasts to broadcasts/step_{step-1}.
save_dir = get_step_path(
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
self.multi_run_manager.progress[idx].step - 1,
)
notified_runs.append((idx, save_dir))
except FileNotFoundError:
self.logger.warning(f"Run {idx} is deleted, skipping")
except Exception as e:
self.logger.error(f"Error resolving broadcast dir for run {idx}: {e}")
return notified_runs
def _notify_orchestrator(self, notified_runs: list[tuple[int, Path]]) -> None:
"""Create STABLE markers for each notified run and clear their ready flags.
Master-only side effects (filesystem writes + state mutation). Called
after `_compute_notified_runs`; non-master ranks skip this entirely.
"""
for idx, save_dir in notified_runs:
try:
save_dir.mkdir(parents=True, exist_ok=True)
stable_file = save_dir / "STABLE"
stable_file.touch()
except FileNotFoundError:
self.logger.warning(f"Run {idx} is deleted, skipping")
except Exception as e:
self.logger.error(f"Error broadcasting weights for run {idx}: {e}")
finally:
self.multi_run_manager.ready_to_update[idx] = False
def _wait_for_nccl_ready(self, notified_runs: list[tuple[int, Path]]):
def _wait_for_nccl_ready(self, save_dir: Path):
"""Wait for inference workers to signal they are ready to receive NCCL broadcast."""
for idx, save_dir in notified_runs:
nccl_ready_file = save_dir / NCCL_READY_MARKER
self.logger.debug(f"Waiting for NCCL_READY marker at {nccl_ready_file}")
sync_wait_for_path(nccl_ready_file, interval=0.1, log_interval=10)
self.logger.debug(f"Inference workers ready for NCCL broadcast (run {idx})")
nccl_ready_file = save_dir / NCCL_READY_MARKER
self.logger.debug(f"Waiting for NCCL_READY marker at {nccl_ready_file}")
sync_wait_for_path(nccl_ready_file, interval=0.1, log_interval=10)
self.logger.debug("Inference workers ready for NCCL broadcast")
@@ -36,7 +36,6 @@ from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import (
TrainerTensor,
TrainerTensorTable,
)
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.utils import get_world
LAYER_RE = re.compile(r"(?:^|\.)layers\.(\d+)(?=\.|$)")
@@ -74,7 +73,6 @@ class NIXLWeightBroadcast(WeightBroadcast):
self.config = config
self.parallel_dims = parallel_dims
self.world = get_world()
self.multi_run_manager = get_multi_run_manager()
if self.is_serving_rank:
set_ucx_env_defaults()
self.nixl_agent = NixlAgent(make_agent_name("trainer", self.world.rank))
@@ -408,7 +406,6 @@ class NIXLWeightBroadcast(WeightBroadcast):
@torch.no_grad()
def broadcast_weights(self, model: nn.Module, step: int) -> None:
ready_runs = list(self.multi_run_manager.ready_to_update_idxs)
self.initialize_transfer(model)
start = time.perf_counter()
@@ -465,6 +462,4 @@ class NIXLWeightBroadcast(WeightBroadcast):
)
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
dist.barrier()
for run_index in ready_runs:
self.multi_run_manager.ready_to_update[run_index] = False
self.logger.info(f"NIXL+ModelExpress policy v{step} synchronized in {time.perf_counter() - start:.2f}s")
+5 -46
View File
@@ -1,4 +1,3 @@
from collections.abc import Callable, Sequence
from pathlib import Path
from typing import TypedDict
@@ -7,8 +6,6 @@ from jaxtyping import Bool, Float, Int
from torch import Tensor
from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.world import get_world
from prime_rl.transport import (
MicroBatch,
@@ -54,10 +51,6 @@ class TensorMicroBatch(TypedDict):
ce_weights: Float[Tensor, "batch seq"] | None
ref_kl_weights: Float[Tensor, "batch seq"] | None
# Packer-derived metadata used for run-local debug exports.
run_id: str | None
run_step: int | None
class FakeDataLoader:
def __init__(self, config: FakeDataLoaderConfig, seq_len: int, dp_world_size: int):
@@ -71,7 +64,6 @@ class FakeDataLoader:
self.seq_len = seq_len
self.generate_samples = config.generate_samples
self.batch_counter = 0
self.multi_run_manager = get_multi_run_manager()
def wait_for_batch(self) -> None:
return
@@ -116,8 +108,6 @@ class FakeDataLoader:
loss_mask = torch.ones(input_ids.shape[0], dtype=torch.bool)
advantages = torch.randn(input_ids.shape[0], generator=generator)
inference_logprobs = torch.randn(input_ids.shape[0], generator=generator)
lora_num_tokens = torch.zeros(self.multi_run_manager.max_runs, dtype=torch.int32)
lora_num_tokens[0] = input_ids.shape[0]
return {
"input_ids": input_ids.unsqueeze(0),
@@ -129,7 +119,7 @@ class FakeDataLoader:
"env_names": ["fake"] * input_ids.shape[0],
"sequence_lengths": sequence_lengths,
"loss_mask": loss_mask.unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"lora_num_tokens": torch.tensor([input_ids.shape[0]], dtype=torch.int32),
"seq_lens": torch.tensor(sequence_lengths, dtype=torch.long),
"routed_experts": None,
"mm_kwargs": None,
@@ -137,13 +127,9 @@ class FakeDataLoader:
"rl_weights": None,
"ce_weights": None,
"ref_kl_weights": None,
"run_id": None,
"run_step": None,
}
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
lora_num_tokens = torch.zeros(self.multi_run_manager.max_runs, dtype=torch.int32)
lora_num_tokens[0] = self.seq_len
return {
"input_ids": torch.randint(
0,
@@ -162,7 +148,7 @@ class FakeDataLoader:
"env_names": ["fake"] * self.seq_len,
"sequence_lengths": [self.seq_len],
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"lora_num_tokens": torch.tensor([self.seq_len], dtype=torch.int32),
"seq_lens": torch.tensor([self.seq_len], dtype=torch.long),
"routed_experts": None,
"mm_kwargs": None,
@@ -170,51 +156,28 @@ class FakeDataLoader:
"rl_weights": None,
"ce_weights": None,
"ref_kl_weights": None,
"run_id": None,
"run_step": None,
}
class DataLoader:
"""Loads serialized data from a data path written by the orchestrator."""
"""Receives packed micro batches from the orchestrator, one stream per DP rank."""
def __init__(
self,
output_dir: Path,
start_step: int,
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
bin_cost: Callable[[Sequence[int]], int],
config: TransportConfig,
):
self.world = get_world()
if self.world.is_master:
self.packer: BasePacker = setup_packer(
dp_world_size=dp_world_size,
seq_len=seq_len,
transport_config=config,
pad_to_multiple_of=pad_to_multiple_of,
bin_cost=bin_cost,
start_step=start_step,
)
non_dp_world_size = self.world.world_size // dp_world_size
dp_rank = self.world.rank // non_dp_world_size
self.multi_run_manager = get_multi_run_manager()
self.receiver: MicroBatchReceiver = setup_micro_batch_receiver(output_dir, dp_rank, start_step, config)
def wait_for_batch(self) -> None:
if self.world.is_master:
self.packer._arm_watchdog()
try:
self.packer.pack()
finally:
self.packer._disarm_watchdog()
self.receiver.wait()
self.multi_run_manager.synchronize_state()
def get_batch(self) -> list[TensorMicroBatch]:
micro_batches = self.receiver.receive()
@@ -222,9 +185,6 @@ class DataLoader:
def _micro_batch_to_tensor(self, micro_batch: MicroBatch) -> TensorMicroBatch:
"""Convert a MicroBatch (msgspec struct with lists) to a TensorMicroBatch (dict with tensors)."""
if micro_batch.lora_num_tokens is None:
micro_batch.lora_num_tokens = [0] * self.multi_run_manager.max_runs
micro_batch.lora_num_tokens[0] = len(micro_batch.input_ids)
mm_kwargs: dict[str, Tensor] | None = None
if micro_batch.mm_kwargs:
# Each value is an EncodedTensor (dtype, shape, raw bytes).
@@ -258,7 +218,8 @@ class DataLoader:
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
env_names=micro_batch.env_names,
sequence_lengths=micro_batch.sequence_lengths,
lora_num_tokens=torch.tensor(micro_batch.lora_num_tokens, dtype=torch.int32),
# Single adapter: every token in the batch belongs to it (padding included).
lora_num_tokens=torch.tensor([len(micro_batch.input_ids)], dtype=torch.int32),
seq_lens=torch.tensor(micro_batch.seq_lens, dtype=torch.long),
mm_kwargs=mm_kwargs,
mm_token_type_ids=torch.tensor(micro_batch.mm_token_type_ids, dtype=torch.long).unsqueeze(0)
@@ -274,8 +235,6 @@ class DataLoader:
ref_kl_weights=torch.tensor(micro_batch.ref_kl_weights, dtype=torch.float).unsqueeze(0)
if micro_batch.ref_kl_weights is not None
else None,
run_id=micro_batch.run_id,
run_step=micro_batch.run_step,
)
-358
View File
@@ -1,358 +0,0 @@
import os
import shutil
import threading
import time
from abc import ABC, abstractmethod
from collections import deque
from collections.abc import Callable, Sequence
from prime_rl.trainer.batch import multimodal_sample_error, prepare_batch
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.transport import (
MicroBatch,
MicroBatchSender,
TrainingSample,
TransportConfig,
setup_micro_batch_sender,
setup_training_batch_receiver,
)
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_rollout_dir
TIMEOUT_SECONDS = 0.1
WATCHDOG_TIMEOUT_SECONDS = 1800 # 30 minutes
class BasePacker(ABC):
def __init__(
self,
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
self.logger = get_logger()
self.multi_run_manager = get_multi_run_manager()
self.dp_world_size = dp_world_size
self.seq_len = seq_len
self.pad_to_multiple_of = pad_to_multiple_of
self.bin_cost = bin_cost
self.receiver = setup_training_batch_receiver(config)
shutil.rmtree(get_rollout_dir(self.multi_run_manager.output_dir), ignore_errors=True)
self.sender: MicroBatchSender = setup_micro_batch_sender(
self.multi_run_manager.output_dir, dp_world_size, start_step, config
)
self._last_heartbeat = time.monotonic()
self._watchdog_armed = threading.Event()
self._watchdog = threading.Thread(target=self._watchdog_loop, daemon=True)
self._watchdog.start()
def _heartbeat(self) -> None:
self._last_heartbeat = time.monotonic()
def _arm_watchdog(self) -> None:
self._last_heartbeat = time.monotonic()
self._watchdog_armed.set()
def _disarm_watchdog(self) -> None:
self._watchdog_armed.clear()
def _watchdog_loop(self) -> None:
while True:
time.sleep(60)
if not self._watchdog_armed.is_set():
continue
stale = time.monotonic() - self._last_heartbeat
if stale > WATCHDOG_TIMEOUT_SECONDS:
self.logger.error(f"Packer heartbeat stale for {stale:.0f}s, killing process to trigger restart")
os._exit(1)
@abstractmethod
def pack(self) -> None:
"""Pack samples for the next step."""
pass
class SinglePacker(BasePacker):
def __init__(
self,
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, config, bin_cost, start_step)
assert self.multi_run_manager.max_runs == 1, "SinglePacker only supports one run"
def pack(self):
# Wait for batch to be available
batches = []
while len(batches) == 0:
self._heartbeat()
self.multi_run_manager.discover_runs()
batches = self.receiver.receive()
time.sleep(0.2)
assert len(batches) == 1, "SinglePacker only supports one batch per step"
batch = batches[0]
self.multi_run_manager.ready_to_update[0] = True
self.multi_run_manager.progress[0].step += 1
micro_batch_grid = prepare_batch(
rollouts=batch.examples,
seq_len=self.seq_len,
pad_to_multiple_of=self.pad_to_multiple_of,
num_train_workers=self.dp_world_size,
idxs=[0] * len(batch.examples),
num_loras=self.multi_run_manager.max_runs,
bin_cost=self.bin_cost,
)
# The receiver always stamps run_idx from used_idxs (a key of idx_2_id).
run_id = self.multi_run_manager.idx_2_id[batch.run_idx]
for worker_batches in micro_batch_grid:
for micro_batch in worker_batches:
micro_batch.run_id = run_id
micro_batch.run_step = batch.step
self.sender.send(micro_batch_grid)
class MultiPacker(BasePacker):
def __init__(
self,
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, config, bin_cost, start_step)
# Per-run buffer: stores (TrainingSample, step) tuples
self.buffers: list[deque[tuple[TrainingSample, int]]] = [
deque() for _ in range(self.multi_run_manager.max_runs)
]
# Round-robin position (persists across pack() calls)
self._round_robin_position: int = 0
# Register forgotten hook for receiver reset (master only, called during discover_runs)
# This must happen when a run is deleted to prevent stale data from remaining
self.multi_run_manager.register_forgotten_hook(self._on_run_data_deleted)
def _on_run_data_deleted(self, idx: int, run_id: str) -> None:
"""Reset run state when run data is deleted (master only)."""
self.logger.debug(f"Packing is resetting run state for deleted run {idx}")
self.receiver.reset_run(idx)
# Reset run state
self.buffers[idx].clear()
def _validate_sample(self, sample: TrainingSample) -> tuple[bool, str | None]:
"""Validate a sample to ensure it won't crash the trainer."""
sample_length = len(sample.token_ids)
for name, arr in (
("mask", sample.mask),
("logprobs", sample.logprobs),
("temperatures", sample.temperatures),
):
if len(arr) != sample_length:
return (
False,
f"Run wrote a sample with {name} length != token_ids length ({len(arr)} != {sample_length})",
)
if sample_length == 0:
return False, "Run wrote a sample with no tokens"
if sample_length > self.seq_len:
return (
False,
f"Run wrote a sample with length {sample_length} which exceeds max sequence length {self.seq_len}",
)
if sample.ref_logprobs is not None and len(sample.ref_logprobs) != sample_length:
return (
False,
f"Run wrote a sample with ref logprobs length != sample length ({len(sample.ref_logprobs)} != {sample_length})",
)
if error := multimodal_sample_error(sample):
return False, error
return True, None
def _get_batch(self) -> None:
"""Receive batches from orchestrator and buffer samples per run."""
self._heartbeat()
self.multi_run_manager.discover_runs()
batches = self.receiver.receive()
for batch in batches:
if batch.run_idx is None:
self.logger.warning("Received batch with no run index")
continue
if len(batch.examples) == 0:
self.multi_run_manager.evict_run(batch.run_idx, "Run wrote a batch with no samples")
continue
for sample in batch.examples:
valid, reason = self._validate_sample(sample)
if not valid:
self.multi_run_manager.evict_run(batch.run_idx, f"Run wrote a sample with invalid data: {reason}")
break
self.buffers[batch.run_idx].append((sample, batch.step))
# This is necessary to forget evicted runs
self.multi_run_manager.discover_runs()
def _count_tokens(self, threshold: int | None = None) -> int:
tokens = 0
for run_idx in self.multi_run_manager.used_idxs:
buffer = self.buffers[run_idx]
current_step = self.multi_run_manager.progress[run_idx].step
for sample, step in buffer:
if step > current_step:
break
tokens += len(sample.token_ids)
if threshold is not None and tokens >= threshold:
return tokens
return tokens
def _has_enough_tokens(self) -> bool:
"""Check if we have enough samples in buffer to pack a step"""
# When not using small batch granularity, require at least one full batch
threshold = self.seq_len * self.dp_world_size
return self._count_tokens(threshold) >= threshold
def _select_samples_round_robin(self, token_budget: int) -> list[tuple[int, TrainingSample, int]]:
"""Select samples using round-robin from runs with buffered work."""
selected: list[tuple[int, TrainingSample, int]] = []
tokens_collected = 0
while tokens_collected < token_budget:
# Round-robin until we find a run with work for the current step
for _ in range(len(self.buffers)):
if len(self.buffers[self._round_robin_position]) > 0:
_, step = self.buffers[self._round_robin_position][0]
if step <= self.multi_run_manager.progress[self._round_robin_position].step:
break
self._round_robin_position = (self._round_robin_position + 1) % len(self.buffers)
else:
# TODO: We could probably make the logic safer. This is basically counting on _has_enough_tokens() to be correct.
# We also need to cover the timeout case here.
break
run_idx = self._round_robin_position
self._round_robin_position = (self._round_robin_position + 1) % len(self.buffers)
current_step = self.multi_run_manager.progress[run_idx].step
while len(self.buffers[run_idx]) > 0:
sample, step = self.buffers[run_idx][0]
if step > current_step:
# Samples from different steps should be consumed later
break
tokens_collected += len(sample.token_ids)
if tokens_collected > token_budget:
if tokens_collected == (len(sample.token_ids)):
tokens_collected -= len(sample.token_ids)
# This means we have a sample that has more tokens than max seqlen
self.buffers[run_idx].popleft()
continue
return selected
selected.append((run_idx, sample, step))
self.buffers[run_idx].popleft()
return selected
def _update_run_progress(self, run_idx: int, num_samples: int, num_tokens: int) -> None:
"""Update run progress; increment step when all samples from the current step have been consumed."""
# HACK: This fixes the issue with branching rollouts having unpredictable batch size
# However, it makes us unable to do incremental orchestrator rollouts
# Removing the len(self.buffers[run_idx]) == 0 check would allow incremental orchestrator rollouts
if (
len(self.buffers[run_idx]) == 0
or self.buffers[run_idx][0][1] > self.multi_run_manager.progress[run_idx].step
):
self.multi_run_manager.progress[run_idx].step += 1
self.multi_run_manager.ready_to_update[run_idx] = True
self.multi_run_manager.progress[run_idx].total_tokens += num_tokens
self.multi_run_manager.progress[run_idx].total_samples += num_samples
def pack(self):
"""Pack samples from buffers using round-robin fair scheduling."""
self._get_batch()
start_time = time.time()
while not self._has_enough_tokens():
if time.time() - start_time > TIMEOUT_SECONDS and self._count_tokens() > 0:
self.logger.warning("Timeout waiting for enough tokens to pack")
break
time.sleep(1)
self._get_batch()
token_budget = self.seq_len * self.dp_world_size
selected_samples = self._select_samples_round_robin(token_budget)
assert selected_samples, "No samples selected"
# Group samples by run_idx - each microbatch must contain samples from only ONE run
# because MultiLoRAGroupedExperts (MoE) only supports one adapter per microbatch
samples_by_run: dict[int, list[TrainingSample]] = {}
steps_by_run: dict[int, int] = {}
per_run_stats: dict[int, tuple[int, int]] = {}
for run_idx, sample, step in selected_samples:
if run_idx not in samples_by_run:
samples_by_run[run_idx] = []
steps_by_run[run_idx] = step
else:
assert steps_by_run[run_idx] == step, "Micro batches for a run must come from a single run step"
samples_by_run[run_idx].append(sample)
num_tokens = len(sample.token_ids)
if run_idx in per_run_stats:
cur_samples, cur_tokens = per_run_stats[run_idx]
per_run_stats[run_idx] = (cur_samples + 1, cur_tokens + num_tokens)
else:
per_run_stats[run_idx] = (1, num_tokens)
for run_idx, (num_samples, num_tokens) in per_run_stats.items():
self._update_run_progress(run_idx, num_samples, num_tokens)
# Pack each run separately to ensure no mixing of runs in microbatches
all_micro_batches: list[list[MicroBatch]] = [[] for _ in range(self.dp_world_size)]
for run_idx in sorted(samples_by_run.keys()):
run_samples = samples_by_run[run_idx]
run_micro_batch_grid = prepare_batch(
rollouts=run_samples,
seq_len=self.seq_len,
pad_to_multiple_of=self.pad_to_multiple_of,
num_train_workers=self.dp_world_size,
idxs=[run_idx] * len(run_samples),
num_loras=self.multi_run_manager.max_runs,
bin_cost=self.bin_cost,
)
run_id = self.multi_run_manager.idx_2_id[run_idx]
run_step = steps_by_run[run_idx]
# Merge into combined grid
for worker_idx, worker_batches in enumerate(run_micro_batch_grid):
for micro_batch in worker_batches:
micro_batch.run_id = run_id
micro_batch.run_step = run_step
all_micro_batches[worker_idx].extend(worker_batches)
self.sender.send(all_micro_batches)
def setup_packer(
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
transport_config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
) -> BasePacker:
multi_run_manager = get_multi_run_manager()
if multi_run_manager.max_runs == 1:
return SinglePacker(dp_world_size, seq_len, pad_to_multiple_of, transport_config, bin_cost, start_step)
else:
return MultiPacker(dp_world_size, seq_len, pad_to_multiple_of, transport_config, bin_cost, start_step)
+18 -37
View File
@@ -10,7 +10,6 @@ from torch import Tensor
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
from prime_rl.utils.logger import get_logger
SCHEMA_VERSION = 1
@@ -19,7 +18,7 @@ class DisabledTokenExporter:
def export(self, *args: Any, **kwargs: Any) -> None:
return
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
def mark_stable(self) -> None:
return
def close(self) -> None:
@@ -35,9 +34,9 @@ class TokenExporter:
self.rank = rank
self.output_dir = output_dir / "token_exports"
self._closed = False
self._initialized_files: set[tuple[str | None, int, int]] = set()
self._sequences_by_file: dict[tuple[str | None, int, int], int] = {}
self._pending_stable_dirs: dict[str | None, set[Path]] = {}
self._initialized_files: set[tuple[int, int]] = set()
self._sequences_by_file: dict[tuple[int, int], int] = {}
self._pending_stable_dirs: set[Path] = set()
atexit.register(self.close)
def export(
@@ -51,9 +50,7 @@ class TokenExporter:
) -> None:
columns = _export_columns(micro_batch, model_output, loss_config)
_check_lengths(columns)
run_id = micro_batch.get("run_id")
export_step = micro_batch.get("run_step") if micro_batch.get("run_step") is not None else step
file_key = (run_id, export_step, self.rank)
file_key = (step, self.rank)
start = 0
for micro_sequence_idx, length in enumerate(sequence_lengths):
@@ -64,17 +61,14 @@ class TokenExporter:
{
"schema_version": SCHEMA_VERSION,
"step": step,
"export_step": export_step,
"rank": self.rank,
"micro_step": micro_step,
"micro_sequence_idx": micro_sequence_idx,
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
"run_id": run_id,
"env_name": _first_non_empty(columns["env_names"][start:end]),
**_slice_columns(columns, start, end),
},
run_id,
export_step,
step,
)
self._sequences_by_file[file_key] = self._sequences_by_file.get(file_key, 0) + 1
start = raw_end
@@ -84,33 +78,20 @@ class TokenExporter:
return
self._closed = True
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
# A single run step's sequences can span multiple trainer steps (the packer
# splits a run step across packs when it exceeds the token budget). Only
# finalize a run's export dir once that run step is fully consumed — the same
# `ready_to_update` signal that gates its optimizer step. ``run_id is None``
# is single-run export, where a step never spans trainer steps, so mark it now.
def mark_stable(self) -> None:
# The caller barriers first so a STABLE only lands after every rank flushed.
ready_run_ids = ready_run_ids or set()
for run_id in [rid for rid in self._pending_stable_dirs if rid is None or rid in ready_run_ids]:
for stable_dir in self._pending_stable_dirs.pop(run_id):
try:
(stable_dir / "STABLE").touch()
except FileNotFoundError:
# A multi-run run dir can be deleted while its tail steps are
# still flushing (mirrors the broadcast paths' guard)
get_logger().warning(f"Run dir for {run_id} is deleted, skipping token-export STABLE marker")
while self._pending_stable_dirs:
stable_dir = self._pending_stable_dirs.pop()
(stable_dir / "STABLE").touch()
def _export_dir(self, export_step: int, run_id: str | None) -> Path:
if run_id is not None:
return self.output_dir.parent / run_id / "token_exports" / f"step_{export_step}"
return self.output_dir / f"step_{export_step}"
def _export_dir(self, step: int) -> Path:
return self.output_dir / f"step_{step}"
def _export_file(self, export_step: int, run_id: str | None) -> Path:
def _export_file(self, step: int) -> Path:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
step_dir = self._export_dir(export_step, run_id)
step_dir = self._export_dir(step)
try:
step_dir.mkdir(parents=True, exist_ok=True)
except FileExistsError:
@@ -118,17 +99,17 @@ class TokenExporter:
raise
return step_dir / f"rank_{self.rank}.jsonl"
def _write(self, record: dict[str, Any], run_id: str | None, export_step: int) -> None:
def _write(self, record: dict[str, Any], step: int) -> None:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
file_key = (run_id, export_step, self.rank)
file_key = (step, self.rank)
mode = "a" if file_key in self._initialized_files else "w"
export_file = self._export_file(export_step, run_id)
export_file = self._export_file(step)
with export_file.open(mode, encoding="utf-8") as file:
file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
self._initialized_files.add(file_key)
self._pending_stable_dirs.setdefault(run_id, set()).add(export_file.parent)
self._pending_stable_dirs.add(export_file.parent)
def setup_token_exporter(
+37 -108
View File
@@ -13,10 +13,9 @@ 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 setup_ckpt_managers
from prime_rl.trainer.multi_ckpt import setup_multi_checkpoint_manager
from prime_rl.trainer.optim import setup_optimizer, setup_multi_optimizer
from prime_rl.trainer.scheduler import setup_scheduler, setup_multi_scheduler
from prime_rl.trainer.ckpt import Progress, setup_ckpt_managers
from prime_rl.trainer.optim import setup_optimizer
from prime_rl.trainer.scheduler import setup_scheduler
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
from prime_rl.utils.cp import (
@@ -46,7 +45,6 @@ from prime_rl.trainer.model import (
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
from prime_rl.trainer.perf import get_perf_counter
from prime_rl.trainer.utils import (
build_bin_cost,
GarbageCollection,
MemoryProfiler,
Tensors,
@@ -58,10 +56,10 @@ from prime_rl.trainer.utils import (
print_benchmark,
)
from prime_rl.trainer.world import get_world
from prime_rl.trainer.runs import setup_multi_run_manager, Progress, get_multi_run_manager
from prime_rl.trainer.lora import get_lora_state
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.metrics_server import HealthServer, MetricsServer, RunStats
from prime_rl.utils.metrics_server import HealthServer, MetricsServer
from prime_rl.utils.monitor import setup_monitor
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
@@ -118,33 +116,22 @@ def train(config: TrainerConfig):
# (e.g. matmul_precision = "highest") on ROCm.
torch.set_float32_matmul_precision(config.matmul_precision)
# Setup multi run manager and offsets (including LoRA validation/scaling hooks if applicable)
multi_run_manager = setup_multi_run_manager(
config.output_dir, config.max_concurrent_runs, torch.device("cuda", world.local_rank), config.model.lora
)
# Resolve ep="auto" to a concrete integer before creating parallel dims
resolve_ep(config.model)
# Initialize parallel dimensions
parallel_dims = get_parallel_dims(config.model)
# For single-run, check for checkpoint to resume from
# Check for checkpoint to resume from
checkpoint_step = None
if config.max_concurrent_runs == 1:
# Set up checkpoint manager for single-run
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
ckpt_manager, weight_ckpt_manager = setup_ckpt_managers(config.output_dir, config.ckpt, config.model.lora)
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
ckpt_manager, weight_ckpt_manager = setup_ckpt_managers(config.output_dir, config.ckpt, config.model.lora)
if config.ckpt and config.ckpt.resume_step is not None and ckpt_manager is not None:
if config.ckpt.resume_step == -1:
checkpoint_step = resolve_latest_ckpt_step(ckpt_manager.ckpt_dir)
else:
checkpoint_step = config.ckpt.resume_step
else:
# Multi-run uses per-run checkpointing via MultiCheckpointManager
ckpt_manager, weight_ckpt_manager = setup_multi_checkpoint_manager(config.output_dir)
logger.info("Initialized multi-run checkpoint manager")
if config.ckpt and config.ckpt.resume_step is not None and ckpt_manager is not None:
if config.ckpt.resume_step == -1:
checkpoint_step = resolve_latest_ckpt_step(ckpt_manager.ckpt_dir)
else:
checkpoint_step = config.ckpt.resume_step
# Initialize the model and tokenizer
logger.info(f"Initializing model ({config.model})")
@@ -164,24 +151,13 @@ def train(config: TrainerConfig):
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
if config.max_concurrent_runs == 1:
optimizer = setup_optimizer(
config.optim,
list(model.named_parameters()),
parallel_dims,
lora=config.model.lora is not None,
cpu_offload=config.model.optim_cpu_offload,
)
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
else:
optimizer = setup_multi_optimizer(config.optim, parallel_dims)
scheduler = setup_multi_scheduler(optimizer, config.scheduler, config.max_steps)
# Register checkpoint loading callback at index 1 (after scheduler creation at index 0)
def load_run_checkpoint(_optimizer, idx: int) -> None:
ckpt_manager.load_run(idx, optimizer, scheduler)
optimizer.register_post_creation_callback(load_run_checkpoint, index=1)
optimizer = setup_optimizer(
config.optim,
list(model.named_parameters()),
parallel_dims,
cpu_offload=config.model.optim_cpu_offload,
)
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
logger.info(f"Using `{config.scheduler.type}` scheduler ({config.scheduler})")
@@ -226,6 +202,11 @@ def train(config: TrainerConfig):
if config.model.cp_style == "ulysses":
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
# Fresh adapter init after FSDP materialization (the pretrained checkpoint
# carries no adapter weights); a checkpoint resume below overwrites it.
if config.model.lora is not None:
get_lora_state().reset_adapter_parameters()
# Optionally, resume training from a checkpoint
progress = Progress()
if checkpoint_step is not None:
@@ -247,9 +228,6 @@ def train(config: TrainerConfig):
config.output_dir,
progress.step,
parallel_dims.get_mesh("dp").size(),
config.model.seq_len,
config.model.cp,
build_bin_cost(model.config),
config.rollout_transport,
)
@@ -274,17 +252,12 @@ def train(config: TrainerConfig):
logger.debug(f"Starting training step {progress.step}")
step_start_time = time.perf_counter()
# In-memory transfers broadcast the incoming policy (v{progress.step-1}) before waiting
# for its rollouts so the trainer and inference pool join the same update lifecycle.
if (
progress.step == start_step
and weight_broadcast is not None
and config.weight_broadcast.type in ("nccl", "nixl")
):
# Broadcast the incoming policy (v{progress.step-1}) before waiting for its
# rollouts so the trainer and inference pool join the same update lifecycle,
# and so a broken broadcast path fails at startup instead of after the first
# optimizer step.
if progress.step == start_step and weight_broadcast is not None:
logger.info(f"Broadcasting startup policy weights (v{progress.step - 1}) to inference engines")
multi_run_manager.wait_for_run(0)
for idx in multi_run_manager.used_idxs:
multi_run_manager.ready_to_update[idx] = True
weight_broadcast.broadcast_weights(model, step=progress.step - 1)
# Wait for the batch to be available
@@ -554,12 +527,7 @@ def train(config: TrainerConfig):
if config.enable_token_export:
dist.barrier()
ready_run_ids = {
multi_run_manager.idx_2_id[idx]
for idx in multi_run_manager.ready_to_update_idxs
if idx in multi_run_manager.idx_2_id
}
token_exporter.mark_stable(ready_run_ids)
token_exporter.mark_stable()
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
# across dp_cp so the final gradient is the true per-token mean over the global batch.
@@ -585,10 +553,7 @@ def train(config: TrainerConfig):
# Update learning rate scheduler
scheduler.step()
if config.max_concurrent_runs == 1:
current_lr = optimizer.param_groups[0]["lr"]
else:
current_lr = optimizer.get_current_lr()
current_lr = optimizer.param_groups[0]["lr"]
forward_backward_time = time.perf_counter() - forward_backward_start_time
# Broadcast the model just produced (policy v{progress.step}) so the orchestrator can
@@ -609,22 +574,12 @@ def train(config: TrainerConfig):
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
if config.weight_broadcast.type == "filesystem":
interval_to_keep = config.ckpt and config.ckpt.interval
weight_broadcast.maybe_clean(interval_to_keep)
weight_broadcast.maybe_clean(progress.step, interval_to_keep)
else:
broadcast_weights_time = 0
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
for idx in multi_run_manager.used_idxs:
multi_run_manager.ready_to_update[idx] = False
# Checkpoint the step we just finished (model = policy v{progress.step}).
if config.max_concurrent_runs > 1:
# Multi-run: save per-run checkpoints every step (interval-gated inside
# MultiCheckpointManager); there is no after-loop final save for multi-run.
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(optimizer, scheduler)
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
ckpt_manager.maybe_clean()
elif (
if (
ckpt_manager is not None
and (config.ckpt and config.ckpt.interval)
# the last step is written once after the loop (final ckpt), so skip it here
@@ -634,7 +589,6 @@ def train(config: TrainerConfig):
save_ckpt_time = 0
if not config.ckpt.weights_only:
# Single-run: 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)
@@ -743,31 +697,6 @@ def train(config: TrainerConfig):
mismatch_kl=tensor_stats.get("mismatch_kl/all/mean", 0.0),
zero_grad_ratio=zero_grad_ratio,
)
# Update run/LoRA metrics
multi_run_manager = get_multi_run_manager()
runs_discovered = len(list(config.output_dir.glob("run_*")))
run_stats = []
for idx in multi_run_manager.used_idxs:
run_id = multi_run_manager.idx_2_id[idx]
run_progress = multi_run_manager.progress[idx]
if config.max_concurrent_runs == 1:
lr = optimizer.param_groups[0]["lr"]
else:
lr = optimizer.get_current_lr(idx) if optimizer.optimizers[idx] else 0.0
run_stats.append(
RunStats(
run_id=run_id,
step=run_progress.step,
total_tokens=run_progress.total_tokens,
learning_rate=lr,
ready=multi_run_manager.ready_to_update[idx],
)
)
metrics_server.update_runs(
runs_discovered=runs_discovered,
runs_max=multi_run_manager.max_runs,
run_stats=run_stats,
)
# Send heartbeat if configured
if heart is not None:
@@ -787,14 +716,14 @@ def train(config: TrainerConfig):
token_exporter.close()
# Write final checkpoint (only for single-run mode; multi-run checkpoints are managed by MultiCheckpointManager)
if config.max_concurrent_runs == 1 and ckpt_manager is not None:
# Write final checkpoint
if ckpt_manager is not None:
if not (config.ckpt and config.ckpt.weights_only):
logger.info("Writing final checkpoint")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
ckpt_manager.maybe_clean()
if config.max_concurrent_runs == 1 and weight_ckpt_manager is not None:
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()
-565
View File
@@ -1,565 +0,0 @@
import pickle
import time
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Callable, Optional
import tomli
import torch
import torch.distributed as dist
import torch.distributed.distributed_c10d as c10d
from prime_rl.configs.trainer import LoRAConfig
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_stable_ckpt_steps
if TYPE_CHECKING:
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.trainer.models.layers.lora import MultiLoRALinear
@dataclass
class Progress:
step: int = 1
total_tokens: int = 0
total_samples: int = 0
class MultiRunManager:
"""This class stores information about the runs in the system."""
# =========================================================================
# Initialization
# =========================================================================
def __init__(self, output_dir: Path, max_runs: int, device: torch.device = torch.device("cpu")):
self.output_dir = output_dir
self.max_runs = max_runs
self.logger = get_logger()
self.idx_2_id: dict[int, str] = {}
self.id_2_idx: dict[str, int] = {}
self.unused_idxs = {i for i in range(self.max_runs)}
self.progress: dict[int, Progress] = {}
self.config: dict[int, "OrchestratorConfig"] = {}
self.ready_to_update = [False] * max_runs
self._creation_hooks: list[Callable[[int, str], None]] = []
self._deletion_hooks: list[Callable[[int, str], None]] = []
self._discovered_hooks: list[Callable[[int, str, "OrchestratorConfig"], None]] = []
self._forgotten_hooks: list[Callable[[int, str], None]] = []
self._config_validation_hooks: list[Callable[["OrchestratorConfig"], tuple[bool, str]]] = []
# We use the store to keep other ranks in sync with master
self.store = c10d._get_default_store()
self.world = get_world()
# Track id_2_idx state at last synchronize_state to calculate diffs
self._last_synced_id_2_idx: dict[str, int] = {}
# Store modules with their FQN prefixes for parameter management
self._modules: list[tuple[str, "MultiLoRALinear"]] = []
# Optional conversion applied to adapter state dicts (e.g. PrimeRL -> HF key rename)
self._adapter_state_dict_converter: Callable[[dict[str, torch.Tensor]], dict[str, torch.Tensor]] | None = None
# Initialize lora globals on device so runs.* ARE the global tensors
from prime_rl.trainer.models.layers.lora import (
get_lora_num_tokens,
get_multilora_scaling,
set_lora_num_tokens,
set_multilora_scaling,
)
# We first set to None so we dont check the shape
# Might be better to not have the check at all but this will do for now
set_lora_num_tokens(None, reset_reference=True)
set_multilora_scaling(None, reset_reference=True)
set_lora_num_tokens(torch.zeros(max_runs, dtype=torch.int32, device=device), reset_reference=True)
self.lora_num_tokens = get_lora_num_tokens()
set_multilora_scaling(
torch.ones(max_runs, dtype=torch.bfloat16, device=device) * 1000_000.0, reset_reference=True
)
self.scaling_factors = get_multilora_scaling()
# =========================================================================
# Hook Registration
# =========================================================================
def register_creation_hook(self, hook: Callable[[int, str], None]) -> None:
"""Register a hook to be called when a new run is created.
Args:
hook: A callable that takes (idx: int, run_id: str) as arguments.
Called on all ranks when a new run is added to the system.
"""
self._creation_hooks.append(hook)
def register_deletion_hook(self, hook: Callable[[int, str], None]) -> None:
"""Register a hook to be called when a run is deleted.
Args:
hook: A callable that takes (idx: int, run_id: str) as arguments.
Called on all ranks when a run is removed from the system.
"""
self._deletion_hooks.append(hook)
def register_discovered_hook(self, hook: Callable[[int, str, "OrchestratorConfig"], None]) -> None:
"""Register a hook to be called when a new run is discovered (master only).
Args:
hook: A callable that takes (idx: int, run_id: str, config: OrchestratorConfig).
Called only on master rank in discover_runs() when a new run is found.
"""
if not self.world.is_master:
raise RuntimeError("register_discovered_hook() must only be called on the master rank")
self._discovered_hooks.append(hook)
def register_forgotten_hook(self, hook: Callable[[int, str], None]) -> None:
"""Register a hook to be called when a run is forgotten/removed (master only).
Args:
hook: A callable that takes (idx: int, run_id: str).
Called only on master rank in discover_runs() when a run is removed.
"""
if not self.world.is_master:
raise RuntimeError("register_forgotten_hook() must only be called on the master rank")
self._forgotten_hooks.append(hook)
def register_config_validation_hook(self, hook: Callable[["OrchestratorConfig"], tuple[bool, str]]) -> None:
"""Register a hook to validate orchestrator config when a run is created.
Args:
hook: A callable that takes (config: OrchestratorConfig) and returns
(is_valid: bool, error_message: str). Error message is used when invalid.
"""
if not self.world.is_master:
raise RuntimeError("register_config_validation_hook() must only be called on the master rank")
self._config_validation_hooks.append(hook)
# =========================================================================
# Module Registration and Parameter Management
# =========================================================================
def register_adapter_state_dict_converter(
self, converter: Callable[[dict[str, torch.Tensor]], dict[str, torch.Tensor]]
) -> None:
"""Register a converter applied in-place to adapter state dicts (e.g. model.convert_adapter_to_hf)."""
self._adapter_state_dict_converter = converter
def register_module(self, prefix: str, module: "MultiLoRALinear") -> None:
"""Register a MultiLoRALinear module with its FQN prefix.
This allows MultiRunManager to manage parameter access, reset, and state dict slicing
for multi-adapter LoRA modules.
Args:
prefix: The module's fully qualified name in the model
(e.g., "model.layers.0.self_attn.q_proj")
module: The MultiLoRALinear module to register
"""
self._modules.append((prefix, module))
def get_named_parameters_for_run(self, idx: int) -> list[tuple[str, torch.nn.Parameter]]:
"""Get named parameters for a specific run index.
Args:
idx: The run index to get parameters for
Returns:
List of (name, parameter) tuples for the specified run index
"""
params = []
for prefix, module in self._modules:
for name, param in module.named_parameters_for_adapter(idx):
params.append((f"{prefix}.{name}.weight", param))
return params
def get_state_dict_for_run(self, idx: int) -> dict[str, torch.Tensor]:
"""Get state dict for a specific run index.
Args:
idx: The run index to get state dict for
Returns:
State dict for the specified run index
"""
state_dict = {}
for prefix, module in self._modules:
# Check if module has a custom state_dict_for_adapter method (e.g., MoE modules)
# which returns vLLM-compatible per-expert format
if hasattr(module, "state_dict_for_adapter"):
for name, tensor in module.state_dict_for_adapter(idx).items():
state_dict[f"{prefix}.{name}"] = tensor.detach()
else:
# Default: use named_parameters_for_adapter
for name, param in module.named_parameters_for_adapter(idx):
state_dict[f"{prefix}.{name}.weight"] = param.detach()
if self._adapter_state_dict_converter is not None:
state_dict = self._adapter_state_dict_converter(state_dict)
return state_dict
def reset_run_parameters(self, idx: int) -> None:
"""Reset parameters for a specific run index.
Called when a new run is created to initialize fresh adapter weights.
Args:
idx: The run index to reset parameters for
"""
for _, module in self._modules:
module.reset_parameters(idx)
# =========================================================================
# Config Loading
# =========================================================================
def get_orchestrator_config(self, run_id: str) -> Optional["OrchestratorConfig"]:
"""Load and validate orchestrator config for a run.
Returns None if config doesn't exist, fails to parse, or fails validation.
Writes error to config dir for orchestrator to consume.
"""
config_path = self.output_dir / run_id / "control" / "orch.toml"
config_dir = config_path.parent
error_path = config_dir / "config_validation_error.txt"
if not config_path.exists():
self.logger.error(f"Run {run_id}: No orchestrator config found at {config_path}")
return None
try:
with open(config_path, "rb") as f:
config_dict = tomli.load(f)
from verifiers.v1.utils.loaders import skip_plugin_install
from prime_rl.configs.orchestrator import OrchestratorConfig
# The trainer only reads training-relevant fields (model, lora, seq_len, buffers,
# env names) and never runs the env, so skip resolving/installing taskset/harness
# plugins from the Environments Hub while parsing. Otherwise a private v1 hub env
# (`taskset.id = owner/name@version`) 404s here — the trainer has no Hub creds — and
# the run is silently skipped. The env server still installs the plugin at runtime.
token = skip_plugin_install.set(True)
try:
config = OrchestratorConfig(**config_dict)
finally:
skip_plugin_install.reset(token)
except Exception as e:
if error_path.parent.exists():
with open(error_path, "w") as f:
f.write(f"Error parsing orchestrator config:\n{str(e)}\n")
self.logger.error(f"Run {run_id}: Error parsing orchestrator config: {e}")
return None
# Run registered validation hooks
for hook in self._config_validation_hooks:
try:
is_valid, error_message = hook(config)
except Exception as e:
hook_name = getattr(hook, "__name__", type(hook).__name__)
is_valid = False
error_message = f"Validation hook {hook_name} crashed: {e}"
if not is_valid:
self.logger.error(f"Run {run_id}: {error_message}")
if error_path.parent.exists():
with open(error_path, "w") as f:
f.write(f"{error_message}\n")
return None
# Config is valid, remove any stale error file
if error_path.exists():
error_path.unlink()
return config
# =========================================================================
# Internal Run Data Helpers
# =========================================================================
def _create_run_data(self, new_run: str, new_id: int, config: "OrchestratorConfig") -> None:
"""Update data structures for a new run (no hooks or param reset)."""
self.id_2_idx[new_run] = new_id
self.unused_idxs.remove(new_id)
self.idx_2_id[new_id] = new_run
# Set progress based on resume_step config (match orchestrator behavior)
self.progress[new_id] = Progress()
# ``step_S`` means step S finished; resume continues at S+1.
if config.ckpt is None or config.ckpt.resume_step is None:
self.progress[new_id].step = 1
elif config.ckpt.resume_step == -1:
ckpt_dir = self.get_run_dir(new_id) / "checkpoints"
# In multi-run, the trainer writes STABLE after saving LoRA weights to the run's checkpoint dir.
# In single-run, only the orchestrator writes checkpoints here (trainer has its own dir), so no STABLE exists.
steps = get_stable_ckpt_steps(ckpt_dir) if self.max_runs > 1 else get_all_ckpt_steps(ckpt_dir)
self.progress[new_id].step = max(steps) + 1 if steps else 1
else:
self.progress[new_id].step = config.ckpt.resume_step + 1
# Store the parsed config
self.config[new_id] = config
def _delete_run_data(self, deleted_run: str, deleted_idx: int) -> None:
"""Update data structures for a deleted run (internal cleanup only, no hooks)."""
del self.progress[deleted_idx]
if deleted_idx in self.config:
del self.config[deleted_idx]
# A big value might help make it error loudly
self.scaling_factors[deleted_idx] = 1000_000.0
# Process mappings
self.unused_idxs.add(deleted_idx)
del self.idx_2_id[deleted_idx]
del self.id_2_idx[deleted_run]
def _create_run_hooks(self, new_id: int, new_run: str) -> None:
"""Reset parameters and call creation hooks for a run."""
self.reset_run_parameters(new_id)
for hook in self._creation_hooks:
hook(new_id, new_run)
def _delete_run_hooks(self, deleted_idx: int, deleted_run: str) -> None:
"""Call deletion hooks for a run."""
for hook in self._deletion_hooks:
hook(deleted_idx, deleted_run)
# =========================================================================
# Run Discovery, Synchronization, and Eviction
# =========================================================================
def evict_run(self, idx: int, reason: str) -> None:
"""Evict a run by writing the reason to a file for the orchestrator to read.
The orchestrator will error and surface this reason. The run will be
ignored by future discover_runs() calls.
Note that the run is not deleted on master until the next discover_runs() call.
And not deleted on other ranks until the next synchronize_state() call.
Args:
idx: The run index to evict
reason: The reason for eviction (will be shown to user)
"""
if not self.world.is_master:
raise RuntimeError("evict_run() must only be called on the master rank")
if idx not in self.idx_2_id:
self.logger.warning(f"Run index {idx} not found, cannot evict")
return
run_id = self.idx_2_id[idx]
run_dir = self.output_dir / run_id
config_dir = run_dir / "control"
config_dir.mkdir(parents=True, exist_ok=True)
evicted_path = config_dir / "evicted.txt"
with open(evicted_path, "w") as f:
f.write(reason)
self.logger.warning(f"Evicted run {run_id} (idx={idx}): {reason}")
def discover_runs(self) -> None:
"""Detect run changes and update data structures (master only). Must be followed by synchronize_state().
Scans for new/deleted runs, calls forgotten/discovered hooks (master only),
and updates internal data structures. Hooks and parameter resets for all ranks
are deferred to synchronize_state().
"""
if not self.world.is_master:
raise RuntimeError("discover_runs() must only be called on the master rank")
run_ids = {run_path.stem for run_path in self.output_dir.glob("run_*")}
# Filter out evicted runs
evicted_runs = {run_id for run_id in run_ids if (self.output_dir / run_id / "control" / "evicted.txt").exists()}
run_ids = run_ids - evicted_runs
deleted_runs = self.id_2_idx.keys() - run_ids
new_runs = run_ids - self.id_2_idx.keys()
for deleted_run in deleted_runs:
deleted_idx = self.id_2_idx[deleted_run]
# Call forgotten hooks (master only) before cleanup
for hook in self._forgotten_hooks:
hook(deleted_idx, deleted_run)
self._delete_run_data(deleted_run, deleted_idx)
for new_run in new_runs:
try:
new_id = next(iter(self.unused_idxs))
config = self.get_orchestrator_config(new_run)
if config is None:
continue
self._create_run_data(new_run, new_id, config)
# Call discovered hooks (master only) after data setup
for hook in self._discovered_hooks:
hook(new_id, new_run, config)
except StopIteration:
continue
def synchronize_state(self) -> None:
"""Sync run state across ranks and execute hooks.
Master calculates what changed since last sync using _last_synced_id_2_idx.
This matches what non-master ranks will calculate as new/deleted runs.
All ranks then execute hooks and parameter resets together.
"""
if self.world.is_master:
# Include configs for new runs so non-master ranks have them
new_runs = self.id_2_idx.keys() - self._last_synced_id_2_idx.keys()
new_configs = {new_run: self.config[self.id_2_idx[new_run]] for new_run in new_runs}
sync_data = {
"id_2_idx": self.id_2_idx,
"ready_to_update": self.ready_to_update,
"scaling_factors": self.scaling_factors.cpu(),
"new_configs": new_configs,
"progress": self.progress,
}
self.store.set("runs", pickle.dumps(sync_data))
dist.barrier()
if self.world.is_master:
# Calculate changes since last sync (this is what other ranks will see)
new_runs = self.id_2_idx.keys() - self._last_synced_id_2_idx.keys()
deleted_runs = self._last_synced_id_2_idx.keys() - self.id_2_idx.keys()
# Capture deleted indices from last synced state (already removed from id_2_idx)
deleted_run_idxs = {run: self._last_synced_id_2_idx[run] for run in deleted_runs}
else:
sync_data: dict = pickle.loads(self.store.get("runs"))
new_id_2_idx: dict[str, int] = sync_data["id_2_idx"]
self.ready_to_update = sync_data["ready_to_update"]
self.scaling_factors.copy_(sync_data["scaling_factors"])
new_configs: dict[str, "OrchestratorConfig"] = sync_data["new_configs"]
master_progress: dict[int, Progress] = sync_data["progress"]
new_runs = new_id_2_idx.keys() - self.id_2_idx.keys()
deleted_runs = self.id_2_idx.keys() - new_id_2_idx.keys()
# Capture deleted indices before removing from id_2_idx
deleted_run_idxs = {run: self.id_2_idx[run] for run in deleted_runs}
# Other ranks catch up with master's data state
for deleted_run in deleted_runs:
deleted_idx = deleted_run_idxs[deleted_run]
self._delete_run_data(deleted_run, deleted_idx)
for new_run in new_runs:
new_id = new_id_2_idx[new_run]
self._create_run_data(new_run, new_id, new_configs[new_run])
# Sync progress from master
self.progress = master_progress
# Call deletion hooks on all ranks
for deleted_run in deleted_runs:
deleted_idx = deleted_run_idxs[deleted_run]
self._delete_run_hooks(deleted_idx, deleted_run)
for new_run in new_runs:
new_id = self.id_2_idx[new_run]
self._create_run_hooks(new_id, new_run)
# Update last synced state for master
if self.world.is_master:
self._last_synced_id_2_idx = self.id_2_idx.copy()
# =========================================================================
# Properties and Accessors
# =========================================================================
def wait_for_run(self, idx: int = 0, poll_interval: float = 1.0) -> None:
"""Block until run ``idx`` is registered. Master discovers from disk; all ranks synchronize.
Runs are otherwise only discovered during batch collection (``packer.discover_runs``), so
callers that need a run before the first batch (optimizer setup, first-step weight sync)
use this to populate ``idx_2_id``/``used_idxs``.
"""
while idx not in self.idx_2_id:
if self.world.is_master:
self.discover_runs()
self.synchronize_state()
self.logger.info(f"Waiting for run {idx} to be created ({self.id_2_idx=})")
time.sleep(poll_interval)
@property
def used_idxs(self):
return sorted(self.idx_2_id.keys())
@property
def ready_to_update_idxs(self):
return [idx for idx, ready in enumerate(self.ready_to_update) if ready]
def run_dirs(self) -> list[Path]:
return [self.output_dir / run_id for run_id in self.id_2_idx.keys()]
def get_run_dir(self, idx: int) -> Path:
return self.output_dir / self.idx_2_id[idx]
def __repr__(self):
return f"MultiRunManager(max={self.max_runs})[{self.idx_2_id.keys()}]"
# Singleton instance of MultiRunManager
_MULTI_RUN_MANAGER: MultiRunManager | None = None
def get_multi_run_manager() -> MultiRunManager:
"""Returns the MultiRunManager singleton. Must be initialized first via setup_multi_run_manager()."""
global _MULTI_RUN_MANAGER
if _MULTI_RUN_MANAGER is None:
raise RuntimeError("MultiRunManager not initialized. Please call `setup_multi_run_manager` first.")
return _MULTI_RUN_MANAGER
def setup_multi_run_manager(
output_dir: Path, max_runs: int, device: torch.device, lora_config: LoRAConfig | None = None
) -> MultiRunManager:
"""Initialize the MultiRunManager singleton.
Args:
output_dir: Directory containing run outputs
max_runs: Maximum number of concurrent runs
device: Device for LoRA tensors
lora_config: Optional trainer LoRA config. If provided, registers validation
and scaling hooks for LoRA rank and alpha.
Returns:
The initialized MultiRunManager instance.
"""
global _MULTI_RUN_MANAGER
_MULTI_RUN_MANAGER = MultiRunManager(output_dir, max_runs, device)
# Register validation and scaling hooks for LoRA
if lora_config is not None and _MULTI_RUN_MANAGER.world.is_master:
trainer_lora = lora_config
def validate_lora_rank(orch_config: "OrchestratorConfig") -> tuple[bool, str]:
if orch_config.model.lora is None:
return False, "orchestrator.model.lora is required when trainer is configured with LoRA"
# Default to trainer's rank/alpha if not specified
if orch_config.model.lora.rank is None:
orch_config.model.lora.rank = trainer_lora.rank
if orch_config.model.lora.alpha is None:
orch_config.model.lora.alpha = trainer_lora.alpha
if orch_config.model.lora.rank > trainer_lora.rank:
return (
False,
f"orchestrator.model.lora.rank ({orch_config.model.lora.rank}) exceeds trainer max rank ({trainer_lora.rank})",
)
return True, ""
def on_run_discovered(idx: int, run_id: str, orch_config: "OrchestratorConfig") -> None:
_MULTI_RUN_MANAGER.scaling_factors[idx] = orch_config.model.lora.alpha / orch_config.model.lora.rank
_MULTI_RUN_MANAGER.register_config_validation_hook(validate_lora_rank)
_MULTI_RUN_MANAGER.register_discovered_hook(on_run_discovered)
return _MULTI_RUN_MANAGER
+1 -69
View File
@@ -4,9 +4,7 @@ from torch.optim import Optimizer
from torch.optim.lr_scheduler import ConstantLR, CosineAnnealingLR, LinearLR, LRScheduler, SequentialLR
from prime_rl.configs.trainer import SchedulerConfig
from prime_rl.trainer.optim import CPUOffloadOptimizer, MultiLoRAOptimizer
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.utils.logger import get_logger
from prime_rl.trainer.optim import CPUOffloadOptimizer
def _get_base_optimizer(optimizer: Optimizer | CPUOffloadOptimizer) -> Optimizer:
@@ -120,69 +118,3 @@ def setup_scheduler(
)
case _:
raise ValueError(f"Invalid scheduler type: {scheduler_config.type}")
class MultiLoRAScheduler:
"""Manages multiple schedulers, one per run.
Each run has its own independent scheduler that is created when
the run's optimizer is created via the optimizer creation hook.
"""
def __init__(
self,
scheduler_config: SchedulerConfig,
max_steps: int | None,
):
self.scheduler_config = scheduler_config
self.max_steps = max_steps
self.multi_run_manager = get_multi_run_manager()
self.logger = get_logger()
self.schedulers: list[LRScheduler | None] = [None] * self.multi_run_manager.max_runs
def scheduler_creation_hook(self, optimizer: Optimizer, idx: int) -> None:
"""Create a scheduler for a newly created optimizer.
This should be called after an optimizer is created for a run.
"""
lr = self.multi_run_manager.config[idx].optim.lr
self.schedulers[idx] = setup_scheduler(
optimizer,
self.scheduler_config,
self.max_steps,
lr,
)
def step(self) -> None:
"""Step all active schedulers."""
for idx in self.multi_run_manager.ready_to_update_idxs:
self.schedulers[idx].step()
def get_last_lr(self, idx: int) -> list[float]:
"""Get the last learning rate for a specific run."""
if self.schedulers[idx] is not None:
return self.schedulers[idx].get_last_lr()
return []
def state_dict(self) -> dict:
return {
"schedulers": [scheduler.state_dict() if scheduler is not None else None for scheduler in self.schedulers],
}
def load_state_dict(self, state_dict: dict) -> None:
for idx, scheduler_state in enumerate(state_dict["schedulers"]):
if scheduler_state is not None and self.schedulers[idx] is not None:
self.schedulers[idx].load_state_dict(scheduler_state)
def setup_multi_scheduler(
optimizer: MultiLoRAOptimizer,
scheduler_config: SchedulerConfig,
max_steps: int | None,
) -> MultiLoRAScheduler:
"""Create a MultiLoRAScheduler for managing per-run schedulers."""
scheduler = MultiLoRAScheduler(scheduler_config, max_steps)
# Register callback at index 0 so schedulers are created before other callbacks
optimizer.register_post_creation_callback(scheduler.scheduler_creation_hook, index=0)
return scheduler
+3 -8
View File
@@ -15,11 +15,11 @@ 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 setup_ckpt_managers
from prime_rl.trainer.ckpt import Progress, setup_ckpt_managers
from prime_rl.utils.pathing import resolve_latest_ckpt_step
from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.cp import setup_cp_params, shard_for_cp
from prime_rl.trainer.runs import Progress, get_multi_run_manager, setup_multi_run_manager
from prime_rl.trainer.lora import get_lora_state
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
from prime_rl.utils.logger import format_time, setup_logger
from prime_rl.trainer.optim import setup_optimizer
@@ -92,9 +92,6 @@ def train(config: SFTConfig):
# (e.g. matmul_precision = "highest") on ROCm.
torch.set_float32_matmul_precision(config.matmul_precision)
if config.model.lora is not None:
setup_multi_run_manager(config.output_dir, 1, torch.device("cuda", world.local_rank), config.model.lora)
# Resolve ep="auto" to a concrete integer before creating parallel dims
resolve_ep(config.model)
@@ -157,9 +154,7 @@ def train(config: SFTConfig):
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
if config.model.lora is not None:
multi_run_manager = get_multi_run_manager()
multi_run_manager.reset_run_parameters(0)
multi_run_manager.scaling_factors[0] = config.model.lora.alpha / config.model.lora.rank
get_lora_state().reset_adapter_parameters()
logger.info(f"Initializing tokenizer ({config.tokenizer})")
tokenizer = setup_tokenizer(config.tokenizer)
+1 -238
View File
@@ -1,12 +1,10 @@
import gc
import heapq
import json
import pickle
import shutil
import time
from collections import defaultdict
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass, field
from collections.abc import Iterable
from datetime import timedelta
from pathlib import Path
from typing import Any
@@ -30,241 +28,6 @@ from prime_rl.utils.utils import format_num, format_time, get_step_path
DEFAULT_TIMEOUT = timedelta(seconds=600)
def _text_config(model_config: Any) -> Any:
"""Unwrap a multimodal model's text config, else return the config unchanged."""
return getattr(model_config, "text_config", model_config)
def _is_mla(config: Any) -> bool:
return bool(getattr(config, "multi_latent_attention", False) or hasattr(config, "q_lora_rank"))
def _kv_channels(config: Any) -> int:
return getattr(config, "kv_channels", getattr(config, "head_dim", config.hidden_size // config.num_attention_heads))
def _qkv_projection_flops_per_token(config: Any) -> int:
"""Linear-in-seqlen FLOPs of the Q/K/V projections (per token)."""
hidden_size = config.hidden_size
num_attention_heads = config.num_attention_heads
kv_channels = _kv_channels(config)
is_mla = _is_mla(config)
qk_head_dim = getattr(config, "qk_head_dim", 0)
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
if is_mla and getattr(config, "q_lora_rank", None) is not None:
q_flops = 2 * config.q_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim))
else:
q_head_dim = (qk_head_dim + qk_pos_emb_head_dim) if is_mla else kv_channels
q_flops = 2 * hidden_size * num_attention_heads * q_head_dim
if is_mla and getattr(config, "kv_lora_rank", None) is not None:
v_head_dim = getattr(config, "v_head_dim", 0)
kv_flops = 2 * (
config.kv_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + v_head_dim))
+ hidden_size * qk_pos_emb_head_dim
)
else:
num_query_groups = getattr(
config, "num_query_groups", getattr(config, "num_key_value_heads", num_attention_heads)
)
kv_flops = 4 * hidden_size * num_query_groups * kv_channels
return q_flops + kv_flops
def _attention_flops_per_token_squared(config: Any) -> int:
"""Quadratic-in-seqlen FLOPs of the attention scores and values (per token^2)."""
num_attention_heads = config.num_attention_heads
kv_channels = _kv_channels(config)
if _is_mla(config):
qk_head_dim = getattr(config, "qk_head_dim", 0)
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
v_head_dim = getattr(config, "v_head_dim", kv_channels)
return num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim) + num_attention_heads * v_head_dim
return 2 * num_attention_heads * kv_channels
def _ffn_flops_per_token(hidden_size: int, ffn_hidden_size: int) -> int:
return 6 * hidden_size * ffn_hidden_size
def _dense_ffn_hidden_size(config: Any) -> int:
return getattr(
config, "ffn_hidden_size", getattr(config, "intermediate_size", getattr(config, "moe_intermediate_size", 0))
)
def _moe_ffn_hidden_size(config: Any) -> int:
"""Effective FFN width of an MoE layer: routed experts (topk) plus shared experts."""
dense_ffn = _dense_ffn_hidden_size(config)
routed_topk = getattr(config, "moe_router_topk", getattr(config, "num_experts_per_tok", 1))
moe_ffn = getattr(config, "moe_ffn_hidden_size", getattr(config, "moe_intermediate_size", dense_ffn))
return moe_ffn * routed_topk + (getattr(config, "moe_shared_expert_intermediate_size", None) or 0)
def _count_dense_and_moe_layers(config: Any) -> tuple[int, int]:
"""Split the model's layers into (dense, moe) counts."""
num_experts = getattr(config, "num_experts", getattr(config, "n_routed_experts", None))
if num_experts is None:
return config.num_hidden_layers, 0
moe_layer_freq = getattr(config, "moe_layer_freq", None)
if isinstance(moe_layer_freq, list):
num_dense = sum(1 for freq in moe_layer_freq if freq == 0)
num_moe = sum(1 for freq in moe_layer_freq if freq > 0)
elif isinstance(moe_layer_freq, int):
num_dense = sum(1 for i in range(config.num_hidden_layers) if i % moe_layer_freq != 0)
num_moe = config.num_hidden_layers - num_dense
elif getattr(config, "first_k_dense_replace", None) is not None:
num_dense = config.first_k_dense_replace
num_moe = config.num_hidden_layers - num_dense
else:
num_dense = 0
num_moe = config.num_hidden_layers
return num_dense, num_moe
def _packing_cost_coeffs(config: Any) -> tuple[int, int]:
"""Return the (linear, quadratic) coefficients of the per-sequence forward FLOPs."""
hidden_size = config.hidden_size
num_dense_layers, num_moe_layers = _count_dense_and_moe_layers(config)
qkv_per_token = _qkv_projection_flops_per_token(config)
attn_per_token_squared = _attention_flops_per_token_squared(config)
def layer_linear(ffn_hidden_size: int) -> int:
return qkv_per_token + 2 * hidden_size * hidden_size + _ffn_flops_per_token(hidden_size, ffn_hidden_size)
linear = (
num_dense_layers * layer_linear(_dense_ffn_hidden_size(config))
+ num_moe_layers * layer_linear(_moe_ffn_hidden_size(config))
+ 2 * hidden_size * config.vocab_size
)
quadratic = (num_dense_layers + num_moe_layers) * attn_per_token_squared
return linear, quadratic
def build_bin_cost(model_config: Any | None) -> Callable[[Sequence[int]], int]:
"""Build a closure scoring a packed bin by estimated forward compute.
With ``model_config=None`` the linear/quadratic coefficients are ``(1, 0)``, so
the cost reduces to the token count and balancing falls back to sequence length.
"""
if model_config is None:
linear, quadratic = 1, 0
else:
linear, quadratic = _packing_cost_coeffs(_text_config(model_config))
def bin_cost(seqlens: Sequence[int]) -> int:
return linear * sum(seqlens) + quadratic * sum(n * n for n in seqlens)
return bin_cost
@dataclass
class _WeightedSet:
total: int = 0
items: list[int] = field(default_factory=list)
def add(self, idx: int, weight: int) -> None:
self.items.append(idx)
self.total += weight
def merge(self, other: "_WeightedSet") -> None:
self.items.extend(other.items)
self.total += other.total
def __lt__(self, other: "_WeightedSet") -> bool:
if self.total != other.total:
return self.total < other.total
return self.items < other.items
class _KKState:
def __init__(self, items: list[tuple[int, int]], k: int):
self.sets = [_WeightedSet() for _ in range(k)]
for set_idx, (idx, weight) in enumerate(items):
self.sets[set_idx].add(idx, weight)
self.sets.sort(reverse=True)
@property
def spread(self) -> int:
return self.sets[0].total - self.sets[-1].total
def merge(self, other: "_KKState") -> None:
k = len(self.sets)
for i in range(k):
self.sets[i].merge(other.sets[k - 1 - i])
self.sets.sort(reverse=True)
def partitions(self) -> list[list[int]]:
return [sorted(weighted_set.items) for weighted_set in self.sets]
def __lt__(self, other: "_KKState") -> bool:
if self.spread != other.spread:
return self.spread > other.spread
return self.sets[0] > other.sets[0]
def _karmarkar_karp(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
assert len(weights) >= num_partitions
assert len(weights) % num_partitions == 0
weighted_indices = sorted((weight, idx) for idx, weight in enumerate(weights))
states: list[_KKState] = []
for offset in range(0, len(weighted_indices), num_partitions):
items = [(idx, weight) for weight, idx in weighted_indices[offset : offset + num_partitions]]
heapq.heappush(states, _KKState(items, num_partitions))
while len(states) > 1:
state = heapq.heappop(states)
state.merge(heapq.heappop(states))
heapq.heappush(states, state)
return states[0].partitions()
def _partition_loads(weights: Sequence[int], partitions: list[list[int]]) -> list[int]:
return [sum(weights[i] for i in partition) for partition in partitions]
def _refine_by_swapping(weights: Sequence[int], partitions: list[list[int]]) -> list[list[int]]:
partitions = [list(partition) for partition in partitions]
loads = _partition_loads(weights, partitions)
while True:
best_swap = None
best_score = (max(loads), max(loads) - min(loads))
for left_rank in range(len(partitions)):
for right_rank in range(left_rank + 1, len(partitions)):
for left_pos, left_idx in enumerate(partitions[left_rank]):
for right_pos, right_idx in enumerate(partitions[right_rank]):
new_left = loads[left_rank] - weights[left_idx] + weights[right_idx]
new_right = loads[right_rank] - weights[right_idx] + weights[left_idx]
new_loads = list(loads)
new_loads[left_rank] = new_left
new_loads[right_rank] = new_right
score = (max(new_loads), max(new_loads) - min(new_loads))
if score < best_score:
best_score = score
best_swap = (left_rank, right_rank, left_pos, right_pos, new_loads)
if best_swap is None:
return partitions
left_rank, right_rank, left_pos, right_pos, loads = best_swap
partitions[left_rank][left_pos], partitions[right_rank][right_pos] = (
partitions[right_rank][right_pos],
partitions[left_rank][left_pos],
)
def balanced_partition(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
"""Partition item indices into ``num_partitions`` groups of near-equal total weight.
Requires ``len(weights)`` to be a positive multiple of ``num_partitions``.
"""
partitions = _karmarkar_karp(weights, num_partitions)
return _refine_by_swapping(weights, partitions)
class GarbageCollection:
"""Controls Python garbage collection to avoid stragglers in distributed training.
+3 -29
View File
@@ -1,45 +1,22 @@
from pathlib import Path
from prime_rl.configs.shared import TransportConfig
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender, TrainingBatchReceiver, TrainingBatchSender
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transport.filesystem import (
FileSystemMicroBatchReceiver,
FileSystemMicroBatchSender,
FileSystemTrainingBatchReceiver,
FileSystemTrainingBatchSender,
)
from prime_rl.transport.types import (
MicroBatch,
RoutedExperts,
TrainingBatch,
TrainingSample,
)
from prime_rl.transport.zmq import (
ZMQMicroBatchReceiver,
ZMQMicroBatchSender,
ZMQTrainingBatchReceiver,
ZMQTrainingBatchSender,
)
def setup_training_batch_sender(output_dir: Path, transport: TransportConfig) -> TrainingBatchSender:
if transport.type == "filesystem":
return FileSystemTrainingBatchSender(output_dir)
elif transport.type == "zmq":
return ZMQTrainingBatchSender(output_dir, transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
def setup_training_batch_receiver(transport: TransportConfig) -> TrainingBatchReceiver:
if transport.type == "filesystem":
return FileSystemTrainingBatchReceiver()
elif transport.type == "zmq":
return ZMQTrainingBatchReceiver(transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
def setup_micro_batch_sender(
output_dir: Path, data_world_size: int, current_step: int, transport: TransportConfig
) -> MicroBatchSender:
@@ -63,18 +40,15 @@ def setup_micro_batch_receiver(
__all__ = [
"FileSystemTrainingBatchSender",
"FileSystemTrainingBatchReceiver",
"FileSystemMicroBatchSender",
"FileSystemMicroBatchReceiver",
"ZMQMicroBatchSender",
"ZMQMicroBatchReceiver",
"MicroBatchReceiver",
"MicroBatchSender",
"TrainingSample",
"TrainingBatch",
"MicroBatch",
"RoutedExperts",
"setup_training_batch_sender",
"setup_training_batch_receiver",
"setup_micro_batch_sender",
"setup_micro_batch_receiver",
]
+5 -60
View File
@@ -3,67 +3,12 @@ from pathlib import Path
import msgspec
from prime_rl.transport.types import MicroBatch, TrainingBatch
from prime_rl.transport.types import MicroBatch
from prime_rl.utils.logger import get_logger
class TrainingBatchSender(ABC):
"""Base class for sending training examples from orchestrator to trainer."""
def __init__(self, output_dir: Path):
self.logger = get_logger()
self.encoder = msgspec.msgpack.Encoder()
self.output_dir = output_dir
@abstractmethod
async def send(self, batch: TrainingBatch) -> None:
"""Send a batch of training examples to the trainer(s).
Args:
batch: The batch of training examples with metadata.
"""
pass
def close(self) -> None:
"""Clean up any resources. Override if needed."""
pass
class TrainingBatchReceiver(ABC):
"""Base class for receiving training examples from orchestrator."""
def __init__(self) -> None:
self.logger = get_logger()
self.decoder = msgspec.msgpack.Decoder(type=TrainingBatch)
@abstractmethod
def can_receive(self) -> bool:
"""Check if any batch is available."""
pass
@abstractmethod
def receive(self) -> list[TrainingBatch]:
"""Receive available batches from all runs.
Returns:
List of training batches with idx field set.
"""
pass
def reset_run(self, idx: int) -> None:
"""Reset state for a run index. Called when a run is deleted and replaced.
Override in subclasses that maintain per-run state.
"""
pass
def close(self) -> None:
"""Clean up any resources. Override if needed."""
pass
class MicroBatchSender(ABC):
"""Base class for sending micro batches to the train workers."""
"""Base class for sending micro batches from the orchestrator to the train workers."""
def __init__(self, output_dir: Path, data_world_size: int):
self.logger = get_logger()
@@ -72,7 +17,7 @@ class MicroBatchSender(ABC):
self.data_world_size = data_world_size
@abstractmethod
def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
"""Send grid of micro batches to the trainers."""
pass
@@ -82,7 +27,7 @@ class MicroBatchSender(ABC):
class MicroBatchReceiver(ABC):
"""Base class for receiving micro batches from the packer."""
"""Base class for receiving micro batches from the orchestrator."""
def __init__(self, output_dir: Path, data_rank: int):
self.logger = get_logger()
@@ -102,7 +47,7 @@ class MicroBatchReceiver(ABC):
@abstractmethod
def receive(self) -> list[MicroBatch]:
"""Receive a micro batch from the trainer."""
"""Receive a micro batch from the orchestrator."""
pass
def close(self) -> None:
+8 -117
View File
@@ -1,121 +1,10 @@
import asyncio
from pathlib import Path
from time import time
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender, TrainingBatchReceiver, TrainingBatchSender
from prime_rl.transport.types import MicroBatch, TrainingBatch
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transport.types import MicroBatch
from prime_rl.utils.pathing import get_rollout_dir, get_step_path, sync_wait_for_path
BATCH_FILE_TMP_NAME = "train_rollouts.bin.tmp"
BATCH_FILE_NAME = "train_rollouts.bin"
LOG_FREQ_SECONDS = 10
class FileSystemTrainingBatchSender(TrainingBatchSender):
"""Filesystem-based training batch sender that writes batches to disk."""
def __init__(self, output_dir: Path):
super().__init__(output_dir)
self.rollout_dir = get_rollout_dir(output_dir)
async def send(self, batch: TrainingBatch) -> None:
"""Send a batch by writing it to disk. Encode + write run in a worker
thread so the orch event loop stays responsive during step transitions."""
step_path = get_step_path(self.rollout_dir, batch.step)
step_path.mkdir(parents=True, exist_ok=True)
await asyncio.to_thread(self._encode_and_write, batch, step_path)
def _encode_and_write(self, batch: TrainingBatch, step_path: Path) -> None:
buffer = self.encoder.encode(batch)
tmp_path = step_path / BATCH_FILE_TMP_NAME
with open(tmp_path, "wb") as f:
f.write(buffer)
tmp_path.rename(step_path / BATCH_FILE_NAME)
class FileSystemTrainingBatchReceiver(TrainingBatchReceiver):
"""Filesystem-based training batch receiver that reads batches from multiple run directories."""
def __init__(self) -> None:
super().__init__()
self.multi_run_manager = get_multi_run_manager()
self._last_logged_paths: list[Path] | None = None
self._last_logged_time = time()
self._waiting_since: float | None = None
# Track received steps per run independently of multi_run_manager.progress[idx].step
# This prevents duplicate reads when trainer step != orchestrator step
self._received_steps: dict[int, int] = {}
def _get_received_step(self, idx: int) -> int:
"""Get the next step to receive for a run, initializing from progress if needed."""
if idx not in self._received_steps:
# Initialize from multi_run_manager.progress on first access (for checkpoint resume)
self._received_steps[idx] = self.multi_run_manager.progress[idx].step
return self._received_steps[idx]
def _get_batch_path(self, idx: int) -> Path:
"""Get the batch file path for a specific run at its next step to receive."""
run_dir = self.multi_run_manager.get_run_dir(idx)
rollout_dir = get_rollout_dir(run_dir)
step = self._get_received_step(idx)
return get_step_path(rollout_dir, step) / BATCH_FILE_NAME
def can_receive(self) -> bool:
"""Check if any run has a batch file available."""
for idx in self.multi_run_manager.used_idxs:
if not self.multi_run_manager.ready_to_update[idx] and self._get_batch_path(idx).exists():
return True
return False
def receive(self) -> list[TrainingBatch]:
"""Read and return all available batches from all runs."""
batches: list[TrainingBatch] = []
now = time()
# Track how long we've been waiting for any new batch to appear.
if self.can_receive():
self._waiting_since = None
else:
self._waiting_since = self._waiting_since or now
current_paths = [self._get_batch_path(idx) for idx in self.multi_run_manager.used_idxs]
if current_paths != self._last_logged_paths or now - self._last_logged_time > LOG_FREQ_SECONDS:
if len(current_paths) == 0:
self.logger.debug(
"Did you set the output dir of the orchestrator to a run_* subdirectory of the trainer output dir?"
)
waiting_suffix = ""
if self._waiting_since is not None:
waiting_suffix = f" (waiting {now - self._waiting_since:.1f}s)"
self.logger.debug(f"Looking for batches in {current_paths}{waiting_suffix}")
self._last_logged_paths = current_paths
self._last_logged_time = now
for idx in self.multi_run_manager.used_idxs:
if self.multi_run_manager.ready_to_update[idx]:
continue
batch_path = self._get_batch_path(idx)
if batch_path.exists():
try:
with open(batch_path, "rb") as f:
batch: TrainingBatch = self.decoder.decode(f.read())
batch.run_idx = idx
batches.append(batch)
# Increment received step to avoid reading the same file again
self._received_steps[idx] = self._get_received_step(idx) + 1
except Exception as e:
self.logger.error(f"Error loading rollouts for run {idx}: {e}")
return batches
def reset_run(self, idx: int) -> None:
"""Reset received step tracking for a run index.
Called when a run is deleted and a new run takes its place.
The next access to _get_received_step will re-initialize from multi_run_manager.progress.
"""
if idx in self._received_steps:
del self._received_steps[idx]
class FileSystemMicroBatchSender(MicroBatchSender):
"""Filesystem-based micro batch sender that writes micro batches to disk."""
@@ -125,23 +14,25 @@ class FileSystemMicroBatchSender(MicroBatchSender):
self.rollout_dir = get_rollout_dir(output_dir)
self.current_step = current_step
def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
"""Send grid of micro batches to the trainers."""
# Validation
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
"""Send grid of micro batches to the trainers. Encode + write run in a worker
thread so the orchestrator event loop stays responsive during step transitions."""
assert len(micro_batch_grid) == self.data_world_size, "Number of micro batch lists must match data world size"
for micro_batch_list in micro_batch_grid:
assert len(micro_batch_list) == len(micro_batch_grid[0]), "All micro batch lists must have the same length"
step_path = get_step_path(self.rollout_dir, self.current_step)
step_path.mkdir(parents=True, exist_ok=True)
await asyncio.to_thread(self._encode_and_write, micro_batch_grid, step_path)
self.current_step += 1
def _encode_and_write(self, micro_batch_grid: list[list[MicroBatch]], step_path: Path) -> None:
for data_rank in range(self.data_world_size):
buffer = self.encoder.encode(micro_batch_grid[data_rank])
tmp_path = step_path / f"rank_{data_rank}.bin.tmp"
with open(tmp_path, "wb") as f:
f.write(buffer)
tmp_path.rename(step_path / f"rank_{data_rank}.bin")
self.current_step += 1
class FileSystemMicroBatchReceiver(MicroBatchReceiver):
+3 -15
View File
@@ -18,7 +18,8 @@ class RoutedExperts(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tru
dtype: str
# Orchestrator -> Packer
# Produced by the orchestrator's train sink; consumed in-process by
# ``prepare_batch``, which packs samples into per-rank ``MicroBatch``es.
class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
"""A single training example — one branch of a rollout as a flat token sequence.
@@ -69,15 +70,7 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
advantages: list[float] | None = None
class TrainingBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
"""A batch of training examples with metadata for transport."""
examples: list[TrainingSample]
step: int
run_idx: int | None = None
# Packer -> Trainer
# Orchestrator -> Trainer
class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
"""A micro batch of data for training."""
@@ -91,7 +84,6 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
env_names: list[str]
seq_lens: list[int]
ref_logprobs: list[float] | None = None
lora_num_tokens: list[int] | None = None
routed_experts: RoutedExperts | None = None
# See TrainingSample.mm_kwargs.
@@ -105,7 +97,3 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
rl_weights: list[float] | None = None
ce_weights: list[float] | None = None
ref_kl_weights: list[float] | None = None
# Packer-derived metadata used for run-local token exports.
run_id: str | None = None
run_step: int | None = None
+30 -186
View File
@@ -1,206 +1,50 @@
from pathlib import Path
from time import time
import zmq
import zmq.asyncio
from prime_rl.configs.shared import ZMQTransportConfig
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender, TrainingBatchReceiver, TrainingBatchSender
from prime_rl.transport.types import MicroBatch, TrainingBatch
LOG_FREQ_SECONDS = 10
class ZMQTrainingBatchSender(TrainingBatchSender):
"""
One PUSH socket; each message is multipart: [sender_id, payload]
sender_id = output_dir.stem
"""
def __init__(self, output_dir: Path, transport: ZMQTransportConfig):
super().__init__(output_dir)
# Async context so ``send`` yields instead of blocking the orchestrator
# event loop when the trainer is slow and we hit SNDHWM.
self.context = zmq.asyncio.Context.instance()
self.socket: zmq.asyncio.Socket = self.context.socket(zmq.PUSH)
self.socket.setsockopt(zmq.SNDHWM, transport.hwm)
self.socket.connect(f"tcp://{transport.host}:{transport.port}")
self.sender_id = output_dir.stem.encode("utf-8")
self.logger.info(
f"ZMQ training batch sender initialized: output_dir={output_dir} "
f"endpoint=tcp://{transport.host}:{transport.port} hwm={transport.hwm}"
)
async def send(self, batch: TrainingBatch) -> None:
payload = self.encoder.encode(batch)
self.logger.debug(f"Sending batch {batch.step} to {self.sender_id}")
await self.socket.send_multipart([self.sender_id, payload], copy=False)
def close(self) -> None:
try:
self.socket.close(linger=0)
finally:
self.logger.info("ZMQ training batch sender closed")
class ZMQTrainingBatchReceiver(TrainingBatchReceiver):
"""
One PULL socket bound to the shared endpoint.
Receives multipart [sender_id, payload].
Semantics vs filesystem version:
- For each run idx, we return at most ONE batch per receive() call.
- We always return the oldest pending batch (by step) for that idx.
- Any newer batches received are buffered for future receive() calls.
"""
def __init__(self, transport: ZMQTransportConfig):
super().__init__()
self.multi_run_manager = get_multi_run_manager()
self._last_logged_time = time()
self._last_logged_ids: list[str] | None = None
self._waiting_since: float | None = None
self.context = zmq.Context.instance()
self.socket: zmq.Socket = self.context.socket(zmq.PULL)
self.socket.setsockopt(zmq.RCVHWM, transport.hwm)
self.socket.bind(f"tcp://{transport.host}:{transport.port}")
self.poller = zmq.Poller()
self.poller.register(self.socket, zmq.POLLIN)
# Pending batches per run_id, keyed by step -> batch.
# We return the smallest step first; newer steps remain buffered.
self._pending: dict[bytes, dict[int, TrainingBatch]] = {}
self.logger.info(
f"ZMQ training batch receiver initialized: endpoint=tcp://{transport.host}:{transport.port} hwm={transport.hwm}"
)
def can_receive(self) -> bool:
events = dict(self.poller.poll(timeout=0))
return self.socket in events
def _drain_into_pending(self) -> None:
"""Drain all currently available ZMQ messages into the per-idx pending buffer (non-blocking)."""
while True:
if not self.can_receive():
break
try:
sender_id, payload = self.socket.recv_multipart(flags=zmq.NOBLOCK, copy=False)
except zmq.Again:
break
try:
batch: TrainingBatch = self.decoder.decode(payload)
sender_id = bytes(sender_id)
except Exception as e:
self.logger.error(f"Error decoding rollouts for sender_id={sender_id!r}: {e}")
continue
per_id_batches = self._pending.setdefault(sender_id, {})
assert batch.step not in per_id_batches, (
f"Step {batch.step} already in pending for {sender_id!r}, this should not happen: {per_id_batches.keys()}"
)
per_id_batches[batch.step] = batch
def receive(self) -> list[TrainingBatch]:
"""Return at most one (oldest) pending batch per run idx; buffer newer ones for later calls."""
batches: list[TrainingBatch] = []
now = time()
# Bring any available messages into the pending buffer (non-blocking)
self._drain_into_pending()
# Track how long we've been waiting for any runnable batch.
runnable_available = False
for idx in self.multi_run_manager.used_idxs:
if self.multi_run_manager.ready_to_update[idx]:
continue
run_id = self.multi_run_manager.idx_2_id[idx].encode("utf-8")
if self._pending.get(run_id):
runnable_available = True
break
if runnable_available:
self._waiting_since = None
else:
self._waiting_since = self._waiting_since or now
current_ids = [self.multi_run_manager.idx_2_id[idx] for idx in self.multi_run_manager.used_idxs]
if current_ids != self._last_logged_ids or now - self._last_logged_time > LOG_FREQ_SECONDS:
if len(current_ids) == 0:
self.logger.debug(
"Did you set the output dir of the orchestrator to a run_* subdirectory of the trainer output dir?"
)
waiting_suffix = ""
if self._waiting_since is not None:
waiting_suffix = f" (waiting {now - self._waiting_since:.1f}s)"
self.logger.debug(f"Listening for batches from runs {current_ids}{waiting_suffix}")
self._last_logged_ids = current_ids
self._last_logged_time = now
for idx in list(self.multi_run_manager.used_idxs):
run_id = self.multi_run_manager.idx_2_id[idx].encode("utf-8")
if self.multi_run_manager.ready_to_update[idx]:
continue
per_id_batches = self._pending.get(run_id)
if not per_id_batches:
continue
oldest_step = min(per_id_batches.keys())
batch = per_id_batches.pop(oldest_step)
if not per_id_batches:
self._pending.pop(run_id, None)
batch.run_idx = idx
self.logger.debug(f"Received batch {batch.step} from {run_id!r}")
batches.append(batch)
return batches
def close(self) -> None:
try:
self.socket.close(linger=0)
finally:
self.context.term()
self.logger.info("ZMQ training batch receiver closed")
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transport.types import MicroBatch
class ZMQMicroBatchSender(MicroBatchSender):
def __init__(self, output_dir: Path, data_world_size: int, current_step: int, transport: ZMQTransportConfig):
"""ZMQ micro batch sender that sends micro batches to the trainers through ZMQ transport. There is one sender for the entire data world."""
"""ZMQ micro batch sender that publishes per-rank micro batches to the trainers.
There is one sender (in the orchestrator process) for the entire data world.
PUB never blocks: a message past a subscriber's HWM would be dropped
silently. The orchestrator's dispatch gate bounds in-flight steps to
TARGET_LAG + 1 (one message per rank per step), far below the HWM, so
drops cannot happen in steady state; the READY barrier below covers
slow joiners at startup.
"""
super().__init__(output_dir, data_world_size)
self.context = zmq.Context.instance()
# Async context so ``send`` yields instead of blocking the orchestrator event loop
self.context = zmq.asyncio.Context.instance()
# Data channel (PUB)
self.socket: zmq.Socket = self.context.socket(zmq.PUB)
self.socket: zmq.asyncio.Socket = self.context.socket(zmq.PUB)
self.socket.setsockopt(zmq.SNDHWM, transport.hwm)
self.socket.bind(f"tcp://{transport.host}:{transport.port + 1}")
self.socket.bind(f"tcp://{transport.host}:{transport.port}")
# ready barrier socket, to avoid slow joiners dropping for step 0 (and generally at startup)
self.ready_socket: zmq.Socket = self.context.socket(zmq.PULL)
self.ready_socket: zmq.asyncio.Socket = self.context.socket(zmq.PULL)
self.ready_socket.setsockopt(zmq.RCVHWM, transport.hwm)
self.ready_socket.bind(f"tcp://{transport.host}:{transport.port + 2}")
self.ready_socket.bind(f"tcp://{transport.host}:{transport.port + 1}")
self._ready = False
self.logger.info(
f"ZMQ micro batch sender initialized: endpoint=tcp://{transport.host}:{transport.port + 1} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 2} hwm={transport.hwm}"
f"ZMQ micro batch sender initialized: endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm}"
)
self._topic_prefix = b"data_rank|"
self._current_step = current_step
def _wait_for_ready(self) -> None:
async def _wait_for_ready(self) -> None:
if self._ready:
return
@@ -209,7 +53,7 @@ class ZMQMicroBatchSender(MicroBatchSender):
# Block until all ranks have announced readiness
while len(ready_ranks) < self.data_world_size:
msg = self.ready_socket.recv() # blocks
msg = await self.ready_socket.recv()
try:
rank = int(msg.decode("utf-8"))
except Exception:
@@ -219,20 +63,20 @@ class ZMQMicroBatchSender(MicroBatchSender):
self.logger.debug(f"All {self.data_world_size} ranks READY, starting PUB")
self._ready = True
def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
"""Send grid of micro batches to the trainers."""
assert len(micro_batch_grid) == self.data_world_size, "Number of micro batch lists must match data world size"
for micro_batch_list in micro_batch_grid:
assert len(micro_batch_list) == len(micro_batch_grid[0]), "All micro batch lists must have the same length"
# Ensure no slow-joiner drops for step 0 (and generally at startup)
self._wait_for_ready()
await self._wait_for_ready()
self.logger.debug(f"Sending micro batch grid for step {self._current_step}")
for data_rank in range(self.data_world_size):
buffer = self.encoder.encode(micro_batch_grid[data_rank])
topic = self._topic_prefix + str(data_rank).encode("utf-8") + b"|"
self.socket.send_multipart([topic, buffer], copy=False)
await self.socket.send_multipart([topic, buffer], copy=False)
self._current_step += 1
def close(self) -> None:
@@ -245,13 +89,13 @@ class ZMQMicroBatchSender(MicroBatchSender):
class ZMQMicroBatchReceiver(MicroBatchReceiver):
def __init__(self, output_dir: Path, data_rank: int, current_step: int, transport: ZMQTransportConfig):
"""ZMQ micro batch receiver that receives micro batches from the sender. There is one receiver per data rank."""
"""ZMQ micro batch receiver that receives micro batches from the orchestrator. There is one receiver per data rank."""
super().__init__(output_dir, data_rank)
self.context = zmq.Context.instance()
self.socket: zmq.Socket = self.context.socket(zmq.SUB)
self.socket.setsockopt(zmq.RCVHWM, transport.hwm)
self.socket.connect(f"tcp://{transport.host}:{transport.port + 1}")
self.socket.connect(f"tcp://{transport.host}:{transport.port}")
self._topic = b"data_rank|" + str(data_rank).encode("utf-8") + b"|"
self.socket.setsockopt(zmq.SUBSCRIBE, self._topic)
@@ -262,14 +106,14 @@ class ZMQMicroBatchReceiver(MicroBatchReceiver):
# ready barrier socket, to avoid slow joiners dropping for step 0 (and generally at startup)
self.ready_socket: zmq.Socket = self.context.socket(zmq.PUSH)
self.ready_socket.setsockopt(zmq.SNDHWM, transport.hwm)
self.ready_socket.connect(f"tcp://{transport.host}:{transport.port + 2}")
self.ready_socket.connect(f"tcp://{transport.host}:{transport.port + 1}")
# Announce readiness after connect+subscribe are set
self.ready_socket.send(str(data_rank).encode("utf-8"))
self.logger.info(
f"ZMQ micro batch receiver initialized: endpoint=tcp://{transport.host}:{transport.port + 1} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 2} hwm={transport.hwm}"
f"ZMQ micro batch receiver initialized: endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm}"
)
self._current_step = current_step
@@ -282,7 +126,7 @@ class ZMQMicroBatchReceiver(MicroBatchReceiver):
return self.socket in events
def receive(self) -> list[MicroBatch]:
"""Receive a micro batch from the trainer."""
"""Receive a micro batch from the orchestrator."""
_, payload = self.socket.recv_multipart(copy=False)
micro_batches: list[MicroBatch] = self.decoder.decode(payload)
self.logger.debug(f"Received {len(micro_batches)} micro batches for step {self._current_step}")
+27 -147
View File
@@ -2,10 +2,7 @@ from __future__ import annotations
import asyncio
import os
from collections.abc import Mapping
from itertools import cycle
from pathlib import Path
from typing import Protocol, runtime_checkable
import httpx
import verifiers.v1 as vf
@@ -18,102 +15,33 @@ from verifiers.v1.configs.client import EvalClientConfig, TrainClientConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
ClientIdentity = str
def client_identity(client: vf.ClientConfig) -> ClientIdentity:
"""Stable identity for load balancing across inference clients."""
return client.base_url
@runtime_checkable
class InferencePool(Protocol):
"""Protocol for inference pools (static or elastic)."""
@property
def model_name(self) -> str:
"""Get current model name for inference requests."""
...
@property
def train_clients(self) -> list[vf.ClientConfig]:
"""Get inference clients."""
...
@property
def admin_clients(self) -> list[AsyncClient]:
"""Get admin clients."""
...
def update_model_name(self, model_name: str) -> None:
"""Update the model name."""
...
async def get_eval_client(self) -> vf.ClientConfig:
"""Get next eval client in round-robin fashion."""
...
async def select_train_client(self, load: Mapping[ClientIdentity, int]) -> vf.ClientConfig:
"""Pick the train client with lowest in-flight load.
Waits for at least one train client to be available, then returns
the one with the smallest ``load[client_identity(client)]``. The
caller owns the in-flight counter; the pool just picks against it.
"""
...
async def wait_for_ready(self, model_name: str, timeout: int | None = None) -> None:
"""Wait for inference pool to be ready."""
...
async def update_weights(self, weight_dir: Path | None, lora_name: str | None = None, step: int = 0) -> None:
"""Update weights on all inference servers."""
...
async def score(self, token_ids: list[int]) -> list[float]:
"""Prefill-score ``token_ids`` under the pool's model — one logprob per token."""
...
async def stop(self) -> None:
"""Stop the inference pool."""
...
class PrefillScorer:
"""Prefill-scores token ids against a pool's *current* endpoints. Resolves one
client per endpoint, cached by endpoint identity — so it fills once for a
static pool and tolerates churn for an elastic one (a departed endpoint is
simply never selected again; its client is closed at stop). Round-robins over
the live endpoints."""
"""Prefill-scores token ids against a pool's endpoint, lazily resolving
a single OpenAI client from the pool's train client config."""
def __init__(self) -> None:
self._clients: dict = {} # client_identity -> AsyncOpenAI, one per endpoint
self._rr = 0
self._client: AsyncOpenAI | None = None
async def score(self, configs: list[vf.ClientConfig], model: str, token_ids: list[int]) -> list[float]:
if not configs:
raise RuntimeError("no inference endpoints available to prefill-score")
cfg = configs[self._rr % len(configs)]
self._rr += 1
key = client_identity(cfg)
openai = self._clients.get(key)
if openai is None:
async def score(self, config: vf.ClientConfig, model: str, token_ids: list[int]) -> list[float]:
if self._client is None:
# Build the OpenAI client straight from the config fields — works for any
# ClientConfig type; resolve_client would hand back an EvalClient (no `.openai`)
# for these chat-completions teacher configs.
openai = self._clients[key] = AsyncOpenAI(
base_url=cfg.base_url,
api_key=os.environ.get(cfg.api_key_var) or "EMPTY",
default_headers=cfg.headers or None,
self._client = AsyncOpenAI(
base_url=config.base_url,
api_key=os.environ.get(config.api_key_var) or "EMPTY",
default_headers=config.headers or None,
)
return await prefill_logprobs(openai, model, token_ids)
return await prefill_logprobs(self._client, model, token_ids)
async def aclose(self) -> None:
await asyncio.gather(*(c.close() for c in self._clients.values()))
if self._client is not None:
await self._client.close()
class StaticInferencePool:
"""Static inference pool with fixed client list."""
class InferencePool:
"""Inference pool with a single data-plane endpoint and one admin client per server."""
def __init__(
self,
@@ -124,13 +52,13 @@ class StaticInferencePool:
renderer_config: RendererConfig | None = None,
):
renderer_model_name = model_name if train_client_type == "renderer" else None
self._train_clients = setup_clients(
self.train_client = setup_client(
client_config,
client_type=train_client_type,
renderer_config=renderer_config,
renderer_model_name=renderer_model_name,
)
self._eval_clients = setup_clients(client_config, client_type=eval_client_type)
self.eval_client = setup_client(client_config, client_type=eval_client_type)
self._admin_clients = setup_admin_clients(client_config)
# When admin URLs bypass a router, also health-check the client-facing
# (router) endpoint - it only starts serving once its workers are healthy.
@@ -141,14 +69,9 @@ class StaticInferencePool:
)
self._skip_model_check = client_config.skip_model_check
self._wait_for_ready_timeout = client_config.wait_for_ready_timeout
self._eval_cycle = cycle(self._eval_clients)
self._scorer = PrefillScorer()
self.model_name = model_name
@property
def train_clients(self) -> list[vf.ClientConfig]:
return self._train_clients
@property
def admin_clients(self) -> list[AsyncClient]:
return self._admin_clients
@@ -156,18 +79,6 @@ class StaticInferencePool:
def update_model_name(self, model_name: str) -> None:
self.model_name = model_name
@property
def eval_clients(self) -> list[vf.ClientConfig]:
return self._eval_clients
async def get_eval_client(self) -> vf.ClientConfig:
return next(self._eval_cycle)
async def select_train_client(self, load: Mapping[ClientIdentity, int]) -> vf.ClientConfig:
while not self.train_clients:
await asyncio.sleep(0.5)
return min(self.train_clients, key=lambda c: load[client_identity(c)])
async def wait_for_ready(self, model_name: str, timeout: int | None = None) -> None:
await check_health(
self._admin_clients + self._router_clients,
@@ -181,47 +92,19 @@ class StaticInferencePool:
async def score(self, token_ids: list[int]) -> list[float]:
"""Prefill-score ``token_ids`` under this pool's model (one logprob per
token, 0.0 for the leading token). Delegates to the shared scorer."""
return await self._scorer.score(self.train_clients, self.model_name, token_ids)
return await self._scorer.score(self.train_client, self.model_name, token_ids)
async def stop(self) -> None:
await self._scorer.aclose()
async def setup_inference_pool(
client_config: ClientConfig,
model_name: str,
train_client_type: str = "openai_chat_completions",
eval_client_type: str = "openai_chat_completions",
renderer_config: RendererConfig | None = None,
) -> InferencePool:
"""Create an inference pool from config (static or elastic)."""
if client_config.is_elastic:
from prime_rl.utils.elastic import ElasticInferencePool
return await ElasticInferencePool.from_config(
client_config,
model_name=model_name,
train_client_type=train_client_type,
eval_client_type=eval_client_type,
renderer_config=renderer_config,
)
return StaticInferencePool(
client_config,
model_name=model_name,
train_client_type=train_client_type,
eval_client_type=eval_client_type,
renderer_config=renderer_config,
)
def setup_clients(
def setup_client(
client_config: ClientConfig,
client_type: str = "openai_chat_completions",
renderer_config: RendererConfig | None = None,
renderer_model_name: str | None = None,
) -> list[vf.ClientConfig]:
"""Build one v1 client config per base URL. ``client_type``
) -> vf.ClientConfig:
"""Build a v1 client config for the base URL. ``client_type``
``renderer`` → token-in/out (``TrainClientConfig``, with the renderer the env
server should use forwarded as a serialized config so it doesn't fall back to the
default renderer); otherwise plain chat-completions (``EvalClientConfig``)."""
@@ -236,13 +119,10 @@ def setup_clients(
env_headers = {
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
}
clients: list[vf.ClientConfig] = []
for base_url in client_config.base_url:
headers = {**client_config.headers, **env_headers}
clients.append(
config_cls(base_url=base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra)
)
return clients
headers = {**client_config.headers, **env_headers}
return config_cls(
base_url=client_config.base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra
)
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
@@ -252,7 +132,7 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
When admin_base_url is set, uses those URLs instead of base_url, allowing
weight updates to bypass routers in disaggregated P/D deployments.
"""
urls = client_config.admin_base_url if client_config.admin_base_url else client_config.base_url
urls = client_config.admin_base_url if client_config.admin_base_url else [client_config.base_url]
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
env_headers = {
@@ -455,8 +335,8 @@ def _is_retryable_lora_error(exception: BaseException) -> bool:
# Per-attempt and total bounds for `/load_lora_adapter`. A LoRA load is fast
# (small adapter file + KV cache reset, single-digit seconds in practice) but
# the global admin AsyncClient uses `timeout=None`, so a stuck server hangs
# the orchestrator forever inside `ElasticInferencePool._sync_server_adapter`.
# the global admin AsyncClient uses `timeout=None`, so a stuck server would
# hang the orchestrator forever.
# `_PER_ATTEMPT` converts a hang into a TimeoutException so tenacity retries;
# `_TOTAL` is the wall-clock budget across all retries — pick whichever
# stop condition fires first.
-507
View File
@@ -1,507 +0,0 @@
"""
Elastic inference pool with DNS-based service discovery.
Discovers inference servers via DNS (any hostname that resolves to multiple IPs),
tracks which servers have the correct LoRA adapter loaded, and
only exposes ready servers to workers.
"""
from __future__ import annotations
import asyncio
import socket
import time
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Literal
import httpx
import verifiers.v1 as vf
from httpx import AsyncClient
from renderers import RendererConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.client import (
ClientIdentity,
PrefillScorer,
client_identity,
load_lora_adapter,
setup_admin_clients,
setup_clients,
)
from prime_rl.utils.logger import get_logger
# --- Shared discovery functions ---
def discover_server_ips(hostname: str) -> list[str]:
"""Discover server IPs via DNS lookup."""
try:
_, _, ips = socket.gethostbyname_ex(hostname)
return sorted(ips)
except socket.gaierror:
return []
async def check_server_model(url: str, model_name: str, timeout: float = 5.0) -> tuple[bool, bool]:
"""Check if a server has a specific model loaded."""
logger = get_logger()
try:
async with httpx.AsyncClient(timeout=timeout) as client:
response = await client.get(f"{url}/v1/models")
response.raise_for_status()
data = response.json()
models = [m.get("id") for m in data.get("data", [])]
return model_name in models, len(models) > 0
except Exception as e:
logger.debug(f"Failed to check server {url}: {e}")
return False, False
async def discover_ready_servers(hostname: str, port: int, model_name: str) -> list[str]:
"""Discover servers via DNS that have the requested model loaded."""
loop = asyncio.get_event_loop()
ips = await loop.run_in_executor(None, discover_server_ips, hostname)
if not ips:
return []
checks = [check_server_model(f"http://{ip}:{port}", model_name) for ip in ips]
results = await asyncio.gather(*checks, return_exceptions=True)
with_model = set()
for ip, result in zip(ips, results):
if isinstance(result, BaseException):
continue
has_model, _ = result
if has_model:
with_model.add(f"http://{ip}:{port}/v1")
return sorted(with_model)
@dataclass
class AdapterState:
"""State of a LoRA adapter (loaded or desired)."""
name: str | None = None
path: Path | None = None
step: int = 0
ServerStatus = Literal["discovering", "syncing", "ready", "unhealthy"]
@dataclass
class ServerState:
"""State of an individual inference server."""
ip: str
url: str
status: ServerStatus = "discovering"
loaded_adapter: AdapterState | None = None
sync_failures: int = 0
class ElasticInferencePool:
"""Manages inference servers with DNS-based discovery and adapter sync.
Discovers servers via DNS, tracks adapter state, syncs LoRA adapters.
"""
def __init__(
self,
client_config: ClientConfig,
model_name: str,
train_client_type: str = "openai_chat_completions",
eval_client_type: str = "openai_chat_completions",
renderer_config: RendererConfig | None = None,
):
self.logger = get_logger()
self.client_config = client_config
self.model_name = model_name
self.base_model_name = model_name # Keep original for health checks
self.renderer_model_name = model_name if train_client_type == "renderer" else None
self.hostname = client_config.elastic.hostname
self.port = client_config.elastic.port
self.sync_interval = client_config.elastic.sync_interval
self.train_client_type = train_client_type
self.eval_client_type = eval_client_type
self.renderer_config = renderer_config
self.router_url = client_config.router_url
self._servers: dict[str, ServerState] = {}
self._admin_clients: dict[str, AsyncClient] = {}
self._lock = asyncio.Lock()
self._desired: AdapterState = AdapterState()
self._train_clients: list[vf.ClientConfig] = []
self._eval_clients: list[vf.ClientConfig] = []
self._client_urls: list[str] = []
self._eval_index = 0
self._sync_task: asyncio.Task | None = None
self._started = False
self._scorer = PrefillScorer()
@classmethod
async def from_config(
cls,
client_config: ClientConfig,
model_name: str,
train_client_type: str = "openai_chat_completions",
eval_client_type: str = "openai_chat_completions",
renderer_config: RendererConfig | None = None,
) -> ElasticInferencePool:
if client_config.elastic is None:
raise ValueError("Elastic inference pool requires elastic config")
pool = cls(
client_config,
model_name=model_name,
train_client_type=train_client_type,
eval_client_type=eval_client_type,
renderer_config=renderer_config,
)
await pool.start()
return pool
def update_model_name(self, model_name: str) -> None:
self.model_name = model_name
def _build_url(self, ip: str) -> str:
return f"http://{ip}:{self.port}"
def _build_inference_url(self, ip: str) -> str:
return f"http://{ip}:{self.port}/v1"
@property
def ready_urls(self) -> list[str]:
return [self._build_inference_url(ip) for ip, s in self._servers.items() if s.status == "ready"]
def _rebuild_clients(self) -> None:
"""Rebuild inference clients when the set of ready URLs changes."""
# When a router URL is configured, route inference requests through it
# instead of directly to discovered pods. Admin operations still use
# individual pod IPs via admin_clients.
# Only expose the router when backends are actually ready — otherwise
# the orchestrator would send requests into a router with no healthy backends.
if self.router_url and self.ready_urls:
urls = [self.router_url]
else:
urls = self.ready_urls
if set(urls) != set(self._client_urls):
self._client_urls = urls
self._eval_index = 0
url_config = ClientConfig(
base_url=urls,
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
headers_from_env=self.client_config.headers_from_env,
extra_headers_from_state=self.client_config.extra_headers_from_state,
)
self._train_clients = (
setup_clients(
url_config,
client_type=self.train_client_type,
renderer_config=self.renderer_config,
renderer_model_name=self.renderer_model_name,
)
if urls
else []
)
self._eval_clients = setup_clients(url_config, client_type=self.eval_client_type) if urls else []
@property
def train_clients(self) -> list[vf.ClientConfig]:
self._rebuild_clients()
return self._train_clients
@property
def eval_clients(self) -> list[vf.ClientConfig]:
self._rebuild_clients()
return self._eval_clients
async def get_eval_client(self) -> vf.ClientConfig:
"""Get next eval client in round-robin fashion."""
while not self.eval_clients:
await asyncio.sleep(self.sync_interval)
client = self._eval_clients[self._eval_index % len(self._eval_clients)]
self._eval_index += 1
return client
async def select_train_client(self, load: Mapping[ClientIdentity, int]) -> vf.ClientConfig:
while not self.train_clients:
await asyncio.sleep(self.sync_interval)
return min(self.train_clients, key=lambda c: load[client_identity(c)])
async def score(self, token_ids: list[int]) -> list[float]:
return await self._scorer.score(self.train_clients, self.model_name, token_ids)
@property
def admin_clients(self) -> list[AsyncClient]:
return list(self._admin_clients.values())
@property
def num_servers(self) -> int:
return len(self._servers)
@property
def num_ready_servers(self) -> int:
return sum(1 for s in self._servers.values() if s.status == "ready")
async def _create_admin_client(self, ip: str) -> AsyncClient:
url = self._build_url(ip)
config = ClientConfig(
base_url=[f"{url}/v1"],
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
headers_from_env=self.client_config.headers_from_env,
)
return setup_admin_clients(config)[0]
async def _get_loaded_adapter(self, ip: str) -> AdapterState | None:
if ip not in self._admin_clients:
return None
try:
admin = self._admin_clients[ip]
response = await admin.get("/v1/models")
response.raise_for_status()
data = response.json()
for model in data.get("data", []):
parent = model.get("parent")
model_id = model.get("id", "")
if self._desired.name:
if model_id != self._desired.name:
continue
elif not parent:
continue
elif parent != self.model_name:
continue
root = model.get("root", "")
path = Path(root)
try:
step_part = path.name
if step_part.startswith("step_"):
step = int(step_part.split("_")[1])
elif step_part.startswith("step-"):
step = int(step_part.split("-")[1])
else:
step = 0
except (ValueError, IndexError):
step = 0
return AdapterState(name=model_id, path=path, step=step)
self.logger.debug(f"No matching adapter found on {ip} for desired={self._desired.name}")
return None
except Exception as e:
self.logger.warning(f"Failed to query /v1/models on {ip}: {e}")
return None
def _adapter_matches_desired(self, loaded: AdapterState | None) -> bool:
if self._desired.path is None:
return True
if loaded is None:
return False
if loaded.path == self._desired.path:
return True
if self._desired.step > 0 and loaded.step == self._desired.step:
return True
return False
async def _sync_server_adapter(self, ip: str) -> bool:
server = self._servers.get(ip)
if not server:
return False
loaded = await self._get_loaded_adapter(ip)
server.loaded_adapter = loaded
if self._adapter_matches_desired(loaded):
server.status = "ready"
return True
# Debug: log why pre-check failed (before attempting load)
self.logger.debug(
f"Pre-check failed on {ip}: loaded={loaded.path if loaded else None} "
f"(step={loaded.step if loaded else None}), desired={self._desired.path} (step={self._desired.step})"
)
server.status = "syncing"
if self._desired.name and self._desired.path:
try:
self.logger.debug(f"Loading adapter {self._desired.name} on {ip}")
await load_lora_adapter([self._admin_clients[ip]], self._desired.name, self._desired.path)
except Exception as e:
server.status = "unhealthy"
server.sync_failures += 1
self.logger.error(f"Failed to sync server {ip}: {e}")
return False
loaded = await self._get_loaded_adapter(ip)
server.loaded_adapter = loaded
if self._adapter_matches_desired(loaded):
server.status = "ready"
server.sync_failures = 0
self.logger.debug(f"Successfully synced server {ip}")
return True
# Debug: log why adapter didn't match after loading
self.logger.warning(
f"Adapter mismatch on {ip} after loading: "
f"loaded={loaded.path if loaded else None} (step={loaded.step if loaded else None}), "
f"desired={self._desired.path} (step={self._desired.step})"
)
server.status = "unhealthy"
server.sync_failures += 1
return False
async def _check_server_health(self, admin_client: AsyncClient, ip: str) -> bool:
try:
response = await admin_client.get("/health")
response.raise_for_status()
except Exception as e:
self.logger.debug(f"Server {ip} health check failed: {e}")
return False
try:
response = await admin_client.get("/v1/models")
response.raise_for_status()
data = response.json()
models = [m.get("id") for m in data.get("data", [])]
if self.base_model_name not in models:
self.logger.debug(f"Server {ip} does not have base model {self.base_model_name}")
return False
except Exception as e:
self.logger.debug(f"Server {ip} model check failed: {e}")
return False
return True
async def _add_server(self, ip: str) -> bool:
try:
admin_client = await self._create_admin_client(ip)
except Exception as e:
self.logger.debug(f"Failed to create admin client for {ip}: {e}")
return False
if not await self._check_server_health(admin_client, ip):
await admin_client.aclose()
return False
self.logger.debug(f"Discovered new inference server: {ip}")
self._admin_clients[ip] = admin_client
self._servers[ip] = ServerState(ip=ip, url=self._build_url(ip), status="discovering")
await self._sync_server_adapter(ip)
return True
async def _remove_server(self, ip: str) -> None:
self.logger.debug(f"Inference server removed: {ip}")
self._servers.pop(ip, None)
if ip in self._admin_clients:
await self._admin_clients.pop(ip).aclose()
async def sync(self) -> tuple[int, int]:
async with self._lock:
discovered_ips = set(
await asyncio.get_event_loop().run_in_executor(None, discover_server_ips, self.hostname)
)
known_ips = set(self._servers.keys())
added = 0
removed = 0
for ip in discovered_ips - known_ips:
if await self._add_server(ip):
added += 1
for ip in known_ips - discovered_ips:
await self._remove_server(ip)
removed += 1
for ip in list(self._servers.keys()):
if ip not in self._admin_clients:
continue
if not await self._check_server_health(self._admin_clients[ip], ip):
self.logger.debug(f"Server {ip} failed health check, removing")
await self._remove_server(ip)
removed += 1
elif self._servers[ip].status != "ready":
await self._sync_server_adapter(ip)
return added, removed
async def _sync_loop(self) -> None:
while True:
try:
added, removed = await self.sync()
if added > 0 or removed > 0:
self.logger.debug(
f"Elastic pool sync: +{added} -{removed} servers "
f"(total: {self.num_servers}, ready: {self.num_ready_servers})"
)
except Exception as e:
self.logger.error(f"Error in elastic sync loop: {e}")
await asyncio.sleep(self.sync_interval)
async def start(self) -> None:
if self._started:
return
self.logger.debug(f"Starting elastic inference pool (hostname={self.hostname})")
await self.sync()
self.logger.debug(f"Initial discovery: {self.num_servers} server(s), {self.num_ready_servers} ready")
self._sync_task = asyncio.create_task(self._sync_loop())
self._started = True
async def stop(self) -> None:
if self._sync_task:
self._sync_task.cancel()
try:
await self._sync_task
except asyncio.CancelledError:
pass
for ip in list(self._servers.keys()):
await self._remove_server(ip)
await self._scorer.aclose()
self._train_clients = []
self._eval_clients = []
self._client_urls = []
self._started = False
async def sync_weights(self, weights_path: Path | None, lora_name: str | None = None, step: int = 0) -> None:
async with self._lock:
self._desired = AdapterState(
name=lora_name,
path=weights_path if lora_name else None,
step=step,
)
# Sync all servers in parallel for faster weight updates
await asyncio.gather(*[self._sync_server_adapter(ip) for ip in self._servers.keys()])
async def wait_for_ready(self, model_name: str = "", timeout: int | None = None, min_servers: int = 1) -> None:
if timeout is None:
timeout = self.client_config.wait_for_ready_timeout
start = time.time()
while time.time() - start < timeout:
await self.sync()
if self.num_ready_servers >= min_servers:
return
self.logger.debug(f"Waiting for servers: {self.num_ready_servers}/{min_servers} ready")
await asyncio.sleep(self.sync_interval)
raise TimeoutError(f"Timed out waiting for {min_servers} ready servers (got {self.num_ready_servers})")
async def update_weights(self, weight_dir: Path | None, lora_name: str | None = None, step: int = 0) -> None:
if lora_name is None:
raise ValueError("Elastic inference pool requires LoRA training (lora_name must be set)")
await self.sync_weights(weight_dir, lora_name, step)
-76
View File
@@ -7,7 +7,6 @@ Runs in a background thread to avoid blocking the training loop.
import threading
import time
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import TYPE_CHECKING
@@ -18,17 +17,6 @@ if TYPE_CHECKING:
from prime_rl.configs.shared import MetricsServerConfig
@dataclass
class RunStats:
"""Statistics for a single run/LoRA adapter."""
run_id: str
step: int
total_tokens: int
learning_rate: float
ready: bool
class HealthServer:
"""Lightweight HTTP server exposing /health for Kubernetes liveness probes.
@@ -120,31 +108,6 @@ class MetricsServer(HealthServer):
"Fraction of tracked parameter elements with zero gradient",
registry=self._registry,
)
# Aggregate run metrics
self._runs_discovered = Gauge(
"trainer_runs_discovered", "Number of run folders discovered", registry=self._registry
)
self._runs_active = Gauge("trainer_runs_active", "Number of runs with assigned slots", registry=self._registry)
self._runs_ready = Gauge(
"trainer_runs_ready", "Number of runs ready for gradient updates", registry=self._registry
)
self._runs_max = Gauge("trainer_runs_max", "Maximum run capacity", registry=self._registry)
# Per-run metrics with labels
self._run_step = Gauge("trainer_run_step", "Training step for run", ["run"], registry=self._registry)
self._run_tokens = Gauge(
"trainer_run_tokens", "Total tokens processed by run", ["run"], registry=self._registry
)
self._run_learning_rate = Gauge(
"trainer_run_learning_rate", "Current learning rate for run", ["run"], registry=self._registry
)
self._run_ready = Gauge(
"trainer_run_ready",
"Whether run is ready for updates (1=ready, 0=not ready)",
["run"],
registry=self._registry,
)
# Track known run labels for cleanup
self._known_runs: set[str] = set()
def _make_handler(self) -> type[BaseHTTPRequestHandler]:
"""Create handler with /metrics and /health endpoints."""
@@ -218,42 +181,3 @@ class MetricsServer(HealthServer):
if entropy > 0:
self._kl_ent_ratio.set(mismatch_kl / entropy)
self._last_step_ts.set(time.time())
def update_runs(
self,
runs_discovered: int,
runs_max: int,
run_stats: list[RunStats],
) -> None:
"""Update run/LoRA metrics.
Args:
runs_discovered: Number of run_* folders found in output directory
runs_max: Maximum run capacity
run_stats: List of per-run statistics
"""
# Update aggregate metrics
self._runs_discovered.set(runs_discovered)
self._runs_active.set(len(run_stats))
self._runs_ready.set(sum(1 for r in run_stats if r.ready))
self._runs_max.set(runs_max)
# Track current runs for cleanup
current_runs = {r.run_id for r in run_stats}
# Remove metrics for runs that no longer exist
removed_runs = self._known_runs - current_runs
for run_id in removed_runs:
self._run_step.remove(run_id)
self._run_tokens.remove(run_id)
self._run_learning_rate.remove(run_id)
self._run_ready.remove(run_id)
# Update per-run metrics
for run in run_stats:
self._run_step.labels(run=run.run_id).set(run.step)
self._run_tokens.labels(run=run.run_id).set(run.total_tokens)
self._run_learning_rate.labels(run=run.run_id).set(run.learning_rate)
self._run_ready.labels(run=run.run_id).set(1 if run.ready else 0)
self._known_runs = current_runs
+1 -9
View File
@@ -98,12 +98,6 @@ def get_all_ckpt_steps(ckpt_dir: Path) -> list[int]:
return sorted([int(step_dir.name.split("_")[-1]) for step_dir in step_dirs])
def get_stable_ckpt_steps(ckpt_dir: Path) -> list[int]:
"""Gets checkpoint steps that have STABLE file, sorted in ascending order."""
steps = get_all_ckpt_steps(ckpt_dir)
return [s for s in steps if (ckpt_dir / f"step_{s}" / "STABLE").exists()]
def resolve_latest_ckpt_step(ckpt_dir: Path) -> int | None:
"""Gets the latest checkpoint step from the checkpoint directory. Returns None if no checkpoints are found."""
steps = get_all_ckpt_steps(ckpt_dir)
@@ -161,11 +155,9 @@ def clean_future_steps(output_dir: Path, resume_step: int) -> None:
Pass ``resume_step=-1`` to wipe every step directory (fresh runs).
"""
run_default = output_dir / "run_default"
dirs = [
get_rollout_dir(output_dir),
get_rollout_dir(run_default),
get_broadcast_dir(run_default),
get_broadcast_dir(output_dir),
]
for directory in dirs:
-1
View File
@@ -23,7 +23,6 @@ from prime_rl.utils.pathing import (
get_eval_dir,
get_log_dir,
get_rollout_dir,
get_stable_ckpt_steps,
get_step_path,
get_weights_dir,
resolve_latest_ckpt_step,
@@ -1,459 +0,0 @@
"""Integration tests for multi-run RL training with LoRA adapters."""
import os
import shutil
import signal
import subprocess
import time
from pathlib import Path
from typing import Generator
import pytest
from tests.conftest import ProcessResult
from tests.utils import check_reward_goes_up, check_reward_in_range, strip_escape_codes
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 600 # 10 minutes (was 300s — too tight when 3 concurrent orchestrators
# contend for 2 inference GPUs; verifiers per-call tracing added overhead)
ORCHESTRATOR_NAMES = ["alpha", "beta", "gamma"]
def remove_run_dir(run_dir: Path) -> None:
"""Delete a run dir, tolerating the shared trainer still flushing its tail
(token exports recreate directories mid-rmtree -> 'Directory not empty')."""
for _ in range(10):
shutil.rmtree(run_dir, ignore_errors=True)
if not run_dir.exists():
return
time.sleep(1)
shutil.rmtree(run_dir)
def wait_for_file(
file_path: Path,
timeout: int = 600,
poll_interval: float = 1.0,
) -> None:
"""Wait for file to exist.
Args:
file_path: Path to the file.
timeout: Timeout waiting for file to exist in seconds.
poll_interval: Interval in seconds to poll for the file.
Raises:
TimeoutError: If the file does not appear within timeout.
"""
print(f"Waiting for {file_path} to exist")
start_time = time.time()
while not file_path.exists():
if time.time() - start_time > timeout:
raise TimeoutError(f"Timed out waiting for {file_path} to exist after {timeout}s")
time.sleep(poll_interval)
def wait_for_log(
log_file: Path,
conditions: list[str],
proc: subprocess.Popen,
timeout: int = 600,
poll_interval: float = 0.1,
sigterm: bool = False,
kill: bool = False,
) -> None:
"""Wait for any of the conditions to appear in log file, then optionally send SIGTERM or kill the process.
Args:
log_file: Path to the log file.
conditions: List of substrings to wait for.
proc: Process to kill.
timeout: Timeout waiting for conditions in seconds.
poll_interval: Interval in seconds to poll the log file.
sigterm: Whether to send SIGTERM to the process.
kill: Whether to kill the process right after sending SIGTERM.
"""
start_time = time.time()
print(f"Waiting for conditions {conditions} in {proc.pid}")
while True:
if time.time() - start_time > timeout:
raise TimeoutError(f"Timed out waiting for conditions {conditions} in {log_file} after {timeout}s")
if log_file.exists():
content = log_file.read_text()
if any(cond in content for cond in conditions):
break
time.sleep(poll_interval)
if sigterm:
print(f"Sending SIGTERM to process {proc.pid}")
proc.send_signal(signal.SIGTERM)
if kill:
print(f"Killing process {proc.pid}")
proc.kill()
try:
proc.wait(timeout=TIMEOUT)
except subprocess.TimeoutExpired:
proc.kill()
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for multi-run RL CI integration tests."""
return f"test-reverse-text-multi-run:{branch_name}"
INFERENCE_PORTS = [8000, 8001]
INFERENCE_BASE_URLS = [f"http://localhost:{port}/v1" for port in INFERENCE_PORTS]
# One env server per run (1:1 with its orchestrator), at that run's base port. A resumed
# run keeps its port, so it reconnects to the same server.
ENV_SERVER_PORTS = {name: 5000 + i for i, name in enumerate(ORCHESTRATOR_NAMES)}
ENV_SERVER_PORTS["alpha_resume"] = ENV_SERVER_PORTS["alpha"]
ENV_SERVER_PORTS["beta_resume"] = ENV_SERVER_PORTS["beta"]
def start_env_server(log_dir: Path, name: str) -> subprocess.Popen:
"""Start one env server for orchestrator `name`, which derives the same address and
connects, polling until the server is up — no readiness wait needed here."""
env_server_log = log_dir / f"env_server_{name}.log"
with open(env_server_log, "w") as f:
return subprocess.Popen(
[
"uv",
"run",
"env-server",
"@",
"configs/ci/integration/reverse-text-multi-run/env.toml",
"--serve.address",
f"tcp://127.0.0.1:{ENV_SERVER_PORTS[name]}",
],
stdout=f,
stderr=f,
)
def start_inference_and_trainer(
log_dir: Path, output_dir: Path, wandb_project: str, wandb_name: str
) -> tuple[subprocess.Popen, list[subprocess.Popen]]:
# Start inference servers (one per GPU on ports 8000 and 8001)
inference_procs: list[subprocess.Popen] = []
inference_logs: list[Path] = []
for i, port in enumerate(INFERENCE_PORTS):
inference_log = log_dir / f"inference_{i}.log"
inference_logs.append(inference_log)
with open(inference_log, "w") as f:
inference_proc = subprocess.Popen(
[
"uv",
"run",
"inference",
"@",
"configs/ci/integration/reverse-text-multi-run/inference.toml",
"--server.port",
str(port),
],
stdout=f,
stderr=f,
env={**os.environ, "VLLM_ALLOW_RUNTIME_LORA_UPDATING": "True", "CUDA_VISIBLE_DEVICES": str(i)},
)
inference_procs.append(inference_proc)
# Start trainer with 2 GPUs
trainer_log = log_dir / "trainer.log"
with open(trainer_log, "w") as f:
trainer_proc = subprocess.Popen(
[
"uv",
"run",
"torchrun",
"--nproc-per-node",
"2",
"-m",
"prime_rl.trainer.rl.train",
"@",
"configs/ci/integration/reverse-text-multi-run/trainer.toml",
"--output-dir",
output_dir.as_posix(),
"--wandb.project",
wandb_project,
"--wandb.name",
f"{wandb_name}-trainer",
"--log.level",
"debug",
],
stdout=f,
stderr=f,
env={**os.environ, "CUDA_VISIBLE_DEVICES": "2,3"},
)
# Wait for all inference servers to be ready
ready_indicators = ["Application startup complete", "Uvicorn running on", "Started server process"]
for i, inference_log in enumerate(inference_logs):
start_time = time.time()
while time.time() - start_time < 300:
if inference_log.exists():
content = inference_log.read_text()
if any(ind in content for ind in ready_indicators):
break
time.sleep(2)
else:
trainer_proc.terminate()
for proc in inference_procs:
proc.terminate()
pytest.fail(f"Inference server {i} did not start in time")
# Wait for trainer to be ready
ready_indicators = ["Starting training loop"]
start_time = time.time()
while time.time() - start_time < 300:
if trainer_log.exists():
content = trainer_log.read_text()
if any(ind in content for ind in ready_indicators):
break
time.sleep(2)
else:
trainer_proc.terminate()
for proc in inference_procs:
proc.terminate()
pytest.fail("Trainer did not start in time")
return trainer_proc, inference_procs
def start_orchestrator(
name: str, max_steps: int, output_dir: Path, wandb_project: str, wandb_name: str, proc_name: str | None = None
):
if proc_name is None:
proc_name = name
print(f"Starting orchestrator {name} with proc name {proc_name}")
run_dir = output_dir / f"run_{name}"
run_dir.mkdir(parents=True, exist_ok=True)
orch_log_dir = run_dir / "logs"
orch_log_dir.mkdir(parents=True, exist_ok=True)
# Build command with multiple inference server URLs
cmd = [
"uv",
"run",
"orchestrator",
"@",
"configs/ci/integration/reverse-text-multi-run/orchestrator.toml",
"--output-dir",
run_dir.as_posix(),
"--max-steps",
str(max_steps),
"--model.lora.name",
name,
"--env-server-base-port",
str(ENV_SERVER_PORTS[name]),
"--wandb.project",
wandb_project,
"--wandb.name",
f"{wandb_name}-{proc_name}",
]
cmd.append("--model.client.base-url")
cmd.extend(INFERENCE_BASE_URLS)
with open(orch_log_dir / "orchestrator.log", "w") as f:
proc = subprocess.Popen(
cmd,
stdout=f,
stderr=f,
)
return proc
@pytest.fixture(scope="module")
def multi_run_result(
output_dir: Path, wandb_project: str, wandb_name: str, tmp_path_factory
) -> Generator[dict[str, ProcessResult], None, None]:
"""
Test multi-run RL with LoRA adapters.
"""
tmp_path: Path = tmp_path_factory.mktemp("prime_rl_test_rl_multi_run_lora")
log_dir = output_dir / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
processes: list[subprocess.Popen] = []
for name in ORCHESTRATOR_NAMES:
processes.append(start_env_server(log_dir, name))
trainer_proc, inference_procs = start_inference_and_trainer(log_dir, output_dir, wandb_project, wandb_name)
processes.append(trainer_proc)
processes.extend(inference_procs)
# ===========================================
# Start alpha, beta, and gamma orchestrators
# -------------------------------------------
orch_procs: dict[str, subprocess.Popen] = {}
for name in ORCHESTRATOR_NAMES:
orch_procs[name] = start_orchestrator(
name, max_steps=20, output_dir=output_dir, wandb_project=wandb_project, wandb_name=wandb_name
)
time.sleep(5)
# ================================================
# Kill alpha orchestrator once it is past step 10
# ------------------------------------------------
# There is a checkpoint at step 10, so we need to wait for step 11
killed_log = output_dir / "run_alpha" / "logs" / "orchestrator.log"
wait_for_log(
killed_log,
conditions=["Step 11", "Step 12", "Step 13"],
proc=orch_procs["alpha"],
sigterm=True,
)
# Wait for trainer checkpoints to be saved (STABLE file indicates checkpoint is complete)
alpha_ckpt_dir = output_dir / "run_alpha" / "checkpoints" / "step_10"
wait_for_file(alpha_ckpt_dir / "STABLE", timeout=TIMEOUT)
# Stash alpha checkpoint and logs
shutil.copy(output_dir / "run_alpha" / "logs" / "orchestrator.log", log_dir / "alpha_orchestrator.log")
shutil.copytree(alpha_ckpt_dir, tmp_path / "alpha_ckpt_step_10")
print(f"Copied alpha checkpoint to {tmp_path / 'alpha_ckpt_step_10'}")
# Remove alpha run directory
remove_run_dir(output_dir / "run_alpha")
# ===========================
# Queue alpha's resume proc
# ---------------------------
# We cant use the same dir in case the trainer misses the change
run_dir = output_dir / "run_alpha_resume"
ckpt_dir = run_dir / "checkpoints" / "step_10"
ckpt_dir.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(tmp_path / "alpha_ckpt_step_10", ckpt_dir)
print(f"Copied alpha checkpoint to {ckpt_dir}")
orch_procs["alpha_resume"] = start_orchestrator(
"alpha_resume", max_steps=20, output_dir=output_dir, wandb_project=wandb_project, wandb_name=wandb_name
)
# ============================================================
# Clear beta run directory once it saves the final checkpoint
# ------------------------------------------------------------
wait_for_log(
output_dir / "run_beta" / "logs" / "orchestrator.log",
conditions=["Orchestrator finished."],
proc=orch_procs["beta"],
poll_interval=1,
)
run_dir = output_dir / "run_beta"
beta_ckpt_dir = run_dir / "checkpoints" / "step_20"
wait_for_file(beta_ckpt_dir / "STABLE", timeout=TIMEOUT)
shutil.copy(run_dir / "logs" / "orchestrator.log", log_dir / "beta_orchestrator.log")
shutil.copytree(beta_ckpt_dir, tmp_path / "beta_ckpt_step_20")
print(f"Copied {beta_ckpt_dir} to {tmp_path / 'beta_ckpt_step_20'}")
remove_run_dir(run_dir)
# =====================
# Queue beta's resume
# ---------------------
run_dir = output_dir / "run_beta_resume"
ckpt_dir = run_dir / "checkpoints" / "step_20"
ckpt_dir.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(tmp_path / "beta_ckpt_step_20", ckpt_dir)
print(f"Copied beta checkpoint to {ckpt_dir}")
orch_procs["beta_resume"] = start_orchestrator(
"beta_resume", max_steps=25, output_dir=output_dir, wandb_project=wandb_project, wandb_name=wandb_name
)
# ===========================================
# Clear gamma run directory once it finishes
# -------------------------------------------
wait_for_log(
output_dir / "run_gamma" / "logs" / "orchestrator.log",
conditions=["Orchestrator finished."],
proc=orch_procs["gamma"],
timeout=TIMEOUT,
)
shutil.copy(output_dir / "run_gamma" / "logs" / "orchestrator.log", log_dir / "gamma_orchestrator.log")
remove_run_dir(output_dir / "run_gamma")
# ================================================
# Wait for alpha_resume and beta_resume to finish
# ------------------------------------------------
for name in ["alpha_resume", "beta_resume"]:
try:
orch_procs[name].wait(timeout=TIMEOUT)
except subprocess.TimeoutExpired:
orch_procs[name].terminate()
for name in ["alpha_resume", "beta_resume"]:
src_log = output_dir / f"run_{name}" / "logs" / "orchestrator.log"
if src_log.exists():
shutil.copy(src_log, log_dir / f"{name}_orchestrator.log")
# ===============
# Build results
# ---------------
results = {name: ProcessResult(orch_procs[name]) for name in orch_procs.keys()}
yield results
# =========
# Cleanup
# ---------
for p in processes:
if p.poll() is None:
p.terminate()
try:
p.wait(timeout=10)
except subprocess.TimeoutExpired:
p.kill()
def test_remaining_orchestrators_complete(
multi_run_result: dict[str, ProcessResult],
output_dir: Path,
):
"""Test that remaining orchestrators complete successfully."""
log_dir = output_dir / "logs"
for name, result in multi_run_result.items():
if name == "alpha": # We sigtermed alpha
continue
if result.returncode != 0:
log_file = log_dir / f"{name}_orchestrator.log"
if log_file.exists():
print(f"=== {name} Orchestrator Outputs ===")
print(log_file.read_text()[-5000:])
assert result.returncode == 0, f"Orchestrator {name} failed with code {result.returncode}"
def test_reward_goes_up(multi_run_result: dict[str, ProcessResult], output_dir: Path):
"""Test that reward goes up for remaining orchestrators."""
log_dir = output_dir / "logs"
print("Test reward goes up", multi_run_result.keys())
for name in multi_run_result.keys():
# The resumes are close to saturation so might not go up
if "resume" in name:
continue
log_file = log_dir / f"{name}_orchestrator.log"
with open(log_file, "r") as f:
lines = strip_escape_codes(f.read()).splitlines()
check_reward_goes_up(lines)
def test_reward_in_range(multi_run_result: dict[str, ProcessResult], output_dir: Path):
"""Test that final reward is in acceptable range for remaining orchestrators."""
log_dir = output_dir / "logs"
print("Test reward in range", multi_run_result.keys())
for name in multi_run_result.keys():
log_file = log_dir / f"{name}_orchestrator.log"
with open(log_file, "r") as f:
lines = strip_escape_codes(f.read()).splitlines()
if name in ["beta", "gamma"]:
check_reward_in_range(lines, step=7, min_threshold=0.2)
check_reward_in_range(lines, min_threshold=0.65)
elif name in ["alpha_resume", "beta_resume"]:
check_reward_in_range(lines, min_threshold=0.65)
elif name == "alpha": # Only had 10 steps, so it's lower
check_reward_in_range(lines, min_threshold=0.4)
else:
pytest.fail(f"Unknown orchestrator {name}")
+1 -1
View File
@@ -13,7 +13,7 @@ from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.orchestrator.types import Rollout
from prime_rl.transport.types import TrainingSample
FROZEN = {"name": "org/ref-model", "base_url": ["http://ref:8001/v1"]}
FROZEN = {"name": "org/ref-model", "base_url": "http://ref:8001/v1"}
_ALGO = pydantic.TypeAdapter(AlgoConfig)
+5 -23
View File
@@ -3,8 +3,7 @@ from types import SimpleNamespace
import numpy as np
import pytest
from prime_rl.trainer.batch import pad_micro_batch, prepare_batch, prepare_sample
from prime_rl.trainer.utils import build_bin_cost
from prime_rl.trainer.batch import _is_multimodal_sample, build_bin_cost, pad_micro_batch, prepare_batch, prepare_sample
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
@@ -104,8 +103,6 @@ def test_prepare_batch_balances_micro_batches_across_workers(
rollouts=examples,
seq_len=4,
num_train_workers=num_train_workers,
idxs=[0] * rollout_count,
num_loras=1,
bin_cost=build_bin_cost(None),
)
@@ -147,8 +144,6 @@ def test_randomized_packing_invariants():
rollouts=examples,
seq_len=seq_len,
num_train_workers=num_train_workers,
idxs=[0] * len(examples),
num_loras=1,
bin_cost=bin_cost,
)
flat_batches = _flatten_batches(batches_per_gpu)
@@ -162,7 +157,6 @@ def test_randomized_packing_invariants():
assert len(batch.input_ids) <= seq_len
assert sum(batch.sequence_lengths) == len(batch.input_ids)
assert batch.seq_lens == batch.sequence_lengths
assert sum(batch.lora_num_tokens) == len(batch.input_ids)
assert len(batch.env_names) == len(batch.input_ids)
for batch in dummy_batches:
@@ -189,8 +183,6 @@ def test_split_to_align_avoids_dummy_micro_batches():
rollouts=examples,
seq_len=12,
num_train_workers=4,
idxs=[0] * len(examples),
num_loras=1,
bin_cost=build_bin_cost(None),
)
@@ -205,8 +197,6 @@ def test_pack_first_then_balance_distributes_micro_batches_by_tokens_without_mod
rollouts=examples,
seq_len=100,
num_train_workers=2,
idxs=[0] * len(examples),
num_loras=1,
bin_cost=build_bin_cost(None),
)
@@ -221,8 +211,6 @@ def test_flop_aware_balancing_pairs_long_and_short_sequence_workloads():
rollouts=examples,
seq_len=32,
num_train_workers=2,
idxs=[0] * len(examples),
num_loras=1,
bin_cost=bin_cost,
)
@@ -238,8 +226,6 @@ def test_flop_aware_split_to_align_splits_heaviest_flop_bin():
rollouts=examples,
seq_len=64,
num_train_workers=4,
idxs=[0] * len(examples),
num_loras=1,
bin_cost=build_bin_cost(make_flops_config()),
)
@@ -258,8 +244,6 @@ def test_prepare_batch_packs_different_temperatures(make_training_example):
rollouts=[example1, example2],
seq_len=16,
num_train_workers=1,
idxs=[0, 0],
num_loras=1,
bin_cost=build_bin_cost(None),
)
@@ -319,8 +303,6 @@ def test_prepare_batch_packs_mixed_components(make_training_example, streams_on_
rollouts=[longer, shorter],
seq_len=16,
num_train_workers=1,
idxs=[0, 0],
num_loras=1,
bin_cost=build_bin_cost(None),
)
@@ -360,8 +342,6 @@ def test_prepare_batch_aligns_ref_logprobs_in_mixed_bins(make_training_example,
seq_len=16,
pad_to_multiple_of=1,
num_train_workers=1,
idxs=[0, 0],
num_loras=1,
bin_cost=build_bin_cost(None),
)
flat_batches = _flatten_batches(batches_per_gpu)
@@ -475,11 +455,13 @@ def test_prepare_batch_packs_multimodal_with_text():
rollouts=[mm_sample, text_sample],
seq_len=8,
num_train_workers=2,
idxs=[0, 0],
num_loras=1,
bin_cost=build_bin_cost(None),
)
# FSDP requires uniform modality at each step index across ranks
for step_mbs in zip(*batches_per_gpu):
assert len({_is_multimodal_sample(mb) for mb in step_mbs}) == 1
real_batches = [batch for batch in _flatten_batches(batches_per_gpu) if _has_loss_tokens(batch)]
assert len(real_batches) == 1
batch = real_batches[0]
@@ -1,6 +1,6 @@
import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
from unittest.mock import MagicMock, patch
from renderers import Qwen3VLRendererConfig
@@ -13,7 +13,7 @@ def test_setup_policy_inference_pool_uses_renderer_when_enabled():
renderer_settings = Qwen3VLRendererConfig()
config = SimpleNamespace(
model=SimpleNamespace(
client=SimpleNamespace(base_url=["http://localhost:8000/v1"]),
client=SimpleNamespace(base_url="http://localhost:8000/v1"),
name="policy-model",
),
renderer=renderer_settings,
@@ -25,8 +25,8 @@ def test_setup_policy_inference_pool_uses_renderer_when_enabled():
with (
patch("renderers.base.create_renderer", return_value=renderer) as create_renderer_mock,
patch(
"prime_rl.orchestrator.utils.setup_inference_pool",
new=AsyncMock(return_value=inference_pool),
"prime_rl.orchestrator.utils.InferencePool",
new=MagicMock(return_value=inference_pool),
) as setup_pool_mock,
):
returned_renderer, returned_pool = await setup_policy_inference_pool(
@@ -37,7 +37,7 @@ def test_setup_policy_inference_pool_uses_renderer_when_enabled():
assert returned_renderer is renderer
assert returned_pool is inference_pool
create_renderer_mock.assert_called_once_with(tokenizer, renderer_settings)
setup_pool_mock.assert_awaited_once_with(
setup_pool_mock.assert_called_once_with(
config.model.client,
model_name="policy-model",
train_client_type="renderer",
@@ -59,7 +59,7 @@ def test_setup_policy_inference_pool_keeps_renderer_without_policy_sampling():
renderer_settings = Qwen3VLRendererConfig()
config = SimpleNamespace(
model=SimpleNamespace(
client=SimpleNamespace(base_url=["http://localhost:8000/v1"]),
client=SimpleNamespace(base_url="http://localhost:8000/v1"),
name="policy-model",
),
renderer=renderer_settings,
@@ -71,8 +71,8 @@ def test_setup_policy_inference_pool_keeps_renderer_without_policy_sampling():
with (
patch("renderers.base.create_renderer", return_value=renderer) as create_renderer_mock,
patch(
"prime_rl.orchestrator.utils.setup_inference_pool",
new=AsyncMock(return_value=inference_pool),
"prime_rl.orchestrator.utils.InferencePool",
new=MagicMock(return_value=inference_pool),
) as setup_pool_mock,
):
returned_renderer, returned_pool = await setup_policy_inference_pool(
@@ -83,7 +83,7 @@ def test_setup_policy_inference_pool_keeps_renderer_without_policy_sampling():
assert returned_renderer is renderer
assert returned_pool is inference_pool
create_renderer_mock.assert_called_once_with(tokenizer, renderer_settings)
setup_pool_mock.assert_awaited_once_with(
setup_pool_mock.assert_called_once_with(
config.model.client,
model_name="policy-model",
train_client_type="renderer",
+1 -1
View File
@@ -559,7 +559,7 @@ def test_shared_output_dir_propagates_through_cli(tmp_path):
shared_out = tmp_path / "shared"
config = cli(RLConfig, args=["@", str(toml_path), "--output-dir", str(shared_out)])
assert config.trainer.output_dir == shared_out
assert config.orchestrator.output_dir == shared_out / "run_default"
assert config.orchestrator.output_dir == shared_out
def test_orchestrator_renderer_auto_rejects_unmapped_model():
-240
View File
@@ -1,240 +0,0 @@
from pathlib import Path
from typing import Generator
import numpy as np
import pytest
import tomli_w
import torch
import torch.distributed as dist
import prime_rl.trainer.runs as runs
from prime_rl.configs.shared import FileSystemTransportConfig
from prime_rl.trainer.rl.packer import MultiPacker
from prime_rl.trainer.runs import setup_multi_run_manager
from prime_rl.trainer.utils import build_bin_cost
from prime_rl.trainer.world import reset_world
from prime_rl.transport.types import EncodedTensor, TrainingSample
@pytest.fixture(autouse=True, scope="module")
def init_process_group() -> Generator[None, None, None]:
dist.init_process_group(backend="gloo", init_method="tcp://localhost:12356", rank=0, world_size=1)
yield
dist.destroy_process_group()
def create_run_with_config(output_dir: Path, run_name: str) -> Path:
run_dir = output_dir / run_name
run_dir.mkdir()
control_dir = run_dir / "control"
control_dir.mkdir()
config = {
"model": {"name": "test-model"},
"batch_size": 2,
"group_size": 1,
"train": {"source": [{"legacy": {"id": "test-env"}}], "sampling": {"temperature": 1.0}},
# test-model isn't in MODEL_RENDERER_MAP; use the explicit default renderer.
"renderer": {"name": "default"},
}
with open(control_dir / "orch.toml", "wb") as f:
tomli_w.dump(config, f)
return run_dir
def make_training_sample() -> TrainingSample:
return TrainingSample(
token_ids=[1, 2],
mask=[False, True],
logprobs=[0.0, -0.1],
temperatures=[1.0, 1.0],
advantages=[0.0, 1.0],
env_name="test-env",
)
def _encoded_tensor(data, dtype) -> EncodedTensor:
arr = np.asarray(data, dtype=dtype)
return EncodedTensor(dtype=str(arr.dtype), shape=list(arr.shape), data=arr.tobytes())
def _decode_encoded_tensor(encoded: EncodedTensor):
return np.frombuffer(encoded.data, dtype=np.dtype(encoded.dtype)).reshape(encoded.shape).tolist()
def _mm_sample(value: float, env_name: str = "test-env") -> TrainingSample:
return TrainingSample(
token_ids=[1, 250, 2],
mask=[False, True, True],
logprobs=[0.0, -0.1, -0.2],
temperatures=[1.0, 1.0, 1.0],
env_name=env_name,
advantages=[0.0, 1.0, 1.0],
mm_token_type_ids=[0, 1, 0],
mm_kwargs={
"pixel_values": _encoded_tensor([[value, value + 1]], np.float32),
"image_grid_thw": _encoded_tensor([[1, 2, 2]], np.int64),
},
)
def _packer_with_two_runs(tmp_path, monkeypatch, dp_world_size, seq_len):
"""Set up a MultiPacker over two discovered runs; capture sent grids."""
reset_world()
runs._MULTI_RUN_MANAGER = None
manager = setup_multi_run_manager(output_dir=tmp_path, max_runs=2, device=torch.device("cpu"))
create_run_with_config(tmp_path, "run_a")
create_run_with_config(tmp_path, "run_b")
manager.discover_runs()
sent: list = []
class DummyReceiver:
def receive(self):
return []
def reset_run(self, idx):
pass
class DummySender:
def send(self, micro_batch_grid):
sent.append(micro_batch_grid)
monkeypatch.setattr("prime_rl.trainer.rl.packer.setup_training_batch_receiver", lambda _c: DummyReceiver())
monkeypatch.setattr("prime_rl.trainer.rl.packer.setup_micro_batch_sender", lambda *a, **k: DummySender())
packer = MultiPacker(
dp_world_size=dp_world_size,
seq_len=seq_len,
pad_to_multiple_of=1,
config=FileSystemTransportConfig(),
bin_cost=build_bin_cost(None),
start_step=0,
)
return manager, packer, sent
def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
reset_world()
runs._MULTI_RUN_MANAGER = None
manager = setup_multi_run_manager(output_dir=tmp_path, max_runs=1, device=torch.device("cpu"))
create_run_with_config(tmp_path, "run_test123")
manager.discover_runs()
run_idx = manager.id_2_idx["run_test123"]
class DummyReceiver:
def receive(self):
return []
def reset_run(self, idx: int) -> None:
pass
class DummySender:
def __init__(self):
self.sent = []
def send(self, micro_batch_grid):
self.sent.append(micro_batch_grid)
sender_holder: dict[str, DummySender] = {}
def fake_receiver(_config):
return DummyReceiver()
def fake_sender(_output_dir, _data_world_size, _current_step, _config):
sender = DummySender()
sender_holder["sender"] = sender
return sender
monkeypatch.setattr("prime_rl.trainer.rl.packer.setup_training_batch_receiver", fake_receiver)
monkeypatch.setattr("prime_rl.trainer.rl.packer.setup_micro_batch_sender", fake_sender)
packer = MultiPacker(
dp_world_size=1,
seq_len=4,
pad_to_multiple_of=1,
config=FileSystemTransportConfig(),
bin_cost=build_bin_cost(None),
start_step=0,
)
# Steps are 1-indexed: a fresh run starts at step 1, so the first batch's samples carry step 1.
packer.buffers[run_idx].append((make_training_sample(), 1))
packer.buffers[run_idx].append((make_training_sample(), 1))
packer.pack()
progress = manager.progress[run_idx]
assert progress.total_samples == 2
assert progress.total_tokens == 4
assert progress.step == 2
sender = sender_holder["sender"]
assert len(sender.sent) == 1
assert len(sender.sent[0][0]) == 1
micro_batch = sender.sent[0][0][0]
assert micro_batch.run_id == "run_test123"
assert micro_batch.run_step == 1
def test_multipacker_pack_preserves_mm_kwargs_modality_and_run_tagging(tmp_path, monkeypatch):
"""MultiPacker keeps multimodal and text microbatches aligned across ranks."""
from prime_rl.trainer.batch import _is_multimodal_sample
manager, packer, sent = _packer_with_two_runs(tmp_path, monkeypatch, dp_world_size=2, seq_len=5)
malformed = _mm_sample(0.0)
malformed.mm_token_type_ids = None
valid, reason = packer._validate_sample(malformed)
assert not valid
assert reason is not None and "require mm_token_type_ids" in reason
a, b = manager.id_2_idx["run_a"], manager.id_2_idx["run_b"]
for idx, value in ((a, 1.0), (b, 10.0)):
packer.buffers[idx].append((_mm_sample(value), 0))
packer.buffers[idx].append((make_training_sample(), 0))
packer.pack()
assert sent, "pack() sent nothing"
grid = sent[-1]
assert len(grid) == 2
for step_mbs in zip(*grid):
assert len({_is_multimodal_sample(mb) for mb in step_mbs}) == 1
mm_mbs = [mb for rank in grid for mb in rank if _is_multimodal_sample(mb)]
assert mm_mbs, "no MM microbatches produced"
real_run_idxs = set()
for mb in mm_mbs:
assert mb.mm_kwargs is not None
if any(mb.loss_mask):
tagged = [i for i, n in enumerate(mb.lora_num_tokens) if n > 0]
assert len(tagged) == 1 and mb.lora_num_tokens[tagged[0]] == len(mb.input_ids)
real_run_idxs.add(tagged[0])
assert real_run_idxs == {a, b}, f"both runs' MM should be tagged; got {real_run_idxs}"
def test_multipacker_packs_mm_kwargs_within_each_run(tmp_path, monkeypatch):
"""Compatible eager multimodal samples pack within a run but never across runs."""
from prime_rl.trainer.batch import _is_multimodal_sample
manager, packer, sent = _packer_with_two_runs(tmp_path, monkeypatch, dp_world_size=1, seq_len=12)
a, b = manager.id_2_idx["run_a"], manager.id_2_idx["run_b"]
for idx, base in ((a, 1.0), (b, 10.0)):
packer.buffers[idx].append((_mm_sample(base), 0))
packer.buffers[idx].append((_mm_sample(base + 2), 0))
packer.pack()
assert sent
grid = sent[-1]
real_mm_mbs = [mb for rank in grid for mb in rank if _is_multimodal_sample(mb) and any(mb.loss_mask)]
assert len(real_mm_mbs) == 2
for mb in real_mm_mbs:
assert len(mb.input_ids) == 6
assert mb.position_ids == [0, 1, 2, 0, 1, 2]
assert mb.seq_lens == [3, 3]
assert mb.mm_kwargs is not None
assert mb.mm_kwargs["pixel_values"].shape == [2, 2]
assert mb.mm_kwargs["image_grid_thw"].shape == [2, 3]
assert len(_decode_encoded_tensor(mb.mm_kwargs["pixel_values"])) == 2
tagged = [i for i, n in enumerate(mb.lora_num_tokens) if n > 0]
assert len(tagged) == 1
-339
View File
@@ -1,339 +0,0 @@
from pathlib import Path
from typing import Generator
import pytest
import tomli_w
import torch.distributed as dist
from prime_rl.trainer.runs import MultiRunManager
@pytest.fixture(autouse=True, scope="module")
def init_process_group() -> Generator[None, None, None]:
"""Initialize and destroy GLOO process group for each test."""
dist.init_process_group(backend="gloo", init_method="tcp://localhost:12355", rank=0, world_size=1)
yield
dist.destroy_process_group()
def create_run_with_config(
output_dir: Path,
run_name: str,
config: dict[str, object] | None = None,
) -> Path:
"""Helper function to create a run directory with a valid config.
Args:
output_dir: Parent directory where the run will be created
run_name: Name of the run directory (e.g., 'run_abc123')
config: Optional config dict. If None, uses a default valid config.
Returns:
Path to the created run directory
"""
run_dir = output_dir / run_name
run_dir.mkdir()
config_dir = run_dir / "control"
config_dir.mkdir()
if config is None:
config = {
"model": {"name": "test-model"},
"batch_size": 32,
"group_size": 4,
"train": {"source": [{"legacy": {"id": "test-env"}}]},
# test-model isn't in MODEL_RENDERER_MAP; use the explicit default renderer.
"renderer": {"name": "default"},
}
with open(config_dir / "orch.toml", "wb") as f:
tomli_w.dump(config, f)
return run_dir
def test_initial_state(tmp_path: Path) -> None:
"""Test that MultiRunManager initializes correctly."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
assert multi_run_manager.output_dir == tmp_path
assert multi_run_manager.max_runs == 5
assert len(multi_run_manager.idx_2_id) == 0
assert len(multi_run_manager.id_2_idx) == 0
assert len(multi_run_manager.unused_idxs) == 5
assert multi_run_manager.run_dirs() == []
def test_detect_new_runs(tmp_path: Path) -> None:
"""Test that new runs are detected correctly."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
# Create some run directories with valid configs
for run_name in ["run_abc123", "run_def456"]:
create_run_with_config(tmp_path, run_name)
# Check for changes
multi_run_manager.discover_runs()
# Verify runs were detected
assert len(multi_run_manager.id_2_idx) == 2
assert len(multi_run_manager.idx_2_id) == 2
assert "run_abc123" in multi_run_manager.id_2_idx
assert "run_def456" in multi_run_manager.id_2_idx
# Verify indices are assigned from available pool
assert len(multi_run_manager.unused_idxs) == 3 # 5 - 2 = 3
assert multi_run_manager.id_2_idx["run_abc123"] in range(5)
assert multi_run_manager.id_2_idx["run_def456"] in range(5)
# Verify bidirectional mapping
idx1 = multi_run_manager.id_2_idx["run_abc123"]
idx2 = multi_run_manager.id_2_idx["run_def456"]
assert multi_run_manager.idx_2_id[idx1] == "run_abc123"
assert multi_run_manager.idx_2_id[idx2] == "run_def456"
def test_detect_deleted_runs(tmp_path: Path) -> None:
"""Test that deleted runs are detected correctly."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
# Create run directories with valid configs
for run_name in ["run_abc123", "run_def456"]:
create_run_with_config(tmp_path, run_name)
# Detect initial runs
multi_run_manager.discover_runs()
initial_idx1 = multi_run_manager.id_2_idx["run_abc123"]
initial_idx2 = multi_run_manager.id_2_idx["run_def456"]
assert len(multi_run_manager.id_2_idx) == 2
assert len(multi_run_manager.unused_idxs) == 3
# Delete one run
run1 = tmp_path / "run_abc123"
import shutil
shutil.rmtree(run1)
multi_run_manager.discover_runs()
# Verify run was removed
assert len(multi_run_manager.id_2_idx) == 1
assert len(multi_run_manager.idx_2_id) == 1
assert "run_abc123" not in multi_run_manager.id_2_idx
assert "run_def456" in multi_run_manager.id_2_idx
assert initial_idx1 not in multi_run_manager.idx_2_id
# Verify index was returned to unused pool
assert len(multi_run_manager.unused_idxs) == 4
assert initial_idx1 in multi_run_manager.unused_idxs
assert initial_idx2 not in multi_run_manager.unused_idxs
def test_max_runs_limit(tmp_path: Path) -> None:
"""Test that only max_runs are tracked."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=2)
# Create more runs than max_runs with valid configs
for run_name in ["run_001", "run_002", "run_003"]:
create_run_with_config(tmp_path, run_name)
multi_run_manager.discover_runs()
# Only max_runs should be tracked
assert len(multi_run_manager.id_2_idx) == 2
assert len(multi_run_manager.idx_2_id) == 2
assert len(multi_run_manager.unused_idxs) == 0
to_delete_run = multi_run_manager.get_run_dir(0)
import shutil
shutil.rmtree(to_delete_run)
multi_run_manager.discover_runs()
assert len(multi_run_manager.id_2_idx) == 2
assert len(multi_run_manager.idx_2_id) == 2
assert len(multi_run_manager.unused_idxs) == 0
assert to_delete_run not in multi_run_manager.run_dirs()
def test_run_dirs(tmp_path: Path) -> None:
"""Test that run_dirs returns correct paths."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
# Create run directories with valid configs
for run_name in ["run_abc", "run_def"]:
create_run_with_config(tmp_path, run_name)
multi_run_manager.discover_runs()
run_dirs = multi_run_manager.run_dirs()
assert len(run_dirs) == 2
assert tmp_path / "run_abc" in run_dirs
assert tmp_path / "run_def" in run_dirs
def test_non_run_directories_ignored(tmp_path: Path) -> None:
"""Test that non-run directories are ignored."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
# Create mix of run and non-run directories
create_run_with_config(tmp_path, "run_abc")
(tmp_path / "other_dir").mkdir()
(tmp_path / "random").mkdir()
multi_run_manager.discover_runs()
# Only run_* directories should be tracked
assert len(multi_run_manager.id_2_idx) == 1
assert "run_abc" in multi_run_manager.id_2_idx
assert "other_dir" not in multi_run_manager.id_2_idx
assert "random" not in multi_run_manager.id_2_idx
def test_config_loading(tmp_path: Path) -> None:
"""Test that orchestrator configs are loaded correctly."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
# Create a run directory with config
test_config = {
"model": {"name": "test-model"},
"batch_size": 32,
"max_steps": 1000,
"group_size": 4,
"train": {"source": [{"legacy": {"id": "test-env"}}]},
"renderer": {"name": "default"},
}
create_run_with_config(tmp_path, "run_test123", config=test_config)
# Detect the run
multi_run_manager.discover_runs()
# Verify config was loaded and parsed as OrchestratorConfig
assert len(multi_run_manager.config) == 1
run_idx = multi_run_manager.id_2_idx["run_test123"]
assert run_idx in multi_run_manager.config
# Access config as OrchestratorConfig object
config = multi_run_manager.config[run_idx]
assert config.model.name == "test-model"
assert config.batch_size == 32
assert config.max_steps == 1000
def test_config_missing(tmp_path: Path) -> None:
"""Test that runs without configs are skipped and config_validation_error.txt is created."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
# Create a run directory without config
run_dir = tmp_path / "run_noconfig"
run_dir.mkdir()
# Detect the run
multi_run_manager.discover_runs()
# Verify run was not added
assert len(multi_run_manager.config) == 0
assert "run_noconfig" not in multi_run_manager.id_2_idx
def test_config_cleanup_on_deletion(tmp_path: Path) -> None:
"""Test that configs are cleaned up when runs are deleted."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
# Create a run directory with valid config
test_config = {
"model": {"name": "test-model"},
"batch_size": 16,
"group_size": 4,
"train": {"source": [{"legacy": {"id": "test-env"}}]},
"renderer": {"name": "default"},
}
run_dir = create_run_with_config(tmp_path, "run_delete_me", config=test_config)
# Detect the run
multi_run_manager.discover_runs()
run_idx = multi_run_manager.id_2_idx["run_delete_me"]
assert run_idx in multi_run_manager.config
# Delete the run directory
import shutil
shutil.rmtree(run_dir)
multi_run_manager.discover_runs()
# Verify config was cleaned up
assert run_idx not in multi_run_manager.config
assert "run_delete_me" not in multi_run_manager.id_2_idx
def test_config_invalid(tmp_path: Path) -> None:
"""Test that runs with invalid configs are skipped and config_validation_error.txt is created."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
# Create a run directory with invalid config (invalid type for a field)
# Invalid config - batch_size should be int, not string
invalid_config = {
"model": {"name": "test-model"},
"batch_size": "not-a-number", # Invalid type
"group_size": 4,
"train": {"source": [{"legacy": {"id": "test-env"}}]},
}
run_dir = create_run_with_config(tmp_path, "run_invalid", config=invalid_config)
config_dir = run_dir / "control"
# Detect the run
multi_run_manager.discover_runs()
# Verify run was not added
assert len(multi_run_manager.config) == 0
assert "run_invalid" not in multi_run_manager.id_2_idx
# Verify config_validation_error.txt was created with error details
error_path = config_dir / "config_validation_error.txt"
assert error_path.exists()
error_content = error_path.read_text()
assert "Error parsing orchestrator config" in error_content
def test_evict_run_writes_file(tmp_path: Path) -> None:
"""Test that evict_run writes the eviction reason to the correct file."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
# Create a run directory with valid config
create_run_with_config(tmp_path, "run_to_evict")
multi_run_manager.discover_runs()
# Get the run index
run_idx = multi_run_manager.id_2_idx["run_to_evict"]
# Evict the run
eviction_reason = "Test eviction reason"
multi_run_manager.evict_run(run_idx, eviction_reason)
# Verify evicted.txt was created with the reason
evicted_path = tmp_path / "run_to_evict" / "control" / "evicted.txt"
assert evicted_path.exists()
assert evicted_path.read_text() == eviction_reason
def test_discover_runs_ignores_evicted(tmp_path: Path) -> None:
"""Test that discover_runs ignores runs with evicted.txt."""
multi_run_manager = MultiRunManager(output_dir=tmp_path, max_runs=5)
# Create two run directories
create_run_with_config(tmp_path, "run_normal")
create_run_with_config(tmp_path, "run_evicted")
# Mark one as evicted by creating evicted.txt
evicted_path = tmp_path / "run_evicted" / "control" / "evicted.txt"
evicted_path.write_text("Previously evicted")
# Discover runs
multi_run_manager.discover_runs()
# Only the normal run should be discovered
assert len(multi_run_manager.id_2_idx) == 1
assert "run_normal" in multi_run_manager.id_2_idx
assert "run_evicted" not in multi_run_manager.id_2_idx
+22 -27
View File
@@ -6,7 +6,7 @@ import httpx
from verifiers.v1.configs.client import EvalClientConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.client import _is_retryable_lora_error, check_health, load_lora_adapter, setup_clients
from prime_rl.utils.client import _is_retryable_lora_error, check_health, load_lora_adapter, setup_client
def test_is_retryable_lora_error_returns_true_for_404():
@@ -49,32 +49,29 @@ def test_load_lora_adapter_succeeds_on_first_attempt():
)
def test_setup_clients_creates_one_renderer_client_per_url():
def test_setup_client_creates_renderer_client():
from renderers import Qwen3VLRendererConfig
client_config = ClientConfig(
base_url=["http://worker-a:8000/v1", "http://worker-b:8000/v1"],
base_url="http://worker-a:8000/v1",
api_key_var="PRIME_API_KEY",
headers={"X-Test": "test"},
extra_headers_from_state={"X-Session-ID": "session_id"},
)
renderer_settings = Qwen3VLRendererConfig()
clients = setup_clients(
client = setup_client(
client_config,
client_type="renderer",
renderer_config=renderer_settings,
)
assert [client.type for client in clients] == ["train", "train"]
assert [client.renderer for client in clients] == [renderer_settings, renderer_settings]
assert [client.renderer_model_name for client in clients] == [None, None]
assert [client.base_url for client in clients] == [
"http://worker-a:8000/v1",
"http://worker-b:8000/v1",
]
assert all("X-data-parallel-rank" not in client.headers for client in clients)
assert clients[0].headers["X-Test"] == "test"
assert client.type == "train"
assert client.renderer == renderer_settings
assert client.renderer_model_name is None
assert client.base_url == "http://worker-a:8000/v1"
assert "X-data-parallel-rank" not in client.headers
assert client.headers["X-Test"] == "test"
def test_check_health_retries_non_success_status():
@@ -90,36 +87,34 @@ def test_check_health_retries_non_success_status():
assert client.get.await_count == 2
def test_setup_clients_assigns_renderer_model_name():
def test_setup_client_assigns_renderer_model_name():
from renderers import Qwen3VLRendererConfig
client_config = ClientConfig(
base_url=["http://worker-a:8000/v1"],
base_url="http://worker-a:8000/v1",
api_key_var="PRIME_API_KEY",
)
clients = setup_clients(
client = setup_client(
client_config,
client_type="renderer",
renderer_config=Qwen3VLRendererConfig(),
renderer_model_name="Qwen/Qwen3-VL-4B-Instruct",
)
assert clients[0].renderer_model_name == "Qwen/Qwen3-VL-4B-Instruct"
assert client.renderer_model_name == "Qwen/Qwen3-VL-4B-Instruct"
def test_setup_clients_preserves_chat_client_defaults():
def test_setup_client_preserves_chat_client_defaults():
client_config = ClientConfig(
base_url=["http://worker-a:8000/v1"],
base_url="http://worker-a:8000/v1",
api_key_var="PRIME_API_KEY",
)
clients = setup_clients(client_config)
client = setup_client(client_config)
assert clients == [
EvalClientConfig(
api_key_var="PRIME_API_KEY",
base_url="http://worker-a:8000/v1",
headers={},
)
]
assert client == EvalClientConfig(
api_key_var="PRIME_API_KEY",
base_url="http://worker-a:8000/v1",
headers={},
)
-444
View File
@@ -1,444 +0,0 @@
import asyncio
import socket
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
from verifiers.v1.configs.client import TrainClientConfig
from prime_rl.utils.elastic import (
AdapterState,
ElasticInferencePool,
check_server_model,
discover_ready_servers,
discover_server_ips,
)
# discover_server_ips tests
def test_discover_server_ips_returns_sorted_ips():
with patch("socket.gethostbyname_ex") as mock_dns:
mock_dns.return_value = ("hostname", [], ["10.0.0.3", "10.0.0.1", "10.0.0.2"])
result = discover_server_ips("test.hostname")
assert result == ["10.0.0.1", "10.0.0.2", "10.0.0.3"]
def test_discover_server_ips_returns_empty_list_on_dns_failure():
with patch("socket.gethostbyname_ex") as mock_dns:
mock_dns.side_effect = socket.gaierror("DNS lookup failed")
result = discover_server_ips("nonexistent.hostname")
assert result == []
def test_discover_server_ips_returns_single_ip():
with patch("socket.gethostbyname_ex") as mock_dns:
mock_dns.return_value = ("hostname", [], ["10.0.0.1"])
result = discover_server_ips("single.hostname")
assert result == ["10.0.0.1"]
# check_server_model tests
def test_check_server_model_returns_true_when_model_found():
with patch("httpx.AsyncClient") as mock_client_class:
mock_client = AsyncMock()
mock_client_class.return_value.__aenter__.return_value = mock_client
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_response.json.return_value = {"data": [{"id": "model-a"}, {"id": "model-b"}]}
mock_client.get.return_value = mock_response
has_model, is_healthy = asyncio.run(check_server_model("http://10.0.0.1:8000", "model-a"))
assert has_model is True
assert is_healthy is True
def test_check_server_model_returns_false_when_model_not_found():
with patch("httpx.AsyncClient") as mock_client_class:
mock_client = AsyncMock()
mock_client_class.return_value.__aenter__.return_value = mock_client
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_response.json.return_value = {"data": [{"id": "other-model"}]}
mock_client.get.return_value = mock_response
has_model, is_healthy = asyncio.run(check_server_model("http://10.0.0.1:8000", "model-a"))
assert has_model is False
assert is_healthy is True
def test_check_server_model_returns_false_on_connection_error():
with patch("httpx.AsyncClient") as mock_client_class:
mock_client = AsyncMock()
mock_client_class.return_value.__aenter__.return_value = mock_client
mock_client.get.side_effect = httpx.ConnectError("Connection refused")
has_model, is_healthy = asyncio.run(check_server_model("http://10.0.0.1:8000", "model-a"))
assert has_model is False
assert is_healthy is False
def test_check_server_model_returns_false_on_http_error():
with patch("httpx.AsyncClient") as mock_client_class:
mock_client = AsyncMock()
mock_client_class.return_value.__aenter__.return_value = mock_client
mock_response = MagicMock()
mock_response.status_code = 500
mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(
"Server error", request=MagicMock(), response=mock_response
)
mock_client.get.return_value = mock_response
has_model, is_healthy = asyncio.run(check_server_model("http://10.0.0.1:8000", "model-a"))
assert has_model is False
assert is_healthy is False
# discover_ready_servers tests
def test_discover_ready_servers_returns_servers_with_model_when_any_have_it():
with (
patch("prime_rl.utils.elastic.discover_server_ips") as mock_discover,
patch("prime_rl.utils.elastic.check_server_model") as mock_check,
):
mock_discover.return_value = ["10.0.0.1", "10.0.0.2", "10.0.0.3"]
async def mock_check_impl(url, model_name):
if "10.0.0.1" in url:
return True, True # has model, healthy
elif "10.0.0.2" in url:
return False, True # no model, healthy
else:
return False, True # no model, healthy
mock_check.side_effect = mock_check_impl
result = asyncio.run(discover_ready_servers("test.hostname", 8000, "my-lora"))
assert result == ["http://10.0.0.1:8000/v1"]
def test_discover_ready_servers_returns_empty_when_none_have_model():
with (
patch("prime_rl.utils.elastic.discover_server_ips") as mock_discover,
patch("prime_rl.utils.elastic.check_server_model") as mock_check,
):
mock_discover.return_value = ["10.0.0.1", "10.0.0.2"]
mock_check.return_value = (False, True) # no model, but healthy
result = asyncio.run(discover_ready_servers("test.hostname", 8000, "my-lora"))
assert result == [] # No servers have the model, so return empty
def test_discover_ready_servers_returns_empty_when_no_dns_records():
with patch("prime_rl.utils.elastic.discover_server_ips") as mock_discover:
mock_discover.return_value = []
result = asyncio.run(discover_ready_servers("test.hostname", 8000, "my-lora"))
assert result == []
def test_discover_ready_servers_only_returns_servers_with_model():
with (
patch("prime_rl.utils.elastic.discover_server_ips") as mock_discover,
patch("prime_rl.utils.elastic.check_server_model") as mock_check,
):
mock_discover.return_value = ["10.0.0.1", "10.0.0.2"]
async def mock_check_impl(url, model_name):
if "10.0.0.1" in url:
return True, True # has model, healthy
else:
return False, True # no model, healthy
mock_check.side_effect = mock_check_impl
result = asyncio.run(discover_ready_servers("test.hostname", 8000, "my-lora"))
# Only returns servers that have the model
assert result == ["http://10.0.0.1:8000/v1"]
# AdapterState tests
def test_adapter_state_creation():
adapter = AdapterState(name="my-lora", path=Path("/weights/step_100"), step=100)
assert adapter.name == "my-lora"
assert adapter.path == Path("/weights/step_100")
assert adapter.step == 100
# ElasticInferencePool adapter matching tests
def test_adapter_matches_when_no_adapter_desired():
with patch("prime_rl.utils.elastic.get_logger"):
mock_config = MagicMock()
mock_config.elastic.hostname = "test.hostname"
mock_config.elastic.port = 8000
mock_config.elastic.sync_interval = 5.0
mock_config.router_url = None
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
# No adapter desired (base model inference)
assert pool._adapter_matches_desired(None) is True
assert pool._adapter_matches_desired(AdapterState("x", Path("/x"), 0)) is True
def test_adapter_matches_by_path():
with patch("prime_rl.utils.elastic.get_logger"):
mock_config = MagicMock()
mock_config.elastic.hostname = "test.hostname"
mock_config.elastic.port = 8000
mock_config.elastic.sync_interval = 5.0
mock_config.router_url = None
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
pool._desired.path = Path("/weights/step_100")
pool._desired.step = 100
loaded = AdapterState(name="lora", path=Path("/weights/step_100"), step=100)
assert pool._adapter_matches_desired(loaded) is True
loaded_wrong_path = AdapterState(name="lora", path=Path("/weights/step_50"), step=50)
assert pool._adapter_matches_desired(loaded_wrong_path) is False
def test_adapter_matches_by_step_when_nonzero():
with patch("prime_rl.utils.elastic.get_logger"):
mock_config = MagicMock()
mock_config.elastic.hostname = "test.hostname"
mock_config.elastic.port = 8000
mock_config.elastic.sync_interval = 5.0
mock_config.router_url = None
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
pool._desired.path = Path("/weights/step_100")
pool._desired.step = 100
# Different path but same step
loaded = AdapterState(name="lora", path=Path("/other/path"), step=100)
assert pool._adapter_matches_desired(loaded) is True
def test_adapter_does_not_match_by_zero_step():
with patch("prime_rl.utils.elastic.get_logger"):
mock_config = MagicMock()
mock_config.elastic.hostname = "test.hostname"
mock_config.elastic.port = 8000
mock_config.elastic.sync_interval = 5.0
mock_config.router_url = None
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
pool._desired.path = Path("/weights/step_0")
pool._desired.step = 0
# Step 0 should not match by step alone (avoid false positives)
loaded = AdapterState(name="lora", path=Path("/other/path"), step=0)
assert pool._adapter_matches_desired(loaded) is False
def test_adapter_returns_false_when_no_adapter_loaded():
with patch("prime_rl.utils.elastic.get_logger"):
mock_config = MagicMock()
mock_config.elastic.hostname = "test.hostname"
mock_config.elastic.port = 8000
mock_config.elastic.sync_interval = 5.0
mock_config.router_url = None
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
pool._desired.path = Path("/weights/step_100")
pool._desired.step = 100
assert pool._adapter_matches_desired(None) is False
# _get_loaded_adapter tests
def test_get_loaded_adapter_finds_correct_adapter_when_multiple_loaded():
"""Test that _get_loaded_adapter returns the adapter matching desired name, not the first one."""
with patch("prime_rl.utils.elastic.get_logger"):
mock_config = MagicMock()
mock_config.elastic.hostname = "test.hostname"
mock_config.elastic.port = 8000
mock_config.elastic.sync_interval = 5.0
mock_config.router_url = None
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
# Set the desired adapter name
pool._desired.name = "rft-target-run"
pool._desired.path = Path("/data/outputs/target_run/broadcasts/step_10")
pool._desired.step = 10
# Mock admin client with multiple adapters (like the real scenario)
mock_admin = AsyncMock()
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
# Simulates vLLM response with multiple adapters from different runs
mock_response.json.return_value = {
"data": [
{
"id": "base-model",
"parent": None,
"root": "base-model",
},
{
"id": "rft-other-run", # Different run's adapter (comes first!)
"parent": "base-model",
"root": "/data/outputs/other_run/broadcasts/step_48",
},
{
"id": "rft-target-run", # Our desired adapter
"parent": "base-model",
"root": "/data/outputs/target_run/broadcasts/step_10",
},
]
}
mock_admin.get.return_value = mock_response
pool._admin_clients["10.0.0.1"] = mock_admin
result = asyncio.run(pool._get_loaded_adapter("10.0.0.1"))
# Should return our target adapter, not the first one found
assert result is not None
assert result.name == "rft-target-run"
assert result.path == Path("/data/outputs/target_run/broadcasts/step_10")
assert result.step == 10
def test_get_loaded_adapter_returns_none_when_desired_adapter_not_found():
"""Test that _get_loaded_adapter returns None when desired adapter is not in the list."""
with patch("prime_rl.utils.elastic.get_logger"):
mock_config = MagicMock()
mock_config.elastic.hostname = "test.hostname"
mock_config.elastic.port = 8000
mock_config.elastic.sync_interval = 5.0
mock_config.router_url = None
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
pool._desired.name = "rft-missing-run"
pool._desired.path = Path("/data/outputs/missing_run/broadcasts/step_5")
pool._desired.step = 5
mock_admin = AsyncMock()
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_response.json.return_value = {
"data": [
{"id": "base-model", "parent": None, "root": "base-model"},
{"id": "rft-other-run", "parent": "base-model", "root": "/data/outputs/other_run/step_10"},
]
}
mock_admin.get.return_value = mock_response
pool._admin_clients["10.0.0.1"] = mock_admin
result = asyncio.run(pool._get_loaded_adapter("10.0.0.1"))
assert result is None
def test_get_loaded_adapter_parses_step_from_path():
"""Test that _get_loaded_adapter correctly parses step number from path."""
with patch("prime_rl.utils.elastic.get_logger"):
mock_config = MagicMock()
mock_config.elastic.hostname = "test.hostname"
mock_config.elastic.port = 8000
mock_config.elastic.sync_interval = 5.0
mock_config.router_url = None
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
pool._desired.name = "my-lora"
mock_admin = AsyncMock()
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_response.json.return_value = {
"data": [
{"id": "my-lora", "parent": "base", "root": "/weights/step_42"},
]
}
mock_admin.get.return_value = mock_response
pool._admin_clients["10.0.0.1"] = mock_admin
result = asyncio.run(pool._get_loaded_adapter("10.0.0.1"))
assert result is not None
assert result.step == 42
def test_get_loaded_adapter_handles_step_dash_format():
"""Test that _get_loaded_adapter parses step-N format (with dash)."""
with patch("prime_rl.utils.elastic.get_logger"):
mock_config = MagicMock()
mock_config.elastic.hostname = "test.hostname"
mock_config.elastic.port = 8000
mock_config.elastic.sync_interval = 5.0
mock_config.router_url = None
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
pool._desired.name = "my-lora"
mock_admin = AsyncMock()
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_response.json.return_value = {
"data": [
{"id": "my-lora", "parent": "base", "root": "/weights/step-99"},
]
}
mock_admin.get.return_value = mock_response
pool._admin_clients["10.0.0.1"] = mock_admin
result = asyncio.run(pool._get_loaded_adapter("10.0.0.1"))
assert result is not None
assert result.step == 99
def test_elastic_clients_preserve_renderer_model_name_when_model_name_updates():
with patch("prime_rl.utils.elastic.get_logger"):
client_config = MagicMock()
client_config.elastic.hostname = "test.hostname"
client_config.elastic.port = 8000
client_config.elastic.sync_interval = 5.0
client_config.router_url = None
client_config.api_key_var = "PRIME_API_KEY"
client_config.headers = {}
client_config.headers_from_env = {}
client_config.extra_headers_from_state = {}
from renderers import Qwen3VLRendererConfig
renderer_settings = Qwen3VLRendererConfig()
pool = ElasticInferencePool(
client_config=client_config,
model_name="Qwen/Qwen3-VL-4B-Instruct",
train_client_type="renderer",
renderer_config=renderer_settings,
)
pool._servers = {
"10.0.0.1": MagicMock(status="ready"),
}
pool.update_model_name("r8-smoke")
clients = pool.train_clients
# `renderer_model_name` stays pinned to the original base model even after the
# served model name flips to the LoRA adapter (`r8-smoke`).
assert clients == [
TrainClientConfig(
renderer=renderer_settings,
renderer_model_name="Qwen/Qwen3-VL-4B-Instruct",
api_key_var="PRIME_API_KEY",
base_url="http://10.0.0.1:8000/v1",
headers={},
)
]
+1 -64
View File
@@ -8,7 +8,7 @@ from contextlib import closing
import pytest
from prime_rl.configs.shared import MetricsServerConfig
from prime_rl.utils.metrics_server import HealthServer, MetricsServer, RunStats
from prime_rl.utils.metrics_server import HealthServer, MetricsServer
def find_free_port() -> int:
@@ -163,69 +163,6 @@ def test_server_port_conflict_raises():
server1.stop()
def test_server_update_runs():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
run_stats = [
RunStats(run_id="run_001", step=50, total_tokens=100000, learning_rate=1e-4, ready=True),
RunStats(run_id="run_002", step=25, total_tokens=50000, learning_rate=1e-5, ready=False),
]
server.update_runs(runs_discovered=5, runs_max=8, run_stats=run_stats)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
content = response.read().decode()
# Check aggregate metrics
assert "trainer_runs_discovered 5.0" in content
assert "trainer_runs_active 2.0" in content
assert "trainer_runs_ready 1.0" in content
assert "trainer_runs_max 8.0" in content
# Check per-run metrics with labels
assert 'trainer_run_step{run="run_001"} 50.0' in content
assert 'trainer_run_step{run="run_002"} 25.0' in content
assert 'trainer_run_tokens{run="run_001"} 100000.0' in content
assert 'trainer_run_learning_rate{run="run_001"}' in content
assert 'trainer_run_ready{run="run_001"} 1.0' in content
assert 'trainer_run_ready{run="run_002"} 0.0' in content
server.stop()
def test_server_update_runs_cleanup():
"""Test that removed runs are cleaned up from metrics."""
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
# First update with two runs
run_stats = [
RunStats(run_id="run_001", step=50, total_tokens=100000, learning_rate=1e-4, ready=True),
RunStats(run_id="run_002", step=25, total_tokens=50000, learning_rate=1e-5, ready=False),
]
server.update_runs(runs_discovered=2, runs_max=8, run_stats=run_stats)
# Second update with only one run (run_002 removed)
run_stats = [
RunStats(run_id="run_001", step=60, total_tokens=120000, learning_rate=1e-4, ready=True),
]
server.update_runs(runs_discovered=1, runs_max=8, run_stats=run_stats)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
content = response.read().decode()
# run_001 should be updated
assert 'trainer_run_step{run="run_001"} 60.0' in content
# run_002 should be removed
assert "run_002" not in content
server.stop()
def test_health_server_start_stop():
port = find_free_port()
server = HealthServer(port=port)