diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 1289714558f..d37110fd232 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -77,13 +77,15 @@ jobs: /tmp/slim/bin/python - <<'PY' import sys - from prime_rl.configs.rl import RLConfig - from prime_rl.configs.sft import SFTConfig - from prime_rl.configs.inference import InferenceConfig - from prime_rl.configs.orchestrator import OrchestratorConfig - from prime_rl.configs.trainer import TrainerConfig - from prime_rl.configs.env_worker_pool import EnvWorkerPoolConfig - from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr + from prime_rl.configs.components.env_worker_pool import EnvWorkerPoolConfig + from prime_rl.configs.components.orchestrator import OrchestratorConfig + from prime_rl.configs.components.router import RouterConfig + from prime_rl.configs.components.trainer import TrainerConfig + from prime_rl.configs.entrypoints.inference import InferenceConfig + from prime_rl.configs.entrypoints.rl import RLConfig + from prime_rl.configs.entrypoints.sft import SFTConfig + from prime_rl.configs.base import BaseConfig + from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr from prime_rl.utils.validation import propagate_shared_fields # `verifiers` (+ its `datasets` dep) is a declared slim dep: the v1 config types @@ -103,7 +105,7 @@ jobs: run: | /tmp/slim/bin/python - <<'PY' from pydantic_config import cli - from prime_rl.configs.sft import SFTConfig + from prime_rl.configs.entrypoints.sft import SFTConfig # The slim wheel intentionally excludes taskset packages, so validate a real # SFT config here. RL recipes are covered by the full config suite. for cfg_cls, args in [ @@ -136,15 +138,20 @@ jobs: - '{pyproject.toml,uv.lock,.python-version,.gitmodules}' - 'deps/**' - 'packages/**/pyproject.toml' - - 'packages/prime-rl-configs/src/prime_rl/configs/{trainer,shared,__init__}.py' + - 'packages/prime-rl-configs/src/prime_rl/configs/{base,__init__}.py' + - 'packages/prime-rl-configs/src/prime_rl/configs/{blocks,components/trainer}/**' + - 'packages/prime-rl-configs/src/prime_rl/configs/{components,entrypoints}/__init__.py' - 'packages/prime-rl-configs/src/prime_rl/utils/**' - 'src/prime_rl/*.py' - 'src/prime_rl/{trainer,multimodal,transports,utils}/**' - 'tests/{__init__.py,conftest.py,utils.py}' - 'tests/integration/{__init__.py,conftest.py}' - - 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_worker_pool,algorithm,monitors}.py' + - 'packages/prime-rl-configs/src/prime_rl/configs/entrypoints/{eval,inference}.py' + - 'packages/prime-rl-configs/src/prime_rl/configs/components/{orchestrator,engine}/**' + - 'packages/prime-rl-configs/src/prime_rl/configs/components/{online_eval,env_worker_pool}.py' - 'src/prime_rl/{control,eval,orchestrator,monitors}/**' - - 'src/prime_rl/entrypoints/{eval,env_worker_pool}.py' + - 'src/prime_rl/entrypoints/eval.py' + - 'src/prime_rl/components/env_worker_pool.py' - 'tests/integration/test_gsm8k_eval.py' - 'tests/integration/configs/gsm8k-eval.toml' diff --git a/AGENTS.md b/AGENTS.md index 50b93d6cd62..ba1e07e41fb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -67,8 +67,8 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests `prime-rl` owns run config resolution and process launch; external orchestrators (such as `prime-factory-operator`) only materialize infrastructure. -- Put role-specific vLLM flags, parallelism, kernel workarounds, role env vars, and router/transport settings in `prime-rl-configs` (`for_pd_role`, `dump_rl_components`, `dump_pd_components`), never only in SLURM templates. -- Ship `[project.scripts]` entrypoints (like `router`) for non-trivial role/service startup, reading mounted JSON configs plus minimal pod inputs (`POD_IP`, `JOB_COMPLETION_INDEX`, peer URLs). +- Put role-specific vLLM flags, parallelism, kernel workarounds, role env vars, and router/transport settings in `prime-rl-configs` (`InferenceSection.engine_config(role=...)`, `components()`, `dump_components`), never only in SLURM templates. +- Ship `[project.scripts]` entrypoints (like `router` and `engine`) for non-trivial role/service startup, reading mounted JSON configs plus minimal pod inputs (`POD_IP`, `JOB_COMPLETION_INDEX`, peer URLs). - Keep orchestrator helpers (like `resolve_client_roles`) compatible with both SLURM per-rank external LB and Kubernetes per-pod internal DP. ## Git diff --git a/benchmarks/llep/bench_llep.py b/benchmarks/llep/bench_llep.py index 12923eaa215..6105081c04d 100644 --- a/benchmarks/llep/bench_llep.py +++ b/benchmarks/llep/bench_llep.py @@ -29,7 +29,7 @@ rel_err, ) -from prime_rl.configs.trainer import LLEPConfig +from prime_rl.configs.components.trainer.moe import LLEPConfig from prime_rl.trainer.distributed.token_dispatcher import TorchTokenDispatcher # noqa: E402 diff --git a/benchmarks/llep/check_grads.py b/benchmarks/llep/check_grads.py index 94f389851df..ec1a3c54af1 100644 --- a/benchmarks/llep/check_grads.py +++ b/benchmarks/llep/check_grads.py @@ -15,7 +15,7 @@ sys.path.insert(0, str(Path(__file__).parent)) from common import clamped_swiglu, make_routing # noqa: E402 -from prime_rl.configs.trainer import LLEPConfig # noqa: E402 +from prime_rl.configs.components.trainer.moe import LLEPConfig from prime_rl.trainer.models.layers.activations import ClampedSilu # noqa: E402 from prime_rl.trainer.models.layers.llep_mega_moe import LLEPMegaMoEExpertCompute # noqa: E402 from prime_rl.trainer.models.layers.mega_moe import MegaMoEExpertCompute, reserve_sms_for_comm # noqa: E402 diff --git a/benchmarks/llep/check_moe_layers.py b/benchmarks/llep/check_moe_layers.py index e4506f4225f..ff8b9bc4185 100644 --- a/benchmarks/llep/check_moe_layers.py +++ b/benchmarks/llep/check_moe_layers.py @@ -15,7 +15,7 @@ import torch import torch.distributed as dist -from prime_rl.configs.trainer import LLEPConfig +from prime_rl.configs.components.trainer.moe import LLEPConfig from prime_rl.trainer.distributed.token_dispatcher import FusedTokenDispatcher from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config from prime_rl.trainer.models.deepseek_v4.moe import DeepseekV4MoE diff --git a/docs/algorithms.md b/docs/algorithms.md index c1421a38cec..b9576e6e0fd 100644 --- a/docs/algorithms.md +++ b/docs/algorithms.md @@ -515,7 +515,7 @@ class MyAlgorithm(Algorithm): assign_advantage(trace, advantage) ``` -Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick `score_episode` for rollout-local work on the trace graph, `score_sample` for model calls on a rollout's samples, and `score_group` for group-relative credit. `assign_advantage` credits every sampled token on the trace's trainable branches with one value. +Add a typed `MyAlgoConfig` to `prime_rl.configs.blocks.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick `score_episode` for rollout-local work on the trace graph, `score_sample` for model calls on a rollout's samples, and `score_group` for group-relative credit. `assign_advantage` credits every sampled token on the trace's trainable branches with one value. Curriculum admission and metrics read each trace's advantage after group scoring. diff --git a/docs/configuration.md b/docs/configuration.md index 56a861e90ff..d22d28deece 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -272,7 +272,7 @@ Then inspect the resolved config: ```bash ls /tmp/reverse-dry/check/configs/latest/resolved/ -# rl.json trainer.json orchestrator.json inference.json +# rl.json trainer.json orchestrator.json engine.json router.json envs/ ``` Each per-process JSON contains the final, validated configuration that the run diff --git a/docs/eval.md b/docs/eval.md index 6da7fcd2757..dd245598734 100644 --- a/docs/eval.md +++ b/docs/eval.md @@ -43,7 +43,7 @@ Against a disaggregated prefill/decode deployment, list the engines in `client.a ## Configuration -Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `[select]`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`: +Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/entrypoints/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `[select]`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`: ```toml model = "Qwen/Qwen3-4B" diff --git a/docs/inference.md b/docs/inference.md index 279681902ee..125f4e968d7 100644 --- a/docs/inference.md +++ b/docs/inference.md @@ -62,7 +62,7 @@ The single-node deployment is the default deployment shape. It runs the inferenc type = "single_node" ``` -The launcher starts a `vllm-router` on `inference.server.port` (default `8000`) fronting the vLLM engine on `inference.backend_port` (default `8100`). Clients connect to the router URL; admin operations (weight updates, health checks) bypass the router and hit the engine port directly — the RL entrypoint wires `orchestrator.model.client.admin_base_url` accordingly. +The launcher starts a `vllm-router` on `inference.server.port` (default `8000`) fronting the vLLM engine on `inference.backend_port` (default `server.port + 100`, i.e. `8100`). Clients connect to the router URL; admin operations (weight updates, health checks) bypass the router and hit the engine port directly — the RL entrypoint wires `orchestrator.model.client.admin_base_url` accordingly. This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations. @@ -207,7 +207,7 @@ On top of vLLM's API, each engine serves the routes the orchestrator drives it w A request to a guarded route must carry the token in the `X-Prime-Admin-Token` header, or it gets a `401`. A process that sends the token reads it from `PRIME_RL_ADMIN_TOKEN`. A process that only checks it can instead be given its SHA-256 digest in `PRIME_RL_ADMIN_TOKEN_SHA256`, so it cannot make the calls it guards. The orchestrator sends the header on its engine admin clients only — never to the router. `/liveness` and vLLM's own health routes stay open for probes. -The `rl` and `sft` launchers handle the token themselves, locally and on SLURM: they generate a fresh one per run (or reuse `PRIME_RL_ADMIN_TOKEN` when the launching environment or `.env` sets it). The process that calls the engines' admin routes gets the token: the orchestrator, or an `sft` run's online evals. The engines, started with `--server.require-admin-token`, and the control APIs get its digest. The env worker pools and the router get neither, and neither is written to a config or to the SLURM script. To call a run's control API yourself, set `PRIME_RL_ADMIN_TOKEN` before launching and send it in the header. +The `rl` and `sft` launchers handle the token themselves, locally and on SLURM: they generate a fresh one per run (or reuse `PRIME_RL_ADMIN_TOKEN` when the launching environment or `.env` sets it). The process that calls the engines' admin routes gets the token: the orchestrator, or an `sft` run's online evals. The engines, whose configs set `server.require_admin_token`, and the control APIs get its digest. The env worker pools and the router get neither, and neither is written to a config or to the SLURM script. To call a run's control API yourself, set `PRIME_RL_ADMIN_TOKEN` before launching and send it in the header. A standalone `eval` generates no token: set `PRIME_RL_ADMIN_TOKEN` yourself to guard its control API. It starts its env worker pools without it. @@ -310,7 +310,7 @@ HiSparse (vLLM, DSA sparse-MLA models such as GLM-5.x) keeps the sparse-MLA KV i host_pool_gib = 160 # pinned host RAM per GPU worker ``` -prime-rl adds vLLM's `HiSparseConnector` to the KV transfer config. Under disaggregated P/D it applies to decode instances only: the launcher writes one engine config per role (`inference-prefill.json`, `inference-decode.json`) and drops HiSparse from the prefill one. Budget decode-node RAM as `GPUs per node × host_pool_gib`. Prefill KV offload works with it, but decode cannot also offload KV: set `inference.deployment.decode_kv_cache_offload = "None"`. Native offload rejects HiSparse's host-resident KV layout, and Mooncake would store that layout under the same keys as prefill's regular layout, so prefill fails to load it. Without P/D, native offload is rejected and Mooncake offload works. vLLM checks HiSparse's requirements at startup: no pipeline or decode context parallelism, and a model with `index_topk`. vLLM also rejects `cudagraph_mode = "FULL"`; the P/D decode launch uses `FULL_DECODE_ONLY`, which it accepts. Size decode `max_num_seqs` explicitly (e.g. 96 per rank): the GPU buffers scale with it. +prime-rl adds vLLM's `HiSparseConnector` to the KV transfer config. Under disaggregated P/D it applies to decode instances only: the launcher writes one engine config per role (`engine-prefill.json`, `engine-decode.json`) and drops HiSparse from the prefill one. Budget decode-node RAM as `GPUs per node × host_pool_gib`. Prefill KV offload works with it, but decode cannot also offload KV: set `inference.deployment.decode_kv_cache_offload = "None"`. Native offload rejects HiSparse's host-resident KV layout, and Mooncake would store that layout under the same keys as prefill's regular layout, so prefill fails to load it. Without P/D, native offload is rejected and Mooncake offload works. vLLM checks HiSparse's requirements at startup: no pipeline or decode context parallelism, and a model with `index_topk`. vLLM also rejects `cudagraph_mode = "FULL"`; the P/D decode launch uses `FULL_DECODE_ONLY`, which it accepts. Size decode `max_num_seqs` explicitly (e.g. 96 per rank): the GPU buffers scale with it. ### Speculative Decoding diff --git a/docs/training.md b/docs/training.md index 97be063f8ce..e3c066981cc 100644 --- a/docs/training.md +++ b/docs/training.md @@ -44,6 +44,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover | `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. | | `uv run pretrain` | Pretraining from scratch on tokenized shards. | Launches torchrun internally; see [Pretraining](#pretraining). | | `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. | +| `uv run engine` | One vLLM engine without a router. | Launchers start these for multi-node and P/D ranks, from the engine part of the inference config. | | `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-worker-pool` per source. | | `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). | | `uv run env-worker-pool` | One source's worker pool replica: a broker and its env workers. | Launchers start these automatically. Use this command for standalone pools, including sources whose `serve.address` points to an externally managed pool. | @@ -83,9 +84,8 @@ Orchestrator ``` An external orchestrator, such as Kubernetes, can run a run's pools itself instead of the -launcher. `dump_env_worker_pool_components(config)` (in `prime-rl-configs`) gives the -`EnvWorkerPoolConfig` of each pool the run would start, keyed `/`, without -writing files. Run `env-worker-pool @ ` for each with `PRL_ENV_BIND_ADDRESS` set to +launcher. `config.components()` (in `prime-rl-configs`) gives the `EnvWorkerPoolConfig` of each +pool the run would start, keyed `envs//`, without writing files. Run `env-worker-pool @ ` for each with `PRL_ENV_BIND_ADDRESS` set to where it should listen (e.g. `tcp://0.0.0.0:5000`), and give the orchestrator `PRL_ENV_ADDRESSES`, a JSON object of the same keys to the addresses peers reach them at. A source's own `serve.address` still wins, and a source with neither waits on its address file @@ -511,7 +511,7 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma ### Asynchronous Checkpoints -By default a trainer step waits until its checkpoint is written to storage. With `--ckpt.async-save` (`--trainer.ckpt.async-save` also works for `rl`), a save only copies each rank's model and optimizer state into pinned host memory. A background thread then writes the copy to storage while training continues: +By default a trainer step waits until its checkpoint is written to storage. With `--ckpt.async-save`, a save only copies each rank's model and optimizer state into pinned host memory. A background thread then writes the copy to storage while training continues: ```bash uv run rl @ rl.toml --ckpt.interval 2 --ckpt.async-save @@ -532,7 +532,7 @@ Some things to know: #### Remote Checkpoints -`[ckpt.remote]` mirrors trainer checkpoints to an S3-compatible object store, with a retention policy of its own (`[trainer.ckpt.remote]` also works for `rl`): +`[ckpt.remote]` mirrors trainer checkpoints to an S3-compatible object store, with a retention policy of its own: ```toml [ckpt] @@ -723,7 +723,7 @@ Only these fields are live; every other field is frozen: | `eval.source[*].interval` | Changes eval cadence from the next policy update. | | `train.source[*].algo.length_penalty` | Changes a GRPO source's length penalty: its weights, its type, or turning it on (a config) or off (`null`). It applies to every group scored from the next step on, including groups already running, since a group is scored when its last rollout finishes. Set it per source: the group-level `train.algo` is only a default for the sources and is frozen. | -Frozen fields include the model, tokenizer, renderer, transports, monitors, logging, checkpointing, output directory, padding and the trainer topology, which are fixed at launch. `seq_len` and `max_steps` are frozen because the trainer depends on them. Eval group sizes, algorithms (except the length penalty), curricula, eval sampling and task selection are frozen, as are adding, removing, renaming or reordering sources and turning eval on or off. In the config, a live field is annotated with `Annotated[T, Live()]` (from `prime_rl.configs.diff`); every other field is frozen. +Frozen fields include the model, tokenizer, renderer, transports, monitors, logging, checkpointing, output directory, padding and the trainer topology, which are fixed at launch. `seq_len` and `max_steps` are frozen because the trainer depends on them. Eval group sizes, algorithms (except the length penalty), curricula, eval sampling and task selection are frozen, as are adding, removing, renaming or reordering sources and turning eval on or off. In the config, a live field is annotated with `Annotated[T, Live()]` (from `prime_rl.utils.diff`); every other field is frozen. ### Exporting Checkpoints @@ -806,7 +806,7 @@ uv run rl @ rl.toml --monitors.wandb # default project, ran uv run rl @ rl.toml --monitors.wandb.project my-proj --monitors.wandb.name run-42 ``` -The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `monitors.wandb.offline = true`. +The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and a connection to the W&B server, so `rl` rejects `monitors.wandb.offline = true`. prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, every training run (RL and SFT) gets an **auto-created `overview` saved view** curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first. diff --git a/packages/prime-rl-configs/README.md b/packages/prime-rl-configs/README.md index a4a382f9006..e7a23cbf569 100644 --- a/packages/prime-rl-configs/README.md +++ b/packages/prime-rl-configs/README.md @@ -16,11 +16,111 @@ The pip *distribution name* (`prime-rl-configs`) and the *import path* (`prime_r ```python from pydantic_config import cli -from prime_rl.configs.rl import RLConfig +from prime_rl.configs.entrypoints.rl import RLConfig config = cli(RLConfig, args=["@", "path/to/rl.toml"]) ``` -Other config classes live alongside `RLConfig` under `prime_rl.configs.*` (`sft`, `inference`, `orchestrator`, `trainer`, `env_worker_pool`). +## Package layout + +``` +prime_rl/configs/ + base.py BaseConfig, EntrypointConfig, ComponentConfig, Placement, build_component_config, dump_components + entrypoints/ the configs that users write: rl, sft, pretrain, eval, inference (_supervised: shared by sft and pretrain) + components/ the configs that one process reads + trainer/ __init__: TrainerSection, TrainerConfig · sft · pretrain · base · model · moe · optim · loss · data · ckpt + orchestrator/ __init__: OrchestratorSection, OrchestratorConfig · sources · sampling · curriculum · ckpt + engine/ __init__: EngineSection, EngineConfig · vllm · kv_cache · deployment + router.py env_worker_pool.py online_eval.py modelexpress_server.py + blocks/ the blocks that several modules use: weight_broadcast, deployment, slurm, monitors, log, client, + run, ckpt, model, algorithm, length_penalty, transport +``` + +To find a field, follow its TOML path. `[trainer.optim]` is in `components/trainer/optim.py`. `[orchestrator.train.source]` is in `components/orchestrator/sources.py`. A top-level table that several entrypoints share, such as `[weight_broadcast]` or `[slurm]`, is in `blocks/`. A table that one entrypoint owns, such as the rl `[deployment]`, is in that entrypoint's module. + +`test_config_package_follows_its_rules` enforces these rules: + +1. A module in `components/` defines at most one `ComponentConfig`, next to its section. Each entry in `components/` defines at least one. No module outside `components/` defines one. +2. Each class name is unique in the package. Prefix a name with its component when two components need the same concept (`TrainerModelConfig`, `OrchestratorModelConfig`). +3. Imports go one way: `entrypoints` → `components` → `blocks` → `base`. A block never imports a component, and a component never imports an entrypoint. +4. A module stays under about 400 lines. Split a larger module along its TOML sub-tables. `entrypoints/rl.py` is the one exception, because `RLConfig` wires every rl component. +5. Each config class and each field has a docstring. A class docstring says what the block configures. A field docstring says what the field controls, and what `None` or a sentinel such as `"auto"` means. Do not repeat the type, the default or the bounds: `--help` shows them from the annotation. A `type` discriminator needs no docstring, because its class docstring describes the variant. + + ```python + class TimeoutConfig(BaseConfig): + """Time limits for one rollout.""" + + setup: float | None = Field(None, gt=0) + """Seconds for task setup (None = no limit).""" + ``` + +## Config rules + +Each entrypoint (outer box) launches component processes (inner nodes). A node shows the public section the entrypoint nests, and the component config the process reads. Arrows show the main data flow. + +```mermaid +flowchart LR + subgraph rl["uv run rl · RLConfig"] + subgraph rl_inference["inference · InferenceSection"] + rl_router["router · RouterConfig"] --> rl_engine["engine ×N · EngineConfig"] + end + rl_orchestrator["orchestrator · OrchestratorSection → OrchestratorConfig"] + rl_trainer["trainer · TrainerSection → TrainerConfig"] + rl_env["env-worker-pool ×source · EnvWorkerPoolConfig"] + rl_orchestrator -- requests --> rl_router + rl_orchestrator -- episodes --> rl_env + rl_orchestrator -- rollouts --> rl_trainer + rl_trainer -- weights --> rl_engine + end + + subgraph sft["uv run sft · SFTConfig"] + sft_trainer["trainer · SFTTrainerSection → SFTTrainerConfig"] + subgraph sft_inference["inference · ServingSection"] + sft_router["router · RouterConfig"] --> sft_engine["engine ×N · EngineConfig"] + end + sft_eval["online eval · SFTOnlineEvalSection → SFTOnlineEvalConfig"] + sft_env["env-worker-pool ×eval source · EnvWorkerPoolConfig"] + sft_trainer -- weights --> sft_engine + sft_eval -- requests --> sft_router + sft_eval -- episodes --> sft_env + end + + subgraph inference["uv run inference · InferenceConfig"] + inf_router["router · RouterConfig"] --> inf_engine["engine ×N · EngineConfig"] + end + + subgraph eval["uv run eval · EvalConfig"] + eval_loop["eval loop"] -- episodes --> eval_env["env-worker-pool ×source · EnvWorkerPoolConfig"] + end + + subgraph pretrain["uv run pretrain · PretrainConfig"] + pretrain_trainer["trainer · PretrainTrainerSection → PretrainTrainerConfig"] + end +``` + +The component scripts (`trainer`, `orchestrator`, `engine`, `router`, `env-worker-pool`) and modules (`prime_rl.trainer.sft.train`, `prime_rl.trainer.pretrain.train`, `prime_rl.eval.online`, `prime_rl.entrypoints.modelexpress_server`) each run one process from its component config. The local, SLURM and external launchers start the same processes. + +An entrypoint gives every component config through one API: + +```python +from prime_rl.configs.base import dump_components + +config.components() # {"trainer": TrainerConfig, "orchestrator": ..., "engine": EngineConfig, "router": RouterConfig, "envs/train/": EnvWorkerPoolConfig, ...} +config.placement() # the same keys -> Placement(replicas, nodes, gpus_per_node) +dump_components(config) # the same keys -> the JSON each process reads +``` + +A key is the stem of the JSON file that a launcher writes. A disaggregated deployment has `engine-prefill` and `engine-decode` in place of `engine`. SFT online evals add `online-eval`. A run with a `modelexpress` weight broadcast adds `modelexpress-server`, unless a SLURM job uses an external server (`slurm.launch_modelexpress = false`). + +Follow these rules when you add or move a field: + +1. An entrypoint config subclasses `EntrypointConfig`. A component config subclasses `ComponentConfig`. `test_config_layout` checks that each lives in its package. +2. Define each field once. Put a block that one component uses with that component. Put a block that several modules use in `blocks/`. +3. An entrypoint nests sections, never component configs. A section (`TrainerSection`, `SFTTrainerSection`, `PretrainTrainerSection`, `OrchestratorSection`, `InferenceSection`, `ServingSection`, `EngineSection`) holds the fields that a user can set. The component config adds the fields that a launcher fills: `TrainerConfig(TrainerSection, ComponentConfig)`. The component config inherits the section, so the two cannot drift. +4. A field that a launcher always fills is not public. Do not keep it on the section and reject user values: put it on the component config. +5. One builder makes each component config from its section and the filled fields (e.g. `RLConfig.trainer_config()`, `InferenceSection.engine_config(role=...)`, `SupervisedConfig.online_eval_config()`). `components()` calls the builders. Each entrypoint calls `components()` when it validates, so a config that resolves can always launch. A launcher dumps each component whole, with no excludes, and never rewrites it. A value that is known before the launcher has hosts goes into the component config. Only host-dependent wiring (an address, the engine URLs, the attempt directory) goes on the command line at process start. +6. A shared top-level field (e.g. `[model]`, `max_steps`, `[ckpt]`) fills the component fields that the user leaves unset. A different explicit value on a component is an error. +7. Configs reject unknown keys (`extra="forbid"`). `VllmConfig` passes unknown keys to vLLM. No process reads the JSON of another component. +8. A renamed or removed field fails as an unknown key. Do not add aliases or import shims. `import prime_rl` on its own succeeds but is empty — it's a [PEP 420](https://peps.python.org/pep-0420/) namespace package with no top-level attributes. Always import a submodule. diff --git a/packages/prime-rl-configs/src/prime_rl/configs/base.py b/packages/prime-rl-configs/src/prime_rl/configs/base.py new file mode 100644 index 00000000000..f1a8504cd64 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/base.py @@ -0,0 +1,63 @@ +from typing import Any, TypeVar + +from pydantic import BaseModel, Field +from pydantic_config import BaseConfig + +from prime_rl.utils.config import dump_resolved_config + +ModelT = TypeVar("ModelT", bound=BaseModel) + + +class ComponentConfig(BaseConfig): + """Config of a component process (trainer, orchestrator, router, ...): resolved by an entrypoint, or by an + external launcher such as a Kubernetes operator, and read by one process.""" + + +class Placement(BaseConfig): + """Where a launcher runs one component: ``replicas`` copies, each on ``nodes`` nodes with ``gpus_per_node`` GPUs + per node.""" + + replicas: int = Field(1, ge=1) + """Copies of the component.""" + + nodes: int = Field(1, ge=1) + """Nodes per copy.""" + + gpus_per_node: int = Field(0, ge=0) + """GPUs per node. 0 runs the component on CPU only.""" + + +class EntrypointConfig(BaseConfig): + """Config of a public entrypoint (``uv run rl``, ``sft``, ...): written by users in TOML and on the CLI.""" + + def components(self) -> dict[str, ComponentConfig]: + """The config of every component process the entrypoint launches, keyed by the stem of the JSON file + that a launcher writes it to (e.g. ``trainer``, ``engine-prefill``, ``envs/train/``).""" + return {} + + def placement(self) -> dict[str, Placement]: + """Where each component of ``components()`` runs, under the same keys.""" + return {} + + +def build_component_config(cls: type[ModelT], section: BaseModel, **wired: Any) -> ModelT: + """Build a component config from the public section it extends plus the fields a launcher fills. + + Takes the section fields that ``cls`` declares: a section can also hold settings of the launch (e.g. an + inference ``deployment``) that the process does not read. Validates the result like a reload of its JSON, + so the component's own validators run. The result keeps the section's record of which fields the user set. + """ + fields = cls.model_fields.keys() + values = {key: value for key, value in dump_resolved_config(section).items() if key in fields} + config = cls.model_validate({**values, **wired}) + fields_set = (section.model_fields_set & fields) | wired.keys() + return cls.model_construct(_fields_set=fields_set, **dict(config)) + + +def dump_components(config: "EntrypointConfig") -> dict[str, dict]: + """The JSON of every component config that an entrypoint launches, keyed like ``config.components()``. + + Keeps arbitrary schema fields and explicit nulls. External launchers use it from the CPU-only configs + distribution, like the local launchers. + """ + return {name: dump_resolved_config(component) for name, component in config.components().items()} diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/__init__.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/packages/prime-rl-configs/src/prime_rl/configs/algorithm.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/algorithm.py similarity index 79% rename from packages/prime-rl-configs/src/prime_rl/configs/algorithm.py rename to packages/prime-rl-configs/src/prime_rl/configs/blocks/algorithm.py index 09266af276b..6a4d9f7d774 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/algorithm.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/algorithm.py @@ -39,9 +39,10 @@ import verifiers.v1 as vf from pydantic import Field, field_validator, model_validator -from prime_rl.configs.diff import Live -from prime_rl.configs.shared import VLLMClientConfig -from prime_rl.utils.config import BaseConfig +from prime_rl.configs.base import BaseConfig +from prime_rl.configs.blocks.client import VLLMClientConfig +from prime_rl.configs.blocks.length_penalty import LengthPenaltyConfig +from prime_rl.utils.diff import Live class FrozenModelConfig(VLLMClientConfig): @@ -57,6 +58,7 @@ class FrozenModelConfig(VLLMClientConfig): """Served model name, sent as the ``model`` field of every request.""" base_url: str + """Base URL of the model's OpenAI-compatible API.""" ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig @@ -68,72 +70,10 @@ class FrozenModelConfig(VLLMClientConfig): # --------------------------------------------------------------------------- -# Shared sub-configs (length penalty, echo roles) +# Shared sub-configs (echo roles) # --------------------------------------------------------------------------- -class LinearLengthPenaltyConfig(BaseConfig): - """Linear ``pass_rate``-scaled penalty subtracted from each reward before the GRPO baseline — the sum of three terms (completion tokens, input tokens, turns), each normalized by the group's own max for that quantity and disabled by setting its coefficient to 0.""" - - type: Literal["linear"] = "linear" - - num_output_tokens_weight: float = Field(0.25, ge=0, allow_inf_nan=False) - """Scale on the output-token term. Each reward is reduced by ``num_output_tokens_weight * pass_rate * (rollout num_output_tokens / group's max num_output_tokens)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative; 0 disables the term.""" - - num_input_tokens_weight: float = Field(0.1, ge=0, allow_inf_nan=False) - """Scale on the input-token term — tokens the model conditioned on but did not generate (``num_total_tokens - num_output_tokens``: prompts, tool responses), as a fraction of the group's max input tokens. 0 disables the term.""" - - num_turns_weight: float = Field(0.1, ge=0, allow_inf_nan=False) - """Scale on the turns term (``pass_rate * (rollout num_turns / group's max num_turns)``). 0 disables the term.""" - - -class LinearSubagentLengthPenaltyConfig(LinearLengthPenaltyConfig): - """Linear penalty using per-call output and new input tokens, weighted by semantic subagent membership before group normalization. Assumes branches do not share physical prefixes.""" - - type: Literal["linear-subagent"] = "linear-subagent" # type: ignore[assignment] - - subagent_token_weight: float = Field(0.0, ge=0, le=1, allow_inf_nan=False) - """Multiplier on subagent input and output tokens before group normalization. Uses harness-declared ``subagent_call`` edges and their continuations, compaction attempts, and compacted contexts; unlabelled calls count at full weight. Nested subagents use the same multiplier. 0 excludes subagent tokens, 1 counts them fully. Does not change the turns term or training-token weights.""" - - -class CostLengthPenaltyConfig(BaseConfig): - """Linear cost penalty subtracted from every rollout's reward before the GRPO baseline: - ``r - clip(weight * cost, 0, 1)``, with - ``cost = num_output_tokens_weight * output + num_input_tokens_weight * input`` in tokens. Subagent tokens - count like the main agent's, so delegating work does not lower the cost. The reward - ``R = S - lambda_e * C`` of Cognition's SWE-2, where ``weight`` is lambda_e for the source's reasoning - effort, set to the slope of the base model's reward-vs-cost Pareto curve at that effort so that moving - along the curve leaves the objective unchanged to first order. It neither scales with the group's pass - rate nor depends on the rest of the group, and it reaches failed rollouts too, unless every rollout of - the group failed (no positive reward), in which case the group is not charged. A rollout whose stop condition - is in ``skip_stop_conditions`` is not charged either.""" - - type: Literal["cost"] = "cost" - - weight: float = Field(ge=0, allow_inf_nan=False) - """lambda: reward subtracted per cost token, before the clip to 1 (e.g. 4e-6). 0 disables the penalty. Each - source sets its own, so sources sampled at different reasoning efforts can each use their frontier slope.""" - - num_output_tokens_weight: float = Field(1.0, ge=0, allow_inf_nan=False) - """Weight of an output (sampled) token in the cost.""" - - num_input_tokens_weight: float = Field(1.0, ge=0, allow_inf_nan=False) - """Weight of a new input token in the cost: tokens the model conditioned on but did not generate (prompts, - tool responses), each counted once per trainable branch, as the ``linear`` penalty counts them.""" - - skip_stop_conditions: list[str] = ["max_turn_tokens"] - """Stop conditions (``Trace.stop_condition``) that exempt a rollout from the cost, so it keeps its reward as - is: framework limits or ``@vf.stop`` names. Pair one with a fixed reward for it in the env (``scoring.skip`` - or ``@vf.stop(skip_scoring=...)``). Run-wide caps such as ``max_turns`` or the token budgets keep the cost by - default, since they bound every rollout alike.""" - - -LengthPenaltyConfig: TypeAlias = Annotated[ - LinearLengthPenaltyConfig | LinearSubagentLengthPenaltyConfig | CostLengthPenaltyConfig, - Field(discriminator="type"), -] - - class EchoRoleConfig(BaseConfig): """Echo CE supervision for one message role.""" @@ -146,9 +86,16 @@ class EchoRolesConfig(BaseConfig): Setting any role replaces the whole table — unset roles stay disabled.""" system: EchoRoleConfig | None = None + """Supervision of system-message tokens (None = they do not train).""" + user: EchoRoleConfig | None = None + """Supervision of user-message tokens (None = they do not train).""" + assistant: EchoRoleConfig | None = None + """Supervision of env-provided assistant-message tokens (None = they do not train).""" + tool: EchoRoleConfig | None = None + """Supervision of tool-response tokens (None = they do not train).""" @model_validator(mode="after") def require_a_role(self): @@ -211,10 +158,11 @@ def validate_env(self, env_config: vf.EnvConfig) -> None: class GRPOAlgoConfig(BaseAlgoConfig): - type: Literal["grpo"] = "grpo" """GRPO: scalar advantage = reward minus the per-group mean baseline, consumed by the ``rl`` loss component on the rollout's action tokens.""" + type: Literal["grpo"] = "grpo" + action_loss_type: ClassVar[ActionLossType] = "rl" length_penalty: Annotated[LengthPenaltyConfig | None, Live()] = None @@ -235,7 +183,6 @@ def default_length_penalty_type(cls, value: Any) -> Any: class EchoAlgoConfig(GRPOAlgoConfig): - type: Literal["echo"] = "echo" # type: ignore[assignment] """ECHO: group-relative advantage on action tokens (GRPO), plus weighted CE on env-provided tokens of later turns (tool output, user feedback), selected by message role via the renderer's per-token ``is_content`` @@ -243,6 +190,8 @@ class EchoAlgoConfig(GRPOAlgoConfig): the whole non-sampled span). Selected tokens feed the ``ce`` loss component at their role's ``alpha`` and stay outside the rl mask and its denominator.""" + type: Literal["echo"] = "echo" # type: ignore[assignment] + roles: EchoRolesConfig = EchoRolesConfig(tool=EchoRoleConfig()) """The role table. The default — tool-response bodies at ``alpha = 0.1`` — is the vetted ECHO setting.""" @@ -252,7 +201,6 @@ class EchoAlgoConfig(GRPOAlgoConfig): class MaxRLAlgoConfig(BaseAlgoConfig): - type: Literal["max_rl"] = "max_rl" """MaxRL (arXiv:2602.02710): scalar advantage = (reward − group mean) / group mean, consumed by the ``rl`` loss component. Normalizing by the mean instead of GRPO's standard deviation makes the policy gradient @@ -262,11 +210,12 @@ class MaxRLAlgoConfig(BaseAlgoConfig): likelihood (∞). Designed for non-negative (canonically binary) rewards; a group with mean reward 0 carries zero advantages everywhere.""" + type: Literal["max_rl"] = "max_rl" + action_loss_type: ClassVar[ActionLossType] = "rl" class RAEAlgoConfig(BaseAlgoConfig): - type: Literal["rae"] = "rae" """RAE — role-conditioned advantage estimation (SPIRAL, https://arxiv.org/abs/2506.24119): scalar advantage = reward minus a per-agent EMA baseline of that agent's own rewards, consumed by the ``rl`` @@ -277,6 +226,8 @@ class RAEAlgoConfig(BaseAlgoConfig): permanent credit. Per-agent baselines measure each agent against its own expected reward instead. Works with any ``group_size`` (including 1).""" + type: Literal["rae"] = "rae" + action_loss_type: ClassVar[ActionLossType] = "rl" decay: float = Field(0.95, ge=0.0, lt=1.0) @@ -287,7 +238,6 @@ class RAEAlgoConfig(BaseAlgoConfig): class HierarchicalGRPOAlgoConfig(BaseAlgoConfig): - type: Literal["hierarchical_grpo"] = "hierarchical_grpo" """GRPO for proposer-solver envs. Agents in ``episode_agents`` are compared with same-role attempts on the @@ -295,6 +245,8 @@ class HierarchicalGRPOAlgoConfig(BaseAlgoConfig): proposals generated from one source task. This keeps rewards from different problems and different roles out of the same average.""" + type: Literal["hierarchical_grpo"] = "hierarchical_grpo" + action_loss_type: ClassVar[ActionLossType] = "rl" episode_agents: list[str] = Field(min_length=1) @@ -320,7 +272,6 @@ def validate_env(self, env_config: vf.EnvConfig) -> None: class OPDAlgoConfig(BaseAlgoConfig): - type: Literal["opd"] = "opd" """On-policy distillation: the per-token signal is the reverse KL to a reference model, evaluated in the trainer from reference prefill logprobs scored over each sample's own context (``ref_logprobs`` on the @@ -328,6 +279,8 @@ class OPDAlgoConfig(BaseAlgoConfig): rollouts keep ``advantages=None`` and samples ship no advantage stream. ``group_size`` only fans out sampling.""" + type: Literal["opd"] = "opd" + action_loss_type: ClassVar[ActionLossType] = "ref_kl" teacher: FrozenModelConfig @@ -339,7 +292,6 @@ class OPDAlgoConfig(BaseAlgoConfig): class OPSDAlgoConfig(BaseAlgoConfig): - type: Literal["opsd"] = "opsd" """On-policy self-distillation (SDFT, https://arxiv.org/abs/2601.19897): the per-token signal is the reverse KL against the live policy conditioned on an expert demonstration. The teacher *is* the policy — self-distillation @@ -349,6 +301,8 @@ class OPSDAlgoConfig(BaseAlgoConfig): number of turns. No scalar advantage is assigned — rollouts keep ``advantages=None`` and samples ship no advantage stream.""" + type: Literal["opsd"] = "opsd" + action_loss_type: ClassVar[ActionLossType] = "ref_kl" demo_key: str = "demonstration" @@ -363,12 +317,13 @@ class OPSDAlgoConfig(BaseAlgoConfig): class SFTAlgoConfig(BaseAlgoConfig): - type: Literal["sft"] = "sft" """SFT distillation: cross-entropy on the sampled tokens. The ``ce`` loss ignores advantages and SFT assigns none — it trains on every sampled token. A curriculum can reject results using reward or any other finalized rollout data.""" + type: Literal["sft"] = "sft" + action_loss_type: ClassVar[ActionLossType] = "ce" teacher: FrozenModelConfig @@ -382,15 +337,15 @@ def rollout_model(self) -> ModelReference: class DebugAlgoConfig(BaseAlgoConfig): - type: Literal["debug"] = "debug" """Debugging algorithm for infra work: every sampled token of every clean - trainable trace gets the same constant ``advantage`` (default 1.0), - ignoring rewards entirely. Every admitted rollout is trainable and every + trainable trace gets the same constant ``advantage``, ignoring rewards entirely. Every admitted rollout is trainable and every action token carries gradient signal, so the full RL path (advantage transport, importance ratios, trust region, optimizer, weight update) can be exercised regardless of the reward function. Not a real training signal — a policy pushed by it drifts monotonically.""" + type: Literal["debug"] = "debug" + action_loss_type: ClassVar[ActionLossType] = "rl" advantage: float = Field(1.0, allow_inf_nan=False) diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/ckpt.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/ckpt.py new file mode 100644 index 00000000000..812f49b0a80 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/ckpt.py @@ -0,0 +1,62 @@ +import re +from pathlib import Path + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig + + +class BaseCheckpointConfig(BaseConfig): + """Where and how often a process saves checkpoints, and which old ones it keeps.""" + + output_dir: Path | None = None + """Override directory for checkpoints. If set, checkpoints are written here instead of under the run's + ``output_dir``, e.g. on a separate storage volume. In an RL run the trainer and the orchestrator each write + their half of a step here.""" + + interval: int | None = Field(None, ge=1) + """Step interval at which to save checkpoints (None = only the final checkpoint).""" + + 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.""" + + keep_interval: int | None = Field(None, ge=1) + """Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping.""" + + +def ckpt_output_dir(output_dir: Path, ckpt_config: BaseCheckpointConfig | None) -> Path: + """Where a run's checkpoints live: ``ckpt.output_dir`` when set, else the run's ``output_dir``.""" + return (ckpt_config.output_dir if ckpt_config else None) or output_dir + + +class ResumeConfig(BaseConfig): + """Resume the run from a checkpoint. A bare ``--resume`` (or empty ``[resume]`` block) + resumes from the latest checkpoint.""" + + step: int | None = Field(None, ge=1) + """Checkpoint step to resume from. None resumes from the latest checkpoint.""" + + dir: Path | None = None + """External checkpoint step directory to resume from (e.g. ``other/run/checkpoints/step_50``) — forks another run's checkpoint into this run. Mutually exclusive with ``step``.""" + + @model_validator(mode="after") + def validate_step_xor_dir(self): + if self.step is not None and self.dir is not None: + raise ValueError( + "resume.step and resume.dir are mutually exclusive — the step is taken from the directory name" + ) + if self.dir is not None: + validate_step_dir(self.dir, field="resume.dir") + return self + + @property + def dir_step(self) -> int: + """The step encoded in ``dir``'s name (validated to exist).""" + assert self.dir is not None + return int(self.dir.name.removeprefix("step_")) + + +def validate_step_dir(path: Path, *, field: str) -> None: + """Raise unless ``path`` names a checkpoint step directory (``.../step_``).""" + if not re.fullmatch(r"step_\d+", path.name): + raise ValueError(f"{field} must point at a checkpoint step directory (`.../step_`), got '{path}'") diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/client.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/client.py new file mode 100644 index 00000000000..1014ef636e4 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/client.py @@ -0,0 +1,55 @@ +from pydantic import Field +from verifiers.v1.configs.client import BaseClientConfig + +from prime_rl.configs.base import BaseConfig + + +class DynamoConfig(BaseConfig): + """Dynamo worker discovery for the inference admin plane.""" + + enabled: bool = True + """Enable Dynamo worker discovery for the inference admin plane.""" + + discovery_url: str | None = Field(default=None, min_length=1, max_length=2048) + """Dynamo frontend URL used to discover inference workers for RL control (None = the client's + ``base_url`` with its port plus one).""" + + +ADMIN_TOKEN_HEADER = "X-Prime-Admin-Token" + + +class ClientConfig(BaseClientConfig): + """Client of an inference pool behind an OpenAI-compatible endpoint, with the startup check and the admin + plane.""" + + wait_for_ready_timeout: int = 3600 + """Seconds to wait at startup for the inference pool to become ready.""" + + skip_model_check: bool = False + """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 multi-replica or disaggregated P/D deployments where the router must not handle admin traffic.""" + + admin_token_var: str | None = None + """Name of the environment variable holding the admin token of the inference servers. When it is set and non-empty, engine admin requests carry it in the ``X-Prime-Admin-Token`` header.""" + + +class VLLMClientConfig(ClientConfig): + """Client defaults for the live inference deployment managed by training.""" + + base_url: str = "http://localhost:8000/v1" + """Base URL of the inference pool's OpenAI-compatible API.""" + + api_key_var: str = "VLLM_API_KEY" + """Name of the environment variable holding the API key.""" + + admin_token_var: str | None = "PRIME_RL_ADMIN_TOKEN" + """Name of the environment variable holding the admin token of the inference servers. When it is set and non-empty, engine admin requests carry it in the ``X-Prime-Admin-Token`` header.""" + + +class PolicyClientConfig(VLLMClientConfig): + """Client of the policy deployment the orchestrator drives (weight updates, admin plane).""" + + dynamo: DynamoConfig | None = None + """Dynamo RL worker-discovery configuration.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/deployment.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/deployment.py new file mode 100644 index 00000000000..0d01e1b1d86 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/deployment.py @@ -0,0 +1,33 @@ +from typing import Literal + +from pydantic import Field + +from prime_rl.configs.base import BaseConfig + + +class BaseDeploymentConfig(BaseConfig): + """GPU and node layout of a launch.""" + + gpus_per_node: int = 8 + """GPUs per node.""" + + +class BaseSingleNodeDeploymentConfig(BaseDeploymentConfig): + """Run on one node, with its GPUs split between training and inference.""" + + type: Literal["single_node"] = "single_node" + + num_train_gpus: int = 1 + """GPUs allocated to the trainer.""" + + num_infer_gpus: int = 1 + """GPUs allocated to inference. ``sft`` uses them only for online evals with an ``[inference]`` block.""" + + +class BaseMultiNodeDeploymentConfig(BaseDeploymentConfig): + """Run on several nodes as one SLURM job, with whole nodes for training and inference.""" + + type: Literal["multi_node"] = "multi_node" + + num_train_nodes: int = Field(ge=1) + """Training nodes.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/length_penalty.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/length_penalty.py new file mode 100644 index 00000000000..4880e4160cf --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/length_penalty.py @@ -0,0 +1,69 @@ +"""Length penalties: a cost on long rollouts that GRPO-family algorithms subtract from each reward.""" + +from typing import Annotated, Literal, TypeAlias + +from pydantic import Field + +from prime_rl.configs.base import BaseConfig + + +class LinearLengthPenaltyConfig(BaseConfig): + """Linear ``pass_rate``-scaled penalty subtracted from each reward before the GRPO baseline — the sum of three terms (completion tokens, input tokens, turns), each normalized by the group's own max for that quantity and disabled by setting its coefficient to 0.""" + + type: Literal["linear"] = "linear" + + num_output_tokens_weight: float = Field(0.25, ge=0, allow_inf_nan=False) + """Scale on the output-token term. Each reward is reduced by ``num_output_tokens_weight * pass_rate * (rollout num_output_tokens / group's max num_output_tokens)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. 0 disables the term.""" + + num_input_tokens_weight: float = Field(0.1, ge=0, allow_inf_nan=False) + """Scale on the input-token term — tokens the model conditioned on but did not generate (``num_total_tokens - num_output_tokens``: prompts, tool responses), as a fraction of the group's max input tokens. 0 disables the term.""" + + num_turns_weight: float = Field(0.1, ge=0, allow_inf_nan=False) + """Scale on the turns term (``pass_rate * (rollout num_turns / group's max num_turns)``). 0 disables the term.""" + + +class LinearSubagentLengthPenaltyConfig(LinearLengthPenaltyConfig): + """Linear penalty using per-call output and new input tokens, weighted by semantic subagent membership before group normalization. Assumes branches do not share physical prefixes.""" + + type: Literal["linear-subagent"] = "linear-subagent" # type: ignore[assignment] + + subagent_token_weight: float = Field(0.0, ge=0, le=1, allow_inf_nan=False) + """Multiplier on subagent input and output tokens before group normalization. Uses harness-declared ``subagent_call`` edges and their continuations, compaction attempts, and compacted contexts; unlabelled calls count at full weight. Nested subagents use the same multiplier. 0 excludes subagent tokens, 1 counts them fully. Does not change the turns term or training-token weights.""" + + +class CostLengthPenaltyConfig(BaseConfig): + """Linear cost penalty subtracted from every rollout's reward before the GRPO baseline: + ``r - clip(weight * cost, 0, 1)``, with + ``cost = num_output_tokens_weight * output + num_input_tokens_weight * input`` in tokens. Subagent tokens + count like the main agent's, so delegating work does not lower the cost. The reward + ``R = S - lambda_e * C`` of Cognition's SWE-2, where ``weight`` is lambda_e for the source's reasoning + effort, set to the slope of the base model's reward-vs-cost Pareto curve at that effort so that moving + along the curve leaves the objective unchanged to first order. It neither scales with the group's pass + rate nor depends on the rest of the group, and it reaches failed rollouts too, unless every rollout of + the group failed (no positive reward), in which case the group is not charged. A rollout whose stop condition + is in ``skip_stop_conditions`` is not charged either.""" + + type: Literal["cost"] = "cost" + + weight: float = Field(ge=0, allow_inf_nan=False) + """lambda: reward subtracted per cost token, before the clip to 1 (e.g. 4e-6). 0 disables the penalty. Each + source sets its own, so sources sampled at different reasoning efforts can each use their frontier slope.""" + + num_output_tokens_weight: float = Field(1.0, ge=0, allow_inf_nan=False) + """Weight of an output (sampled) token in the cost.""" + + num_input_tokens_weight: float = Field(1.0, ge=0, allow_inf_nan=False) + """Weight of a new input token in the cost: tokens the model conditioned on but did not generate (prompts, + tool responses), each counted once per trainable branch, as the ``linear`` penalty counts them.""" + + skip_stop_conditions: list[str] = ["max_turn_tokens"] + """Stop conditions (``Trace.stop_condition``) that exempt a rollout from the cost, so it keeps its reward as + is: framework limits or ``@vf.stop`` names. Pair one with a fixed reward for it in the env (``scoring.skip`` + or ``@vf.stop(skip_scoring=...)``). Run-wide caps such as ``max_turns`` or the token budgets keep the cost by + default, since they bound every rollout alike.""" + + +LengthPenaltyConfig: TypeAlias = Annotated[ + LinearLengthPenaltyConfig | LinearSubagentLengthPenaltyConfig | CostLengthPenaltyConfig, + Field(discriminator="type"), +] diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/log.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/log.py new file mode 100644 index 00000000000..202c4b486ea --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/log.py @@ -0,0 +1,37 @@ +import os + +from pydantic import Field + +from prime_rl.configs.base import BaseConfig + + +class LogConfig(BaseConfig): + """Logging of one process.""" + + level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info")) + """Log level for the process and the verifiers library it runs, env worker pools included. + Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``.""" + + json_logging: bool = False + """Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.).""" + + +class PeriodicLogConfig(LogConfig): + """Logging of a process that also logs a periodic view of its rollout pipeline.""" + + interval: float = Field(10.0, gt=0) + """Interval (seconds) for the periodic pipeline log.""" + + +class TrainerLogConfig(LogConfig): + """Logging of the trainer.""" + + ranks_filter: list[int] = [0] + """Trainer ranks to show in console output. Passed to ``torchrun --local-ranks-filter``.""" + + +class SupervisedLogConfig(TrainerLogConfig): + """Logging of the ``sft`` and ``pretrain`` trainer.""" + + log_data: bool = False + """Log the first data sample at startup.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/model.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/model.py new file mode 100644 index 00000000000..bc13083d408 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/model.py @@ -0,0 +1,31 @@ +from prime_rl.configs.base import BaseConfig + + +class VLMConfig(BaseConfig): + """Vision-language model support.""" + + freeze_vision_encoder: bool = True + """Freeze the vision encoder parameters during training.""" + + +class BaseModelConfig(BaseConfig): + """The model a process loads.""" + + name: str = "Qwen/Qwen3-0.6B" + """HF model name or local path.""" + + trust_remote_code: bool = False + """Trust remote code when initializing the tokenizer.""" + + +class TokenizerConfig(BaseConfig): + """The tokenizer and chat template a process uses.""" + + name: str | None = None + """Tokenizer name or path. If None, the model's default tokenizer is used.""" + + trust_remote_code: bool | None = None + """Trust remote code when initializing the tokenizer. If None, inherits the model's ``trust_remote_code`` setting.""" + + chat_template: str | None = None + """Chat template for the tokenizer. Either a Jinja2 template string or a path to a template file. If None, the tokenizer's default chat template is used.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/monitors.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/monitors.py similarity index 85% rename from packages/prime-rl-configs/src/prime_rl/configs/monitors.py rename to packages/prime-rl-configs/src/prime_rl/configs/blocks/monitors.py index d0361844183..24e8506d025 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/monitors.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/monitors.py @@ -3,10 +3,12 @@ from pydantic import Field -from prime_rl.utils.config import BaseConfig +from prime_rl.configs.base import BaseConfig class WandbMonitorConfig(BaseConfig): + """Log metrics to Weights & Biases.""" + project: str = "prime-rl" """W&B project to log to.""" @@ -27,6 +29,8 @@ class WandbMonitorConfig(BaseConfig): class FileMonitorConfig(BaseConfig): + """Log metrics and episode traces to files in the run's output directory.""" + path: Path = Path("metrics.jsonl") """Path of the metrics JSONL file, relative to the file monitor's directory under the component's ``output_dir`` (``monitors/file/``; absolute paths win).""" @@ -61,19 +65,23 @@ class FileMonitorConfig(BaseConfig): class PrimeMonitorConfig(BaseConfig): + """Log metrics and episodes to the Prime Intellect platform.""" + name: str | None = None """Run or evaluation name shown on Prime. Inherits ``run.name`` when unset.""" class MonitorsConfig(BaseConfig): + """The metric monitors of a process. Each monitor that is not None is on.""" + wandb: WandbMonitorConfig | None = None - """Log metrics to Weights & Biases. Off by default; enable with ``--monitors.wandb``.""" + """Log metrics to Weights & Biases. Enable with ``--monitors.wandb``.""" file: FileMonitorConfig | None = FileMonitorConfig() - """Log metrics and episode traces to the run's output directory. On by default; disable with ``--no-monitors.file``.""" + """Log metrics and episode traces to the run's output directory. Disable with ``--no-monitors.file``.""" prime: PrimeMonitorConfig | None = None """Log metrics and episodes to the Prime Intellect platform: a training run's processes log to one platform run, and a standalone eval uploads each source's epoch as an - evaluation. Off by default; enable with ``--monitors.prime``. Needs a Prime API key, and a + evaluation. Enable with ``--monitors.prime``. Needs a Prime API key, and a training run also needs a team enabled for external training runs.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/run.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/run.py new file mode 100644 index 00000000000..ac08f1d92d0 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/run.py @@ -0,0 +1,76 @@ +from typing import Annotated, TypeAlias + +from pydantic import AfterValidator, Field + +from prime_rl.configs.base import BaseConfig + +# Launcher-managed env vars that a component's `env_vars` must not set: GPU partitioning +# and the single shared W&B run. The launcher always sets these last, so allowing them in +# `env_vars` would be a silent no-op (or, on multi-node, a footgun) — reject them instead. +PROTECTED_ENV_VARS = frozenset( + { + "CUDA_VISIBLE_DEVICES", + "PRL_RUN_ID", + "PRL_RUN_NAME", + "WANDB_RUN_ID", + "WANDB_SHARED_MODE", + "WANDB_SHARED_LABEL", + "WANDB_SHARED_PRIMARY", + "WANDB_SHARED_FINISHER", + } +) + + +def reject_protected_env_vars(env_vars: dict[str, str]) -> dict[str, str]: + clobbered = sorted(PROTECTED_ENV_VARS & env_vars.keys()) + if clobbered: + raise ValueError( + f"env_vars cannot set launcher-managed vars {clobbered} — set by the launcher, not overridable" + ) + return env_vars + + +EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_env_vars)] +"""A per-component `env_vars` mapping, validated to not clobber `PROTECTED_ENV_VARS`.""" + + +class RunConfig(BaseConfig): + """Identity of a run: its name and its directory.""" + + name: str | None = None + """Run name. Auto-generated as ``----`` when unset, so every launch gets a fresh, readable run directory; set an explicit name (e.g. an experiment name) to get a predictable run directory, which is also required to resume a previous run. Unless set explicitly, the W&B run name and the Prime platform run name inherit it.""" + + dir: str | None = None + """Run directory name — the run writes all its artifacts to ``output_dir / dir``. Defaults to ``run.name``; set it only when the directory should differ from the display name.""" + + +class ControlConfig(BaseConfig): + """The control API of a process: the HTTP server that accepts commands while the run goes on.""" + + host: str = "0.0.0.0" + """Address the control API binds to.""" + + port: int = Field(8040, ge=1, le=65535) + """Port the control API listens on.""" + + admin_token_var: str = "PRIME_RL_ADMIN_TOKEN" + """Name of the environment variable holding the run's admin token. When it, or ``_SHA256`` holding the token's SHA-256 digest, is set, every control request must carry the token in the ``X-Prime-Admin-Token`` header.""" + + +class GCConfig(BaseConfig): + """Scheduled Python garbage collection.""" + + interval: int = Field(50, ge=1) + """Run a scheduled garbage collection every N training steps, in place of Python's automatic collections that would run at unpredictable times.""" + + +class HeartbeatConfig(BaseConfig): + """Heartbeat pings to an uptime monitor (e.g. Better Stack) while the process makes progress.""" + + url: str + """URL to send the heartbeat to.""" + + min_interval: float = Field(30.0, gt=0) + """Minimum seconds between pings. Beats can arrive far more often (evals beat once + per landed episode); surplus beats are dropped to stay under Better Stack's heartbeat + rate limit. Size it well under the monitor's period.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/slurm.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/slurm.py new file mode 100644 index 00000000000..45681ae6676 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/slurm.py @@ -0,0 +1,70 @@ +from pathlib import Path + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig + + +class SlurmConfig(BaseConfig): + """Submit the launch as a SLURM job.""" + + job_name: str | None = None + """SLURM job name. Defaults to ``run.name`` for ``rl`` and ``sft``, and to ``inference`` for ``inference``.""" + + project_dir: Path = Path(".") + """Path to the project root, used to source .env, activate .venv, and run uv sync.""" + + template_path: Path | None = None + """SLURM template file. If None, uses the bundled single-node or multi-node template.""" + + partition: str | None = None + """SLURM partition (#SBATCH --partition). If None, the job goes to the cluster's default partition.""" + + nodelist: str | None = None + """Comma-separated list of specific nodes to run on (#SBATCH --nodelist).""" + + exclude: str | None = None + """Comma-separated list of nodes to exclude (#SBATCH --exclude).""" + + account: str | None = None + """SLURM account to charge (#SBATCH --account).""" + + time: str | None = None + """Maximum wall time, e.g. '24:00:00' or '7-00:00:00' (#SBATCH --time).""" + + pre_run_command: str | None = None + """Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes.""" + + launch_modelexpress: bool = True + """Start a job-scoped ModelExpress server for ModelExpress weight broadcasts on multi-node jobs.""" + + cleanup_grace_period: int = Field(3600, ge=0) + """Maximum seconds a multi-node RL job that hit a non-zero exit waits for an in-flight trainer checkpoint to finish before tearing down. Without an in-flight checkpoint (or without ``[ckpt]``) it tears down immediately. Set to 0 to never wait.""" + + shared_fs: bool = True + """Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun.""" + + sync_args: str = "--all-extras --all-packages" + """Arguments of the ``uv sync`` the job runs before it starts. Narrow them to install less, e.g. ``--extra train`` for an SFT job without online evals. Set it in a TOML file: on the command line a value starting with ``--`` is read as a flag.""" + + @property + def template_vars(self) -> dict: + """Common template variables for all SLURM templates.""" + return { + "job_name": self.job_name, + "project_dir": self.project_dir, + "partition": self.partition, + "nodelist": self.nodelist, + "exclude": self.exclude, + "account": self.account, + "time": self.time, + "pre_run_command": self.pre_run_command, + "cleanup_grace_period": self.cleanup_grace_period, + "shared_fs": self.shared_fs, + "sync_args": self.sync_args, + } + + @model_validator(mode="after") + def resolve_project_dir(self): + self.project_dir = self.project_dir.resolve() + return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/transport.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/transport.py new file mode 100644 index 00000000000..f084877b189 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/transport.py @@ -0,0 +1,19 @@ +from prime_rl.configs.base import BaseConfig + + +class ZMQTransportConfig(BaseConfig): + """Send rollouts from the orchestrator to the trainer over ZMQ.""" + + host: str = "localhost" + """Host address for ZMQ transport.""" + + port: int = 5555 + """Port for ZMQ transport.""" + + retain: bool = False + """Keep every shipped step, and the training arrays the env worker pools hold for it, + until a trainer checkpoint covers it, so a restarted trainer resumes from its newest + checkpoint and trains the steps since again. Needs a checkpoint interval, the filesystem + weight broadcast, a run directory the orchestrator and trainer share, and a rollout store + in every train env worker pool: the ``rl`` launcher sets ``store_dir`` for the pools it + starts, a pool started separately needs it in its own config.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/blocks/weight_broadcast.py b/packages/prime-rl-configs/src/prime_rl/configs/blocks/weight_broadcast.py new file mode 100644 index 00000000000..1998ff9ebc8 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/blocks/weight_broadcast.py @@ -0,0 +1,100 @@ +from typing import Annotated, Any, Literal, TypeAlias + +from pydantic import Field + +from prime_rl.configs.base import BaseConfig +from prime_rl.utils.config import dump_resolved_config + + +class BaseWeightBroadcastConfig(BaseConfig): + """Weight transfer from the trainer to inference.""" + + timeout: int = 3600 + """Timeout in seconds for the broadcast handshake and transfer, including the orchestrator's wait + for the trainer's startup broadcast. The trainer fails the run when no consumer acknowledges an + offered version in time. Raise it for large models on slow shared filesystems.""" + + +class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig): + """Send weights through a filesystem that the trainer and inference share.""" + + type: Literal["filesystem"] = "filesystem" + + +class NCCLWeightBroadcastSection(BaseWeightBroadcastConfig): + """Broadcast weights from the trainer to the inference workers over NCCL.""" + + type: Literal["nccl"] = "nccl" + + port: int = 29501 + """Port for the NCCL broadcast rendezvous.""" + + +class ModelExpressWeightBroadcastSection(BaseWeightBroadcastConfig): + """Transfer weights from the trainer to the inference workers through ModelExpress (NIXL).""" + + type: Literal["modelexpress"] = "modelexpress" + + host: str = "localhost" + """ModelExpress server host. Set it only for a server that the run does not start.""" + + port: int = 8001 + """ModelExpress gRPC port.""" + + metadata_port: int = 5655 + """Base port of the trainer's NIXL metadata listener. Each local rank listens on this plus its device id.""" + + staging_mode: Literal["COPY_TO_HOST", "COPY_TO_DEVICE", "IN_PLACE"] = "COPY_TO_HOST" + """Trainer storage policy passed to ModelExpress.""" + + staging_buffer_bytes: int | None = Field(None, gt=0) + """Receiver staging capacity per buffer. None stages a complete update.""" + + staging_buffers_count: int = Field(1, ge=1) + """Number of receiver buffers. Two overlap the next read with installation.""" + + +WeightBroadcastSection: TypeAlias = Annotated[ + FileSystemWeightBroadcastConfig | NCCLWeightBroadcastSection | ModelExpressWeightBroadcastSection, + Field(discriminator="type"), +] +"""Weight transfer from trainer to inference, as ``rl`` and ``sft`` take it.""" + + +class NCCLWeightBroadcastConfig(NCCLWeightBroadcastSection): + """``[weight_broadcast]`` over NCCL as a process takes it: the section plus the rendezvous host and the + transfer group size.""" + + host: str = "localhost" + """Rendezvous host: the address the trainer binds, and the trainer's address for the other processes.""" + + inference_world_size: int = Field(1, ge=1) + """Inference GPUs across all engines. Each one joins the transfer group.""" + + +class ModelExpressWeightBroadcastConfig(ModelExpressWeightBroadcastSection): + """``[weight_broadcast]`` through ModelExpress as a process takes it: the section plus the transfer group + size.""" + + inference_world_size: int = Field(1, ge=1) + """Inference GPUs across all engines. Each one pulls its shards from the server.""" + + +WeightBroadcastConfig: TypeAlias = Annotated[ + FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | ModelExpressWeightBroadcastConfig, + Field(discriminator="type"), +] +"""Weight transfer from trainer to inference, as a process takes it.""" + + +def weight_broadcast_config( + section: WeightBroadcastSection, inference_world_size: int, nccl_host: str = "localhost" +) -> dict[str, Any]: + """The ``WeightBroadcastConfig`` fields of a process: ``section`` plus the transfer group size and the + NCCL rendezvous host.""" + config = dump_resolved_config(section) + if section.type != "filesystem": + config["inference_world_size"] = inference_world_size + if section.type == "nccl": + config["host"] = nccl_host + return config diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/__init__.py b/packages/prime-rl-configs/src/prime_rl/configs/components/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/engine/__init__.py b/packages/prime-rl-configs/src/prime_rl/configs/components/engine/__init__.py new file mode 100644 index 00000000000..75dca290bbc --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/engine/__init__.py @@ -0,0 +1,310 @@ +import os +from argparse import Namespace +from typing import Any, Literal + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig, ComponentConfig +from prime_rl.configs.blocks.log import LogConfig +from prime_rl.configs.blocks.run import EnvVars +from prime_rl.configs.components.engine.deployment import PDKVTransferConfig +from prime_rl.configs.components.engine.kv_cache import ( + HiSparseConfig, + KVCacheOffloadConfig, + NativeKVCacheOffloadConfig, +) +from prime_rl.configs.components.engine.vllm import ServerConfig, VllmConfig + + +class EngineWeightBroadcastConfig(BaseConfig): + """Weight broadcast that an engine receives updated weights over.""" + + type: Literal["nccl", "filesystem", "modelexpress"] = "filesystem" + """Weight broadcast transport.""" + + +class EngineSection(BaseConfig): + """The settings of one inference engine that a user writes: a vLLM server without a router.""" + + server: ServerConfig = ServerConfig() + """API server of the engine: bind address, liveness timeout and admin token.""" + + vllm: VllmConfig = Field(default_factory=VllmConfig) + """vLLM server arguments, under vLLM's own argument names. Unknown fields pass through verbatim.""" + + log: LogConfig = LogConfig() + """Logging configuration.""" + + env_vars: EnvVars = {} + """Extra environment variables for the inference server process(es). Merged on top of the launcher defaults.""" + + use_deep_gemm: bool = False + """Enable vLLM DeepGEMM FP8 kernels ``VLLM_USE_DEEP_GEMM=1``. Only works with block-wise FP8 quantization (e.g. GLM-5-FP8).""" + + kv_cache_offload: KVCacheOffloadConfig | None = None + """KV cache offload for inference workers, as composable CPU/disk tiers. Discriminated on ``type``: ``native`` (vLLM ``OffloadingConnector``/``TieringOffloadingSpec``, self-contained) or ``mooncake`` (per-node Mooncake distributed store). Disaggregated P/D combines the chosen connector with NIXL through ``MultiConnector``.""" + + hisparse: HiSparseConfig | None = None + """Enable vLLM HiSparse (experimental). Under disaggregated P/D it applies to decode instances only, and decode must not offload KV (``deployment.decode_kv_cache_offload = None``). vLLM checks its requirements at startup (a DSA model, no pipeline or decode context parallelism).""" + + kv_load_failure_policy: Literal["recompute", "fail"] | None = None + """What vLLM does when a KV load from another instance fails or is declined (``kv_transfer_config.kv_load_failure_policy``): ``recompute`` computes the missing tokens locally, ``fail`` ends the request with an error. None keeps vLLM's default (``fail``). Under bidirectional P/D, prefill defaults to ``recompute``: it declines reading decode blocks that are about to expire, and that turn should then prefill locally instead of failing.""" + + enable_return_sampling_mask: bool = False + """Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling and for recorded sampler logprobs (``sampling.logprobs``, set by score centering), which are captured next to the mask. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs. Requests opt in with ``extra_args.prl_replay = true``; only these requests require positive temperature. Their supports are captured whole, so top-p alone needs no top-k. Evaluation requests need not opt in. Under speculative decoding each accepted position carries its own support, and sampler logprobs need truncated (replayed) sampling.""" + + sampling_support_capacity: int = Field(16 * 2**20, ge=1) + """Entries (8 bytes each) in the per-step device buffer that holds captured sampling supports: the kept ids of every replayed request in one sampling step, plus sampler rows. Requests whose supports do not fit fail with an explicit error instead of being truncated; the server logs the maximum per-step total every minute.""" + + enable_fp32_lm_head: bool = True + """Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented natively by vLLM's LogitsProcessor, which reads ``head_dtype`` off the HF config, so this flag injects ``hf_overrides = {"head_dtype": "float32"}``.""" + + enable_fp32_router_logits: bool = True + """Request FP32 MoE router logits via ``hf_overrides = {"moe_router_dtype": "float32"}``. Operand and weight precision depend on the serving model implementation; FP32 logits do not imply FP32 gate weights. Trainer routers use BF16 operands with FP32 logits; configure serving gate precision explicitly to match.""" + + @model_validator(mode="after") + def auto_setup_kv_cache_offload(self): + offloads = [offload for offload in self.kv_cache_offload_by_role.values() if offload is not None] + if len({offload.disk.path for offload in offloads if offload.type == "mooncake" and offload.disk}) > 1: + raise ValueError("Mooncake roles share one store master, so their disk tiers must use the same path.") + if offloads: + if self.vllm.enable_prefix_caching is False: + raise ValueError("KV cache offloading requires inference.vllm.enable_prefix_caching to be true.") + if "enable_prefix_caching" not in self.vllm.model_fields_set: + self.vllm.enable_prefix_caching = True + + return self + + @model_validator(mode="after") + def validate_hisparse_decode_offload(self): + """A HiSparse decode instance keeps its sparse-MLA KV in a host-resident layout: native offload rejects it, and Mooncake stores it under the same keys as prefill's regular layout, so prefill fails to load it.""" + if self.hisparse is None: + return self + if self.kv_cache_offload_by_role.get("decode") is not None: + raise ValueError( + "HiSparse runs on decode, which cannot also offload KV: set " + "inference.deployment.decode_kv_cache_offload = None (prefill offload is supported)." + ) + if isinstance(self.kv_cache_offload_by_role.get("all"), NativeKVCacheOffloadConfig): + raise ValueError("HiSparse does not work with native KV cache offload: use Mooncake or no offload.") + return self + + @property + def kv_cache_offload_by_role(self) -> dict[str, KVCacheOffloadConfig | None]: + """KV cache offload per P/D role (``prefill``/``decode``), or ``all`` when the config has no roles.""" + return {"all": self.kv_cache_offload} + + @property + def vllm_overrides(self) -> list[dict[str, Any]]: + """The untyped vLLM arguments of each engine this config starts.""" + return [self.vllm.model_extra or {}] + + +class EngineConfig(EngineSection, ComponentConfig): + """Config of one inference engine process. The launchers fill the fields it adds to ``EngineSection``.""" + + weight_broadcast: EngineWeightBroadcastConfig = EngineWeightBroadcastConfig() + """Transport the engine receives updated weights over. It selects the vLLM worker extension.""" + + pd_kv_transfer: PDKVTransferConfig | None = None + """NIXL KV transfer to the other role of a disaggregated deployment. The launcher sets it on the prefill and + decode engines. None for an engine that is not part of a disaggregated deployment.""" + + def build_kv_transfer_config(self) -> dict[str, Any] | None: + """Build the single vLLM ``kv_transfer_config`` from the transfer, offload and HiSparse connectors. + + Disaggregated P/D always uses NIXL for prefill→decode transfer. KV cache offload and + HiSparse (if configured) contribute their own connectors. Several connectors are composed + via ``MultiConnector``. Returns None when none applies. + """ + connectors: list[dict[str, Any]] = [] + pd = self.pd_kv_transfer + bidirectional = pd.bidirectional if pd is not None else None + spill = bidirectional.spill_to_store if bidirectional is not None else None + if pd is not None: + nixl_extra: dict[str, Any] = {"num_threads": 1} + if bidirectional is not None: + nixl_extra |= { + "bidirectional_kv_xfer": True, + "decoder_kv_blocks_ttl": bidirectional.decode_blocks_ttl_s, + } + if spill is not None: + nixl_extra |= { + "prime_rl_spill_lead_s": spill.start_before_expiry_s, + "prime_rl_spill_fetch_wait_s": spill.fetch_wait_s, + } + connectors.append( + {"kv_connector": "NixlConnector", "kv_role": "kv_both", "kv_connector_extra_config": nixl_extra} + ) + if self.kv_cache_offload is not None: + connector = self.kv_cache_offload.to_connector_dict() + if spill is not None and connector["kv_connector"] == "MooncakeStoreConnector": + # Capacity-only: the connector mounts the store client for the spill and does no lookups, loads or + # saves of its own. + connector["kv_role"] = "kv_consumer" + connector["kv_connector_extra_config"]["enable_lookup"] = False + elif pd is not None and connector["kv_connector"] == "MooncakeStoreConnector": + # Decode instances also store the KV they generate, so the next turn's prefill can load it. + connector["kv_connector_extra_config"]["save_decode_cache"] = True + connectors.append(connector) + if self.hisparse is not None: + connectors.append( + { + "kv_connector": "HiSparseConnector", + "kv_role": "kv_both", + "kv_connector_extra_config": {"host_pool_gib": self.hisparse.host_pool_gib}, + } + ) + + if not connectors: + return None + if len(connectors) == 1: + config = connectors[0] + else: + config = { + "kv_connector": "MultiConnector", + "kv_role": "kv_both", + "kv_connector_extra_config": {"connectors": connectors}, + } + if self.kv_load_failure_policy is not None: + # The scheduler reads the policy from the top-level config only, also under MultiConnector. + config["kv_load_failure_policy"] = self.kv_load_failure_policy + return config + + # Fields vLLM rejects as None — omitted from the namespace so vLLM applies its + # own default (e.g. quantization is inferred from the checkpoint). + _OMIT_IF_NONE = frozenset( + {"chat_template", "tool_call_parser", "reasoning_parser", "lora_target_modules", "quantization", "rope_scaling"} + ) + + def to_namespace(self) -> Namespace: + """Dump the server + vllm sections into a vLLM-compatible Namespace.""" + namespace = Namespace( + host=self.server.host, + port=self.server.port, + liveness_timeout_seconds=self.server.liveness_timeout_seconds, + admin_token_var=self.server.admin_token_var, + ) + + extra_fields = self.vllm.model_extra or {} + for key in (*type(self.vllm).model_fields, *extra_fields): + value = getattr(self.vllm, key) + # None extras are dropped too: `--vllm.foo None` means "use vLLM's default". + if value is None and (key in self._OMIT_IF_NONE or key in extra_fields): + continue + setattr(namespace, key, value) + + # Auto tool choice is gated on a tool-call parser being resolved, unless + # explicitly overridden. + if "enable_auto_tool_choice" not in extra_fields: + namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser") + + # Default `logprobs_mode` to `processed_logprobs` + if not hasattr(namespace, "logprobs_mode"): + namespace.logprobs_mode = "processed_logprobs" + + # Always surface cached prompt tokens in `usage` — the router's + # cache-discount billing counters parse them off /inference/v1/generate. + if "enable_prompt_tokens_details" not in extra_fields: + namespace.enable_prompt_tokens_details = True + + # The orchestrator generates through /inference/v1/generate, a scale-out + # endpoint that vLLM registers only with `--enable-scale-out`. + if "enable_scale_out" not in extra_fields: + namespace.enable_scale_out = True + + # vLLM's DeepseekV2-family (and transformers-backend MoE) gates read + # `moe_router_dtype` off the HF config to pick the router logits dtype. + if self.enable_fp32_router_logits: + hf_overrides = getattr(namespace, "hf_overrides", None) or {} + hf_overrides.setdefault("moe_router_dtype", "float32") + namespace.hf_overrides = hf_overrides + + # vLLM's LogitsProcessor reads `head_dtype` off the HF config to pick the + # lm_head projection dtype (fp32 runs as a native bf16xbf16 -> fp32 GEMM). + if self.enable_fp32_lm_head: + hf_overrides = getattr(namespace, "hf_overrides", None) or {} + hf_overrides.setdefault("head_dtype", "float32") + namespace.hf_overrides = hf_overrides + + if self.enable_return_sampling_mask: + namespace.return_sampling_mask = True + + # The LoRA adapter is registered under the model name clients send, and vLLM rejects + # an adapter named like a served base model, so serve the base under another name. + if self.vllm.enable_lora and "served_model_name" not in extra_fields: + namespace.served_model_name = [f"{self.vllm.model}-base"] + + kv_transfer_config = self.build_kv_transfer_config() + if kv_transfer_config is not None: + namespace.kv_transfer_config = kv_transfer_config + + default_moe_backend = os.environ.get("PRL_DEFAULT_MOE_BACKEND") + if default_moe_backend and getattr(namespace, "moe_backend", None) is None: + namespace.moe_backend = default_moe_backend + + return namespace + + +def set_max_lora_rank(vllm: VllmConfig, rank: int) -> None: + """Serve adapters of the trainer's LoRA ``rank``. An explicit larger ``max_lora_rank`` stays.""" + if "max_lora_rank" in vllm.model_fields_set and vllm.max_lora_rank is not None: + if vllm.max_lora_rank < rank: + raise ValueError( + f"inference.vllm.max_lora_rank ({vllm.max_lora_rank}) is below the trainer's LoRA rank ({rank}). " + "Remove it to inherit the LoRA rank." + ) + return + vllm.max_lora_rank = rank + + +def reject_explicit_data_parallel_size(vllm: VllmConfig, num_infer_gpus: int) -> None: + """The launchers size data parallelism to fill the inference GPUs; an explicit size that does not fill them + is an error, not a value to replace.""" + if "data_parallel_size" in vllm.model_fields_set: + raise ValueError( + f"inference.vllm.data_parallel_size ({vllm.data_parallel_size}) × tensor_parallel_size " + f"({vllm.tensor_parallel_size}) does not match the {num_infer_gpus} inference GPUs of the deployment. " + "Remove data_parallel_size to fill the GPUs." + ) + + +MODEL_NAME_DRAFT_METHODS = ("mtp", "dspark") + + +def setup_dummy_load(engine: EngineSection, dummy: bool) -> None: + """With ``dummy``, the server starts with placeholder weights (``load_format = "dummy"``), which the trainer's + startup broadcast replaces, unless ``load_format`` is set explicitly. That is the case when the trainer's weights + are not HF weights stored at ``model.name``: a ``scratch`` init, known from the config, or a checkpoint step + directory as ``model.name``, which the inference server detects since only it is sure to see the path. HF weights + still load from disk: vLLM checks that a load from disk writes every weight, but no weight transfer checks that the + trainer's update does, so a weight the update misses keeps its pretrained value instead of a placeholder. + + Under a dummy-loaded target, a speculative draft with its own ``model`` still loads it from disk, except a + ``draft_model`` draft, which vLLM loads with the target's load format. A draft that reads its weights from + ``model.name`` (MTP, DSpark without a ``model``) gets none.""" + if dummy and "load_format" not in (engine.vllm.model_extra or {}): + engine.vllm.load_format = "dummy" + if getattr(engine.vllm, "load_format", None) != "dummy": + return + for override in engine.vllm_overrides: + draft = next((value for key, value in override.items() if key.replace("-", "_") == "speculative_config"), None) + if not draft: + continue + draft_keys = {key.replace("-", "_") for key in draft} + # vLLM treats a draft with a model but no method as a draft_model draft + method = str(draft.get("method") or ("draft_model" if "model" in draft_keys else None)) + if method == "draft_model": + raise ValueError( + 'vLLM loads a speculative_config method "draft_model" draft with the target\'s load format, here ' + 'dummy: use a method such as "eagle3", or load the target from disk (HF weights at model.name with model.init.type = "pretrained", or an explicit engine.vllm.load_format)' + ) + if "model" in draft_keys: + if "draft_load_config" not in draft_keys: + draft["draft_load_config"] = {"load_format": "auto"} + continue + if method in MODEL_NAME_DRAFT_METHODS or method.endswith("_mtp"): + raise ValueError( + f'speculative_config method "{method}" reads its draft weights from model.name, which a dummy-loaded ' + 'server does not load: set speculative_config.model to a draft checkpoint, or load the target from disk (HF weights at model.name with model.init.type = "pretrained", or an explicit engine.vllm.load_format)' + ) diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/engine/deployment.py b/packages/prime-rl-configs/src/prime_rl/configs/components/engine/deployment.py new file mode 100644 index 00000000000..cc14b67630e --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/engine/deployment.py @@ -0,0 +1,163 @@ +from typing import Annotated, Any, Literal, TypeAlias + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig +from prime_rl.configs.blocks.run import EnvVars +from prime_rl.configs.components.engine.kv_cache import KVCacheOffloadConfig, SpillToStoreConfig + + +class BidirectionalKVTransferConfig(BaseConfig): + """Bidirectional NIXL KV transfer for multi-turn P/D (vLLM ``bidirectional_kv_xfer``). + + After a turn, decode keeps the turn's KV blocks (prompt and completion) for ``decode_blocks_ttl_s``. The router + remembers them per session (``x-session-id``) and hands them to the next turn's prefill, which reads them from + decode over NIXL and computes only the new tokens, instead of recomputing the conversation. Each handle is used at + most once: decode frees the blocks after the first read, so a retried turn falls back to a plain prefill.""" + + decode_blocks_ttl_s: int = Field(480, ge=1) + """How long decode keeps a finished turn's blocks for the next turn (``decoder_kv_blocks_ttl``). Retained blocks + occupy decode's KV cache until read or expired, so a long TTL with many idle sessions costs decode capacity.""" + + router_ttl_s: int | None = Field(None, ge=1) + """How long the router keeps a session's decode handle. Must be shorter than ``decode_blocks_ttl_s`` so the router + never hands out blocks decode has already released. Defaults to ``decode_blocks_ttl_s`` minus 30 s, or to + ``spill_to_store.fetchable_for_s`` with a spill.""" + + spill_to_store: SpillToStoreConfig | None = None + """Spill expiring turns to the Mooncake store. The router then keeps handles for + ``spill_to_store.fetchable_for_s``, past the lease: prefill finds such a handle expired and reads the store.""" + + @property + def effective_router_ttl_s(self) -> int: + if self.router_ttl_s is not None: + return self.router_ttl_s + if self.spill_to_store is not None: + return self.spill_to_store.fetchable_for_s + return max(1, self.decode_blocks_ttl_s - 30) + + @model_validator(mode="after") + def router_ttl_below_decode_ttl(self): + if self.spill_to_store is not None: + if self.decode_blocks_ttl_s <= self.spill_to_store.start_before_expiry_s: + raise ValueError( + "bidirectional_kv_transfer.decode_blocks_ttl_s must be longer than " + "spill_to_store.start_before_expiry_s: the spill would otherwise start as the turn finishes." + ) + return self + if self.effective_router_ttl_s >= self.decode_blocks_ttl_s: + raise ValueError( + "bidirectional_kv_transfer.router_ttl_s must be shorter than decode_blocks_ttl_s: the router would " + "otherwise hand out decode blocks that are already released." + ) + return self + + +class PDKVTransferConfig(BaseConfig): + """NIXL KV transfer between the prefill and decode engines of a disaggregated deployment.""" + + bidirectional: BidirectionalKVTransferConfig | None = None + """Bidirectional transfer: ``deployment.bidirectional_kv_transfer``. None transfers from prefill to decode + only.""" + + +class BaseInferenceDeploymentConfig(BaseConfig): + """Layout of the inference engines over nodes.""" + + gpus_per_node: int = 8 + """GPUs per node.""" + + +class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig): + """Inference on one node.""" + + type: Literal["single_node"] = "single_node" + + +# Multi-node inference: each node runs an independent vLLM replica. +class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig): + """Inference on several nodes. Each node runs an independent vLLM replica.""" + + type: Literal["multi_node"] = "multi_node" + + num_nodes: int = Field(2, ge=1) + """Inference nodes.""" + + +# Disaggregated prefill/decode inference. Each replica is split into separate +# prefill and decode node groups. Requires NIXL for KV transfer and a router for +# request routing. +class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig): + """Disaggregated prefill/decode (P/D) inference. Each replica splits into separate prefill and decode node + groups, with NIXL for KV transfer and a router in front.""" + + type: Literal["disaggregated"] = "disaggregated" + + prefill_nodes_per_replica: int = Field(1, ge=1) + """Nodes in each prefill vLLM instance.""" + + decode_nodes_per_replica: int = Field(1, ge=1) + """Nodes in each decode vLLM instance.""" + + num_prefill_replicas: int = Field(1, ge=1) + """Independent prefill vLLM instances.""" + + num_decode_replicas: int = Field(1, ge=1) + """Independent decode vLLM instances.""" + + prefill_port: int = 8100 + """Port for prefill vLLM instances.""" + + decode_port: int = 8200 + """Port for decode vLLM instances.""" + + prefill_env_vars: EnvVars = {} + """Extra environment variables exported only on prefill nodes.""" + + decode_env_vars: EnvVars = {} + """Extra environment variables exported only on decode nodes.""" + + prefill_vllm_overrides: dict[str, Any] = {} + """Extra vLLM config options for prefill engines only.""" + + decode_vllm_overrides: dict[str, Any] = {} + """Extra vLLM config options for decode engines only.""" + + prefill_kv_cache_offload: KVCacheOffloadConfig | Literal["inherit"] | None = "inherit" + """KV cache offload on prefill instances. ``inherit`` uses ``inference.kv_cache_offload``; None disables it.""" + + decode_kv_cache_offload: KVCacheOffloadConfig | Literal["inherit"] | None = "inherit" + """KV cache offload on decode instances. ``inherit`` uses ``inference.kv_cache_offload``; None disables it.""" + + bidirectional_kv_transfer: BidirectionalKVTransferConfig | None = None + """Bidirectional KV transfer: the next turn's prefill reads the previous turn's KV back from decode. Requires the + ``vllm-router`` router. None keeps one-way prefill-to-decode transfer.""" + + nixl_nic_affinity: bool = True + """Pin each single-GPU engine's NIXL/UCX traffic to the RDMA port nearest its GPU, on one rail + (``UCX_NET_DEVICES``, ``UCX_MAX_RMA_RAILS=1``). Spreading GPUDirect RDMA over every NIC sends traffic across + CPU sockets, which can stall the GPU under sustained P/D transfer load. Engines spanning several GPUs keep all + ports. Applied by the SLURM launchers only.""" + + @property + def num_prefill_nodes(self) -> int: + return self.prefill_nodes_per_replica * self.num_prefill_replicas + + @property + def num_decode_nodes(self) -> int: + return self.decode_nodes_per_replica * self.num_decode_replicas + + @property + def num_nodes(self) -> int: + return self.num_prefill_nodes + self.num_decode_nodes + + +InferenceDeploymentConfig: TypeAlias = Annotated[ + SingleNodeInferenceDeploymentConfig | MultiNodeInferenceDeploymentConfig | DisaggregatedInferenceDeploymentConfig, + Field(discriminator="type"), +] + + +def prefill_uses_deepep_high_throughput(overrides: dict[str, Any]) -> bool: + """vLLM cannot capture DeepEP high-throughput dispatch in a breakable CUDA graph.""" + return overrides.get("all2all_backend", "deepep_high_throughput") == "deepep_high_throughput" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/engine/kv_cache.py b/packages/prime-rl-configs/src/prime_rl/configs/components/engine/kv_cache.py new file mode 100644 index 00000000000..74b16aa2341 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/engine/kv_cache.py @@ -0,0 +1,130 @@ +from pathlib import Path +from typing import Annotated, Any, Literal, TypeAlias + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig + + +class CPUOffloadTier(BaseConfig): + """CPU/DRAM tier of KV cache offload.""" + + num_bytes: int = Field(..., ge=0) + """CPU/DRAM offload capacity. For the ``native`` backend this is vLLM's aggregate ``cpu_bytes_to_use`` (scaled across workers internally; must be positive). For the ``mooncake`` backend this is the per-node store client's DRAM segment (``-global_segment_size``); 0 connects the node to the shared pool without contributing storage.""" + + +class DiskOffloadTier(BaseConfig): + """Disk tier of KV cache offload, behind the CPU tier.""" + + path: Path + """Filesystem root for the disk tier. For ``native`` this is the ``fs`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota).""" + + +class BaseKVCacheOffloadConfig(BaseConfig): + """KV cache offload tiers that every offload backend has.""" + + cpu: CPUOffloadTier | None = None + """CPU/DRAM offload tier. Always required — disk-only offload is not supported.""" + + disk: DiskOffloadTier | None = None + """Optional disk tier, layered behind the CPU tier (GPU → DRAM → disk).""" + + @model_validator(mode="after") + def valid_tiers(self): + # Both backends support only two shapes: cpu-only or cpu+disk. Native disk + # tiering needs a CPU primary tier; Mooncake standalone-store needs a DRAM + # staging tier. Disk-only is rejected for both. + if self.cpu is None: + raise ValueError("inference.kv_cache_offload requires a cpu tier (disk-only offload is not supported).") + return self + + +class NativeKVCacheOffloadConfig(BaseKVCacheOffloadConfig): + """vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs`` disk secondary). Fully self-contained — no external processes.""" + + type: Literal["native"] = "native" + + @model_validator(mode="after") + def positive_cpu_capacity(self): + if self.cpu is not None and self.cpu.num_bytes == 0: + raise ValueError("Native KV cache offload requires a positive cpu.num_bytes.") + return self + + def to_connector_dict(self) -> dict[str, Any]: + assert self.cpu is not None + extra: dict[str, Any] = {"cpu_bytes_to_use": int(self.cpu.num_bytes)} + if self.disk is not None: + extra["spec_name"] = "TieringOffloadingSpec" + extra["secondary_tiers"] = [{"type": "fs", "root_dir": str(self.disk.path)}] + return { + "kv_connector": "OffloadingConnector", + "kv_role": "kv_both", + "kv_connector_extra_config": extra, + } + + +class MooncakeKVCacheOffloadConfig(BaseKVCacheOffloadConfig): + """Mooncake distributed store offloading (SLURM only). One ``mooncake_master`` + metadata server runs on the head inference node; every node runs a ``mooncake_client`` contributing its segment to the single shared pool, so prefixes cached on any node are reusable by all. The cpu tier sizes each node's DRAM segment; the optional disk tier adds an SSD tier.""" + + type: Literal["mooncake"] = "mooncake" + + device_name: str = "" + """RDMA device name(s) for the store (empty = auto-detect).""" + + lease_ttl_s: float = Field(30.0, gt=0) + """How long the master protects a newly written or read KV object from eviction (``-default_kv_lease_ttl``). + Leased objects are skipped by eviction, so a lease close to the time the pool takes to turn over leaves only + fresh, not yet reused prefixes to evict, and one longer than the time it takes to fill blocks eviction: puts + then fail and the store stops caching. The P/D prefill-to-decode handoff goes over NIXL and is governed by its + own ``kv_lease_duration``, not this lease. Under P/D the larger of the two roles' values applies, since one + master serves both.""" + + lookup_async: bool = True + """Look up a request's prefix in the store on a background thread (``lookup_async``), starting when the request + arrives. A synchronous lookup blocks the scheduler for its whole duration (tens of ms for a long prompt, one key + per KV block and group), and with data parallelism the ranks of a node step together, so one rank's lookup + stalls them all.""" + + def to_connector_dict(self) -> dict[str, Any]: + # Addresses/sizes/tiers are realized by the per-node store launch in the sbatch + # template (MOONCAKE_CONFIG_PATH JSON); blocks are keyed by model + parallel rank + + # content hash (no instance id), so the shared pool is reused across nodes/replicas. + return { + "kv_connector": "MooncakeStoreConnector", + "kv_role": "kv_both", + "kv_connector_extra_config": {"lookup_async": self.lookup_async}, + } + + +KVCacheOffloadConfig: TypeAlias = Annotated[ + NativeKVCacheOffloadConfig | MooncakeKVCacheOffloadConfig, Field(discriminator="type") +] + + +class HiSparseConfig(BaseConfig): + """vLLM HiSparse for DSA sparse-MLA models (e.g. GLM-5.x): the sparse-MLA KV lives in a pinned host pool and decode attention reads per-request GPU buffers of the indexer top-k rows.""" + + host_pool_gib: float = Field(..., gt=0) + """Pinned host pool per GPU worker, in GiB (``HiSparseConnector`` ``host_pool_gib``). Budget ``GPUs per node × host_pool_gib`` against node RAM.""" + + +class SpillToStoreConfig(BaseConfig): + """Write a finished turn's KV from decode to the Mooncake store shortly before its lease ends unread, and let a + turn that returns later fetch it from there (``prime_rl.inference.kv_spill``). + + Without it, decode pins every idle session's KV for the whole ``decode_blocks_ttl_s``, and a turn that returns + after the lease is recomputed in full. With it the lease can be a few tens of seconds: decode's KV cache then + holds mostly running requests, and late turns cost one store read. Both roles need a Mooncake + ``kv_cache_offload``; it only provides the store, vLLM's own store lookups, loads and saves stay off.""" + + start_before_expiry_s: float = Field(10.0, gt=5) + """How long before the lease ends the put starts. Prefill stops reading from decode 5 s before the lease ends, + so the put must be done by then.""" + + fetch_wait_s: float = Field(6.0, ge=0) + """How long a fetch waits for the objects of a put that is still in flight before it gives up and the turn is + recomputed.""" + + fetchable_for_s: int = Field(3600, ge=1) + """How long the router keeps a session's handle, and so how long after a turn its KV can still be fetched from + the store (if the store has not evicted it).""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/engine/vllm.py b/packages/prime-rl-configs/src/prime_rl/configs/components/engine/vllm.py new file mode 100644 index 00000000000..00a24fa2299 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/engine/vllm.py @@ -0,0 +1,207 @@ +import json +import re +import warnings +from typing import Any, Literal + +from pydantic import ConfigDict, Field, model_validator + +from prime_rl.configs.base import BaseConfig +from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser + +# TODO: Set thinking/ solution budget + + +class ServerConfig(BaseConfig): + """API server of an inference engine.""" + + host: str | None = None + """Host to bind to (None = vLLM's default).""" + + port: int = 8000 + """Port to bind to.""" + + liveness_timeout_seconds: float = Field(30.0, gt=0) + """Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. Health checks polling this endpoint should use a timeout at least this high.""" + + admin_token_var: str = "PRIME_RL_ADMIN_TOKEN" + """Name of the environment variable holding the admin token. When it, or ``_SHA256`` holding the token's SHA-256 digest, is set, the admin routes (weight updates, pause/resume, broadcaster setup, LoRA loading) reject requests whose ``X-Prime-Admin-Token`` header does not match it.""" + + require_admin_token: bool = False + """Refuse to start when neither ``admin_token_var`` nor its ``_SHA256`` digest variable is set, instead of serving the admin routes without authentication.""" + + +# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so +# tiny adapters round up to 8. Hardcoded rather than imported: prime-rl-configs does +# not depend on vLLM, and importing it costs seconds in every config-parsing process. +VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512) + +QuantizationType = Literal["fp8_per_block", "mxfp8", "online"] + + +class VllmConfig(BaseConfig): + """Arguments forwarded to the vLLM server, under vLLM's own argument names + (https://docs.vllm.ai/en/latest/configuration/engine_args.html). + + The fields below are the arguments prime-rl types, defaults, or reads back; + any other vLLM argument can be set as well (``[inference.vllm] max_num_seqs = 256`` + or ``--vllm.max-num-seqs 256``) and passes through to the server verbatim. + + Parser fields (``tool_call_parser``, ``reasoning_parser``) default to ``"auto"``, + which resolves to a concrete parser name at validation time from the tokenizer name, then the model name. + Set to ``None`` to disable. + """ + + model_config = ConfigDict(extra="allow") + + model: str = "Qwen/Qwen3-0.6B" + """HF model name or local path.""" + + max_model_len: int | None = None + """Maximum model context length. If None, uses the model config's value.""" + + chat_template: str | None = None + """Chat template — a Jinja2 template string or path to a template file. If None, uses the model's default.""" + + tool_call_parser: str | None = "auto" + """Tool-call parser. Set to ``"auto"`` to detect from the tokenizer name, then the model name, or ``None`` to disable.""" + + reasoning_parser: str | None = "auto" + """Parser for extracting reasoning content from model outputs. Set to ``"auto"`` to detect from the tokenizer name, then the model name, or ``None`` to disable.""" + + rope_scaling: dict[str, Any] | str | None = None + """RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``).""" + + tensor_parallel_size: int = 1 + """Tensor parallel size.""" + + data_parallel_size: int = Field(1, ge=1) + """Data parallel size.""" + + data_parallel_size_local: int | None = Field(None, ge=1) + """Data parallel replicas to run on this node (None = all ``data_parallel_size`` replicas).""" + + data_parallel_rpc_port: int = Field(13345, ge=1, le=65535) + """RPC port for data parallel communication.""" + + api_server_count: int = Field(1, ge=0) + """API servers to run. Set to 0 for headless mode.""" + + gpu_memory_utilization: float = 0.9 + """GPU memory utilization.""" + + enable_prefix_caching: bool | None = None + """Enable prefix caching (None = vLLM's default). KV cache offload turns it on when unset.""" + + quantization: QuantizationType | None = None + """Online inference quantization method. If None, vLLM infers it from the checkpoint. ``"online"`` takes the + per-layer-kind schemes from ``quantization_config``, e.g. ``{linear = "mxfp8", moe = "nvfp4_per_token"}``.""" + + enable_lora: bool = False + """Enable LoRA.""" + + max_lora_rank: int | None = None + """Maximum LoRA rank. Rounded up to the nearest value vLLM accepts. If None, the ``rl`` and ``sft`` + entrypoints set the trainer's LoRA rank.""" + + lora_target_modules: list[str] | None = None + """LoRA target modules (None = vLLM's default).""" + + enable_expert_parallel: bool = False + """Enable expert parallelism for MoE models.""" + + enable_eplb: bool = False + """Enable expert parallel load balancer (EPLB).""" + + enable_ep_weight_filter: bool = True + """Skip non-local expert weights at load time under expert parallelism, so each + rank reads only its own expert shard from disk. No-op for non-MoE models, when + expert parallelism is disabled, or under EPLB (redundant expert slots need all + logical expert weights).""" + + enable_return_routed_experts: bool = False + """Return routed experts in responses.""" + + @model_validator(mode="before") + @classmethod + def parse_extra_values(cls, data: dict) -> dict: + """Normalize pass-through (untyped) entries: kebab-case keys become snake_case, + and string values — which is how CLI overrides arrive — are JSON-parsed so + ``--vllm.max-num-seqs 256`` lands as an int and ``--vllm.compilation-config + '{"cudagraph_mode": "NONE"}'`` as a dict. Non-JSON strings stay strings.""" + if not isinstance(data, dict): + return data + for key in [k for k in data if k not in cls.model_fields]: + value = data.pop(key) + if isinstance(value, str): + try: + value = json.loads(value) + except json.JSONDecodeError: + pass + data[key.replace("-", "_")] = value + return data + + @model_validator(mode="after") + def auto_resolve_parsers(self): + """Resolve ``"auto"`` parser values to concrete parser names from the tokenizer name, then the model name. + + Runs after ``RLConfig.auto_setup_shared_configs`` (mode=before) has + propagated the shared ``[model] name`` and ``[tokenizer] name`` into ``inference.vllm``, so the + names are set even when only the shared blocks specify them. + """ + tokenizer = (self.model_extra or {}).get("tokenizer") + names = [name for name in (tokenizer, self.model) if name] + unresolved = [] + for field, resolve in ( + ("tool_call_parser", resolve_tool_call_parser), + ("reasoning_parser", resolve_reasoning_parser), + ): + if getattr(self, field) == "auto": + parser = next((parser for name in names if (parser := resolve(name))), None) + setattr(self, field, parser) + if parser is None: + unresolved.append(field) + if unresolved and tokenizer is None and not re.fullmatch(r"[\w.-]+/[\w.-]+", self.model): + warnings.warn( + f"No {' or '.join(unresolved)} matches the local model {self.model}: set tokenizer.name to the HF " + "model name to pick them", + stacklevel=2, + ) + return self + + @model_validator(mode="after") + def auto_setup_max_lora_rank(self): + """Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value. + + vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512). + This validator ensures that any configured rank is rounded up to the minimum valid value + that can serve adapters of the requested rank. + """ + if self.max_lora_rank is not None: + original_rank = self.max_lora_rank + for valid_rank in VALID_VLLM_LORA_RANKS: + if valid_rank >= self.max_lora_rank: + self.max_lora_rank = valid_rank + break + else: + raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}") + return self + + @model_validator(mode="after") + def auto_setup_api_server_count(self): + """ + Ensures that we have at least as many API servers as data parallel + size. Unless LoRA is enabled, in which case only one API server is + supported (vLLM limitation). + """ + if self.model_extra and self.model_extra.get("headless", False): + self.api_server_count = 0 + return self + + if "api_server_count" not in self.model_fields_set: + min_api_server_count = self.data_parallel_size_local or self.data_parallel_size + if self.api_server_count < min_api_server_count: + self.api_server_count = min_api_server_count + + if self.enable_lora: + self.api_server_count = 1 # LoRA requires only one API server + return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/env_worker_pool.py b/packages/prime-rl-configs/src/prime_rl/configs/components/env_worker_pool.py similarity index 74% rename from packages/prime-rl-configs/src/prime_rl/configs/env_worker_pool.py rename to packages/prime-rl-configs/src/prime_rl/configs/components/env_worker_pool.py index fd07691bc06..4b77cc04a53 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/env_worker_pool.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/env_worker_pool.py @@ -5,11 +5,12 @@ import verifiers.v1 as vf from pydantic import Field, SerializeAsAny, model_validator -from prime_rl.configs.shared import LogConfig -from prime_rl.utils.config import BaseConfig, default_output_dir, dump_resolved_config +from prime_rl.configs.base import BaseConfig, ComponentConfig +from prime_rl.configs.blocks.log import LogConfig +from prime_rl.utils.config import default_output_dir, dump_resolved_config if TYPE_CHECKING: - from prime_rl.configs.orchestrator import EnvConfig + from prime_rl.configs.components.orchestrator.sources import EnvConfig class StaticPoolConfig(BaseConfig): @@ -50,7 +51,7 @@ class ServeConfig(BaseConfig): episode bound.""" pool: PoolConfig = Field(default_factory=ElasticPoolConfig) - """Worker-pool sizing. `elastic` (default) starts at one worker and scales up on + """Worker-pool sizing. `elastic` starts at one worker and scales up on demand; `static` pre-spawns a fixed `num_workers`.""" address: str | None = None """ZMQ address the pool's broker binds (and clients connect to). None binds an @@ -62,7 +63,7 @@ class ServeConfig(BaseConfig): """How the replica's sample server scores kept samples.""" -class EnvWorkerPoolConfig(BaseConfig): +class EnvWorkerPoolConfig(ComponentConfig): """``uv run env-worker-pool``: one source's env and its broker/worker pool replica. Launchers write one config per managed train/eval source. Each replica's broker publishes its bound address to ``address_file``; its workers execute episodes.""" @@ -74,9 +75,9 @@ class EnvWorkerPoolConfig(BaseConfig): """How it's served: the worker pool, the bind address, each worker's episode bound.""" address_file: Path | None = None - """Publish the bound address to this file once serving. Set by the launchers for the - pools they spawn, so the address never has to be agreed on up front (``serve.address`` - unset binds an OS-assigned port).""" + """Publish the bound address to this file once serving. The launchers pass it at start + (``--address-file``) for the pools they spawn, so the address never has to be agreed on up + front (``serve.address`` unset binds an OS-assigned port).""" store_dir: Path | None = None """Keep finished episodes' training arrays as files in a directory of this pool's @@ -86,9 +87,10 @@ class EnvWorkerPoolConfig(BaseConfig): on the node. Set by the ``rl`` launcher for ``rollout_transport.retain``.""" log: LogConfig = LogConfig() + """Logging of the env worker pool process.""" output_dir: Path = Field(default_factory=default_output_dir) - """Directory to write outputs to — logs and any generated artifacts are written as subdirectories. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" + """The only directory under which the pool writes checkpoint files. The launchers set it to the run's checkpoint directory. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" @model_validator(mode="before") @classmethod @@ -112,25 +114,23 @@ def validate_env(self): def env_worker_pool_config( - source: "EnvConfig", - log: LogConfig, - output_dir: Path, - *, - address_file: Path | None = None, - store_dir: Path | None = None, -) -> dict: + source: "EnvConfig", log: LogConfig, output_dir: Path, *, store_dir: Path | None = None +) -> EnvWorkerPoolConfig: """The ``EnvWorkerPoolConfig`` that runs one source's env: its env and serve blocks; its other knobs (sampling, algo, name, ...) stay client-side. ``output_dir`` is the run's checkpoint root, where the pool keeps checkpoint files.""" source_dict = dump_resolved_config(source) - config = { - "env": source_dict["env"], - "serve": source_dict.get("serve") or {}, - "log": {"level": log.level, "json_logging": log.json_logging}, - "output_dir": output_dir.as_posix(), - } - if address_file is not None: - config["address_file"] = address_file.as_posix() - if store_dir is not None: - config["store_dir"] = store_dir.as_posix() - return config + return EnvWorkerPoolConfig.model_validate( + { + "env": source_dict["env"], + "serve": source_dict.get("serve") or {}, + "log": {"level": log.level, "json_logging": log.json_logging}, + "output_dir": output_dir.as_posix(), + "store_dir": store_dir.as_posix() if store_dir is not None else None, + } + ) + + +def env_worker_pool_key(split: str, name: str) -> str: + """How a run names one of its env worker pools, in ``components()`` and ``PRL_ENV_ADDRESSES``.""" + return f"envs/{split}/{name}" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/modelexpress_server.py b/packages/prime-rl-configs/src/prime_rl/configs/components/modelexpress_server.py new file mode 100644 index 00000000000..1b577502710 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/modelexpress_server.py @@ -0,0 +1,25 @@ +from pathlib import Path + +from pydantic import Field + +from prime_rl.configs.base import ComponentConfig +from prime_rl.configs.blocks.weight_broadcast import ModelExpressWeightBroadcastSection, WeightBroadcastSection + + +class ModelExpressServerConfig(ComponentConfig): + """Config of the run-scoped ModelExpress server process and its Valkey metadata store.""" + + port: int = Field(ge=1, le=65535) + """Port the server listens on: the port of the run's ``modelexpress`` weight broadcast.""" + + log_dir: Path + """Directory for the server's state and logs, which go to ``/modelexpress``.""" + + +def modelexpress_server_config( + weight_broadcast: WeightBroadcastSection | None, log_dir: Path +) -> ModelExpressServerConfig | None: + """The config of a run's ModelExpress server, or None unless ``weight_broadcast`` uses ModelExpress.""" + if not isinstance(weight_broadcast, ModelExpressWeightBroadcastSection): + return None + return ModelExpressServerConfig(port=weight_broadcast.port, log_dir=log_dir) diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/online_eval.py b/packages/prime-rl-configs/src/prime_rl/configs/components/online_eval.py new file mode 100644 index 00000000000..f50f0bc0b3f --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/online_eval.py @@ -0,0 +1,131 @@ +from pathlib import Path +from typing import Literal + +from pydantic import Field, model_validator + +from prime_rl.configs.base import ComponentConfig +from prime_rl.configs.blocks.ckpt import ResumeConfig +from prime_rl.configs.blocks.client import VLLMClientConfig +from prime_rl.configs.blocks.log import PeriodicLogConfig +from prime_rl.configs.blocks.monitors import MonitorsConfig +from prime_rl.configs.blocks.run import ControlConfig, HeartbeatConfig +from prime_rl.configs.blocks.weight_broadcast import WeightBroadcastConfig +from prime_rl.configs.components.orchestrator import ConcurrencyConfig +from prime_rl.configs.components.orchestrator.sources import EvalSourcesConfig, ScheduledEvalConfig +from prime_rl.utils.config import default_output_dir, resolve_client_roles + + +class ServedEvalConfig(EvalSourcesConfig): + """Eval sources run against a live inference server: the server's client and the + adaptive concurrency band.""" + + client: VLLMClientConfig = Field(default_factory=VLLMClientConfig) + """Client of the inference server evals run against.""" + + concurrency: ConcurrencyConfig = ConcurrencyConfig() + """Adaptive in-flight episode concurrency, sized by the same controller as + ``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it.""" + + inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None + """P/D role of each ``client.admin_base_url`` entry, in the same order: labels inference + metrics and lets the concurrency controller read prefill and decode engines apart.""" + + dispatch_per_minute: int | None = Field(None, ge=1) + """Rate limit on episode dispatch: at most this many episodes start per minute. Each + episode counts once, so a group of ``group_size`` episodes counts ``group_size`` + times. Use it for sandbox-backed environments to pace provisioning during + autoscaling. None disables it.""" + + control: ControlConfig | None = None + """Serve the eval's control API, which reads and sets its concurrency while it runs + (``GET``/``PUT /v1/concurrency``). If None, it takes no control requests.""" + + heartbeat: HeartbeatConfig | None = None + """BetterStack heartbeat for the run: pinged by landed episodes — the first + landed episode is the first beat, so the run's boot never shows up as a + stale-prone silence. Pings are throttled to at most one every + ``heartbeat.min_interval`` seconds. When episodes stop landing, the pings stop + and the heartbeat goes stale on Better Stack after its grace period. Size that + period + grace above the longest legitimate gap between episodes.""" + + @model_validator(mode="after") + def validate_inference_metrics_roles(self): + if self.inference_metrics_roles is not None: + admin_urls = self.client.admin_base_url or [] + try: + resolve_client_roles(len(admin_urls), self.inference_metrics_roles) + except ValueError as err: + raise ValueError( + f"inference_metrics_roles has {len(self.inference_metrics_roles)} role(s) but " + f"client.admin_base_url has {len(admin_urls)} URL(s): give one role per admin URL " + "(or one uniform block per pod under internal DP)" + ) from err + return self + + @property + def env_addresses(self) -> dict[tuple[str, str], str | None]: + """Where each eval source's env worker pool lives, keyed by ``("eval", resolved_name)``. + Same contract as ``OrchestratorConfig.env_addresses``: an explicit ``serve.address`` + is an externally managed server; None means the launcher spawns the server and the + eval learns its address from the file it publishes.""" + return {("eval", source.resolved_name): source.serve.address for source in self.source} + + +class SFTOnlineEvalSection(ScheduledEvalConfig, ServedEvalConfig): + """The ``[eval]`` block of the ``sft`` entrypoint: interval-driven eval sources against the + inference server that receives the trainer's weight broadcasts.""" + + cancel_on_new_checkpoint: bool = True + """Cancel unfinished episodes when a newer trainer checkpoint is ready. Disable to + finish every triggered eval epoch before loading later weights. The trainer can idle + while it waits for slow evals.""" + + +class SFTOnlineEvalConfig(SFTOnlineEvalSection, ComponentConfig): + """The config of the online-eval process the ``sft`` launcher spawns from ``[eval]``. The + process watches the broadcasts directory, moves the inference server onto each broadcast, + and runs the due sources against the updated weights. The launcher fills the fields below + from the resolved SFT config.""" + + model: str | None = None + """Name the inference server serves the model under. The name stays fixed across + weight updates (weights are swapped in place), so per-step results are told apart by + ``eval/{env}/policy_version``.""" + + weight_broadcast: WeightBroadcastConfig | None = None + """Weight transport. None reloads weights from the filesystem broadcasts.""" + + broadcasts_dir: Path | None = None + """Directory to watch for ``step_{n}`` weight broadcasts. Defaults to + ``/broadcasts``.""" + + max_steps: int | None = None + """Trainer step at which the run ends. The final checkpoint always fires every eval + env, and the process exits after processing it. If None, runs until terminated.""" + + resume: ResumeConfig | None = None + """The trainer's ``resume``. The process resumes at the step that the trainer resumes from.""" + + ckpt_output_dir: Path | None = None + """The trainer's checkpoint root (``ckpt.output_dir``, else the run directory). With ``resume`` and no step, + the process resumes at the latest complete checkpoint under it.""" + + resume_step: int | None = None + """Trainer step the run resumed from. Takes precedence over ``resume``. When set, the startup (base-model) + eval is skipped; set ``retrigger_on_resume`` to re-fire interval-aligned evals at this step.""" + + output_dir: Path = Field(default_factory=default_output_dir) + """The run directory, shared with the trainer. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" + + log: PeriodicLogConfig = PeriodicLogConfig() + """Logging of the online-eval process.""" + + monitors: MonitorsConfig = MonitorsConfig() + """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``): the + trainer's, so the process logs to the trainer's W&B and Prime runs.""" + + @model_validator(mode="after") + def auto_setup_broadcasts_dir(self): + if self.broadcasts_dir is None: + self.broadcasts_dir = self.output_dir / "broadcasts" + return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/__init__.py b/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/__init__.py new file mode 100644 index 00000000000..f7e54850c99 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/__init__.py @@ -0,0 +1,398 @@ +import warnings +from collections.abc import Callable +from pathlib import Path +from typing import Annotated, Literal + +from pydantic import Field, model_validator +from renderers import AutoRendererConfig, RendererConfig + +from prime_rl.configs.base import BaseConfig, ComponentConfig +from prime_rl.configs.blocks.algorithm import GRPOAlgoConfig +from prime_rl.configs.blocks.ckpt import ResumeConfig +from prime_rl.configs.blocks.client import PolicyClientConfig +from prime_rl.configs.blocks.log import PeriodicLogConfig +from prime_rl.configs.blocks.model import BaseModelConfig, TokenizerConfig +from prime_rl.configs.blocks.monitors import MonitorsConfig +from prime_rl.configs.blocks.run import ControlConfig, EnvVars, GCConfig, HeartbeatConfig +from prime_rl.configs.blocks.transport import ZMQTransportConfig +from prime_rl.configs.blocks.weight_broadcast import FileSystemWeightBroadcastConfig, WeightBroadcastConfig +from prime_rl.configs.components.orchestrator.ckpt import OrchestratorCheckpointConfig +from prime_rl.configs.components.orchestrator.sampling import TrainSamplingConfig +from prime_rl.configs.components.orchestrator.sources import EnvConfig, RLOnlineEvalConfig, TrainConfig +from prime_rl.utils.config import default_output_dir +from prime_rl.utils.diff import Live + + +class OrchestratorModelConfig(BaseModelConfig): + """The model being trained, plus the client of its live inference deployment.""" + + client: PolicyClientConfig = Field(default_factory=PolicyClientConfig) + """Client of the live deployment (``[orchestrator.model.client]``).""" + + +class ConcurrencyConfig(BaseConfig): + """Adaptive in-flight concurrency control. The orchestrator sizes the + in-flight episode cap from engine load; these fields only bound and + seed it.""" + + initial_inflight: Annotated[int | None, Live()] = Field(None, ge=1) + """Optional initial in-flight episodes to start from. Set it when a good value is known to skip the initial ramp; otherwise auto-derive a pessimistic bound at runtime.""" + + min_inflight: Annotated[int, Live()] = Field(1, ge=1) + """Minimum number of in-flight episodes. Set ``min_inflight = max_inflight`` to recover fixed concurrency.""" + + max_inflight: Annotated[int | None, Live()] = Field(None, ge=1) + """Maximum number of in-flight episodes. None leaves the cap to the controller. Set it to bound other external resources the episodes hold (e.g. sandboxes).""" + + @model_validator(mode="after") + def validate_bounds(self): + if self.max_inflight is not None: + if self.initial_inflight is not None and self.initial_inflight > self.max_inflight: + raise ValueError("concurrency.initial_inflight must not exceed concurrency.max_inflight") + if self.min_inflight > self.max_inflight: + raise ValueError("concurrency.min_inflight must not exceed concurrency.max_inflight") + return self + + +# Top-k set on truncated policy sampling that has none: the kept ids of every sampled token travel to the +# trainer, and top-p alone can keep most of the vocabulary on a flat distribution. +TRAIN_TOP_K_DEFAULT = 10000 + + +class OrchestratorControlConfig(ControlConfig): + """Control API of the orchestrator.""" + + port: int = Field(8041, ge=1, le=65535) + """Port the control API listens on, next to the trainer's 8040 on a single node.""" + + +class SpeculativeDecodingConfig(BaseConfig): + """Draft model for speculative decoding on the policy engines.""" + + draft: Annotated[Path, Live()] + """Draft checkpoint the inference engines serve; at launch, the one they started with. A live update + loads the new draft on every engine at the next policy weight sync. It must keep the served draft's + architecture and tensor shapes. A failed load restores the previous draft and reverts this value.""" + + +class OrchestratorSection(BaseConfig): + """The orchestrator settings that a user writes: the ``[orchestrator]`` block of ``rl``.""" + + model: OrchestratorModelConfig = OrchestratorModelConfig() + """The model being trained: its model fields plus the client of the live + vLLM deployment (``[orchestrator.model] name = ...`` with + ``[orchestrator.model.client]``). Algorithm components reference it as + ``"policy"``.""" + + train: TrainConfig = TrainConfig() + """Training sources and the defaults they inherit (``[orchestrator.train]``).""" + + tokenizer: TokenizerConfig = TokenizerConfig() + """Tokenizer. An unset ``name`` or ``trust_remote_code`` takes the value of ``model``.""" + + renderer: RendererConfig = AutoRendererConfig() + """Typed renderer config (``renderers.RendererConfig`` discriminated union), required — + training is renderer-only. ``"auto"`` resolves from + ``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.""" + + eval: RLOnlineEvalConfig | None = None + """Evaluation configuration.""" + + log: PeriodicLogConfig = PeriodicLogConfig() + """Logging of the orchestrator process.""" + + env_vars: EnvVars = {} + """Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults.""" + + collect_inference_metrics: bool = True + """Mirror inference-server metrics to W&B (requires wandb). The ``/metrics`` poll itself always runs — it feeds the concurrency controller.""" + + inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None + """P/D role of each policy admin client: labels inference metrics, and prefill engines pause before decode engines on weight updates.""" + + dispatch_per_minute: int | None = Field(None, ge=1) + """Rate limit on episode dispatch, shared by train and eval: at most this many episodes start per minute. Each episode counts once, so a group of ``group_size`` episodes counts ``group_size`` times. Recommended for sandbox-backed environments to pace provisioning during autoscaling. None disables it.""" + + batch_size: Annotated[int, Live()] = Field(128, ge=1) + """Samples to train on per step.""" + + constant_trainer_batch_size: bool = True + """Require each batch to reach its effective sample target.""" + + concurrency: ConcurrencyConfig = ConcurrencyConfig() + """Adaptive in-flight concurrency control (``[orchestrator.concurrency]``).""" + + gc: GCConfig | None = GCConfig() + """Garbage collection config. Freezes the startup heap, turns off automatic full collections (each one holds the GIL and stalls the event loop for as long as it takes to walk every held episode) and runs one every N steps instead. Young collections still run. Set to null to use Python's default GC behavior.""" + + seq_len: int = 2048 + """Training sequence length. Shorter samples are padded; longer samples are truncated.""" + + max_staleness: Annotated[int, Live()] = Field(8, ge=0) + """Maximum token staleness: the version a batch trains on (v{step-1}) minus the policy version that sampled the token, queue time included. Engines label each sampled token with the policy step (vLLM ``weight_versions``); unlabelled tokens (Dynamo engines) count as old as their episode's dispatch version. Older tokens are masked out of every loss component; the rest of the sample still trains with its own advantage and inference logprobs. A sample is dropped only when nothing is left to train. Rollouts are never cancelled for staleness, unless ``strict_staleness`` is set. Higher values yield better throughput at the cost of noisier, more off-policy updates.""" + + strict_staleness: Annotated[bool, Live()] = False + """Bound the staleness of every KV a trained token attends to, not only of the trained tokens. A train rollout counts as old as the policy version it was dispatched with, since its prompt and early-turn KVs come from that version. The orchestrator drops whole rollouts past ``max_staleness``: queued rollouts at the queue sweep, and in-flight groups before each weight update, which also saves their inference. Fresher tokens of a dropped rollout never train.""" + + heartbeat: HeartbeatConfig | None = None + """BetterStack heartbeat configuration for monitoring training progress.""" + + control: OrchestratorControlConfig | None = None + """Serve the orchestrator's control API (pause or checkpoint at a step the trainer + accepted, update the config live). If None, it takes no control requests.""" + + speculative_decoding: SpeculativeDecodingConfig | None = None + """Draft model served by the policy engines. Auto-filled by the ``rl`` entrypoint from the inference + servers' speculative config; set it for standalone orchestrator runs that should swap drafts.""" + + def dynamo_sampling_conflict(self) -> str | None: + """Why the policy sampling cannot run on Dynamo engines, or None. Dynamo's sidecar rejects + prime-rl's request extensions (``extra_args``), which sampling replay and logprob heads use.""" + for sampling in self.policy_samplings: + if sampling.truncates_distribution(): + return f"truncated sampling (top_p = {sampling.top_p}, top_k = {sampling.top_k}) needs sampling replay" + if sampling.logprobs: + return f"a logprob head (sampling.logprobs = {sampling.logprobs}, also set by score centering)" + return None + + @model_validator(mode="after") + def validate_dynamo_sampling(self): + dynamo = self.model.client.dynamo + if dynamo is not None and dynamo.enabled and (conflict := self.dynamo_sampling_conflict()): + raise ValueError(f"Dynamo engines cannot serve {conflict}: their sidecar rejects prime-rl's extra_args") + return self + + @model_validator(mode="after") + def validate_draft_swaps(self): + dynamo = self.model.client.dynamo + if self.speculative_decoding is not None and dynamo is not None and dynamo.enabled: + raise ValueError("Draft swaps use prime-rl's engine admin routes, which Dynamo deployments do not serve") + return self + + @model_validator(mode="after") + def auto_setup_tokenizer(self): + if self.tokenizer.name is None: + self.tokenizer.name = self.model.name + if self.tokenizer.trust_remote_code is None: + self.tokenizer.trust_remote_code = self.model.trust_remote_code + return self + + @model_validator(mode="after") + def validate_env_algorithms(self): + """Let each algorithm reject environments it cannot score correctly.""" + for env_cfg in self.train.source: + env_cfg.algo.validate_env(env_cfg.env) + return self + + @model_validator(mode="after") + def validate_loss_aggregation(self): + """The trainer divides the rl loss by the batch's summed rl weights, so token-mean (weight + 1 per token) and prompt-mean (weight 1 per group) envs can't share a batch.""" + algos = [env.algo for env in self.train.source if env.algo.action_loss_type == "rl"] + aggregations = {algo.loss_aggregation if isinstance(algo, GRPOAlgoConfig) else "token" for algo in algos} + if len(aggregations) > 1: + raise ValueError( + "All train envs with an rl loss must use the same loss_aggregation: a prompt-mean group " + "would weigh as much as a single token of a token-mean env." + ) + return self + + @model_validator(mode="after") + def setup_truncated_sampling(self): + """Truncated policy sampling trains with sampling replay (rollout + logprobs are renormalized — see docs/inference.md, Sampling Replay). + Owned here: every truncating config gets a top-k (bounds the replayed supports); opd/opsd + is rejected (full-vocab prefill refs would mix normalizations). Frozen-source envs sample + externally and are exempt.""" + truncating = [sampling for sampling in self.policy_samplings if sampling.truncates_distribution()] + if not truncating: + return self + + if any(sampling.temperature == 0 for sampling in truncating): + raise ValueError( + "Truncated train sampling (top_p/top_k) requires temperature > 0: greedy sampling has " + "no truncated distribution to replay, and the inference server rejects such requests " + "while sampling-mask capture is on." + ) + + algos = [env.algo for env in self.train.source] or [self.train.algo] + if any(algo.type in ("opd", "opsd") for algo in algos): + raise ValueError( + "opd/opsd is not supported with truncated train sampling: reference logprobs are full-vocab " + "prefill scores while trainer logprobs are renormalized over the sampling mask, biasing the " + "ref_kl term. Remove the truncation (top_p/top_k) or the opd/opsd algo." + ) + + if any(sampling.top_k is None for sampling in truncating): + warnings.warn( + f"Truncated train sampling: defaulting top_k = {TRAIN_TOP_K_DEFAULT} so every replayed " + "support is bounded. Set top_k explicitly to override.", + stacklevel=2, + ) + self.update_policy_samplings( + lambda sampling: ( + sampling.model_copy(update={"top_k": TRAIN_TOP_K_DEFAULT}) + if sampling.truncates_distribution() and sampling.top_k is None + else sampling + ) + ) + + return self + + @property + def policy_samplings(self) -> list[TrainSamplingConfig]: + """Sampling of each train source that samples from the policy, else the group's when + there are no sources.""" + if not self.train.source: + return [self.train.sampling] + return [env.sampling for env in self.train.source if env.algo.rollout_model == "policy"] + + def update_policy_samplings(self, update: Callable[[TrainSamplingConfig], TrainSamplingConfig]) -> None: + """Replace each of ``policy_samplings`` with ``update(sampling)``. The group's sampling is + a frozen field, so its config is copied rather than assigned.""" + if not self.train.source: + self.train = self.train.model_copy(update={"sampling": update(self.train.sampling)}) + for env in self.train.source: + if env.algo.rollout_model == "policy": + env.sampling = update(env.sampling) + + @property + def any_policy_sourced(self) -> bool: + """True when at least one train env samples rollouts from the live policy.""" + return any(env.algo.rollout_model == "policy" for env in self.train.source) + + @model_validator(mode="after") + def validate_renderer_auto_resolves(self): + """Reject the silent DefaultRenderer fallback at config time. + + When ``renderer.name='auto'`` and the model isn't in + ``MODEL_RENDERER_MAP``, ``create_renderer`` would fall back to + ``DefaultRenderer``. That fallback doesn't fix the + position-dependent chat-template bug the renderer client exists + to solve, and rejects envs that pass tools (the rollout dies + with "RendererPool does not support tools") unless + ``DefaultRendererConfig.tool_parser`` is configured. Surface at + config time so ``--dry-run`` reports the error. + """ + if self.renderer.name != "auto": + return self + from renderers.base import MODEL_RENDERER_MAP + + model_id = self.tokenizer.name or self.model.name + if model_id in MODEL_RENDERER_MAP: + return self + raise ValueError( + f"orchestrator.renderer.name='auto' but " + f"{model_id!r} is not in renderers.base.MODEL_RENDERER_MAP, so it " + f"would silently fall back to DefaultRenderer. Pick one: " + f"(a) [orchestrator.renderer] name='default' — for fine-tunes / " + f"vendored mirrors with custom chat templates (DefaultRenderer " + f"calls apply_chat_template); set tool_parser= if the env " + f"uses tools. " + f"(b) [orchestrator.renderer] name= — " + f"if {model_id!r} is template-identical to a mapped family " + f"(and ideally also add it upstream to " + f"renderers.base.MODEL_RENDERER_MAP)." + ) + + @model_validator(mode="after") + def resolve_batching(self): + group_sizes = [source.group_size for source in self.train.source] or [self.train.group_size] + if any(self.batch_size % size for size in group_sizes): + raise ValueError( + f"Batch size {self.batch_size} must be divisible by every train source's group_size {sorted(set(group_sizes))}" + ) + + for field in ("max_inflight", "initial_inflight"): + value = getattr(self.concurrency, field) + if value is not None and value < max(group_sizes): + raise ValueError( + f"concurrency.{field} must be at least the largest train group_size ({max(group_sizes)})" + ) + + return self + + @model_validator(mode="after") + def resolve_sampling_replay(self): + """Opt policy train sources into replay and keep eval sampling independent.""" + for env in self.train.source: + # Only truncated policy sampling needs replay. Frozen-sourced rollouts may hit external + # OAI endpoints, and policy engines without prime-rl's extension (Dynamo), that reject the flag. + if env.algo.rollout_model == "policy" and env.sampling.truncates_distribution(): + extra_args = dict(env.sampling.extra_body.get("extra_args") or {}) + extra_args["prl_replay"] = True + env.sampling.extra_body["extra_args"] = extra_args + if self.eval is not None: + for env in self.eval.source: + if getattr(env.sampling, "top_k", None) is None: + env.sampling.top_k = -1 + env.sampling.logprobs = None + return self + + @property + def env_sources(self) -> list[tuple[str, EnvConfig]]: + """Every ``(split, source)`` this run pulls from, train first then eval — the + order used by the launcher to write per-source pool configs.""" + sources: list[tuple[str, EnvConfig]] = [("train", source) for source in self.train.source] + if self.eval is not None: + sources += [("eval", source) for source in self.eval.source] + return sources + + @property + def managed_env_sources(self) -> list[tuple[str, EnvConfig]]: + """``(split, source)`` for every source whose env worker pool the run starts: those + without ``serve.address``. A source with one is externally managed — its pool runs + elsewhere and only the orchestrator connects to it.""" + return [(split, source) for split, source in self.env_sources if source.serve.address is None] + + @property + def env_addresses(self) -> dict[tuple[str, str], str | None]: + """Where each source's env worker pool lives, keyed by ``(split, resolved_name)``: the + source's own ``serve.address`` when set (an externally managed pool), else None — + the launcher starts the pool, whose broker binds an OS-assigned port and publishes it + to the source's address file for the orchestrator to pick up.""" + return {(split, source.resolved_name): source.serve.address for split, source in self.env_sources} + + +class OrchestratorConfig(OrchestratorSection, ComponentConfig): + """Config of the orchestrator process. The ``rl`` launcher fills the fields it adds to ``OrchestratorSection``: + the run-level settings of ``rl`` and the wiring to the other components.""" + + monitors: MonitorsConfig = MonitorsConfig() + """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).""" + + ckpt: OrchestratorCheckpointConfig | None = None + """Checkpoint configuration.""" + + resume: ResumeConfig | None = None + """Resume the orchestrator from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints.""" + + rollout_transport: ZMQTransportConfig = ZMQTransportConfig() + """Transport used to ship rollouts from orchestrator to trainer.""" + + max_steps: int | None = None + """Maximum training steps. If None, runs indefinitely.""" + + weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig() + """Transport used to receive updated weights from the trainer.""" + + output_dir: Path = Field(default_factory=default_output_dir) + """The run directory, shared with the trainer: checkpoints, rollouts, and logs are written as subdirectories. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" + + env_worker_pool_replicas: int | None = Field(None, ge=1) + """Replicas of each launcher-managed env worker pool, each publishing its address to + ``..address``; the orchestrator spreads each source's episodes over them, + least loaded first. None means one pool publishing to ``.address``. Set by the + ``rl`` launcher: multi-node runs start one replica per inference node, so pool + memory spreads over all of them.""" + + @model_validator(mode="after") + def auto_setup_prime_monitor_name(self): + """Default ``monitors.prime.name`` to the W&B run name when monitoring + is enabled and the user hasn't named the platform run explicitly.""" + if self.monitors.prime is None or self.monitors.prime.name is not None: + return self + if self.monitors.wandb is not None and self.monitors.wandb.name: + self.monitors.prime.name = self.monitors.wandb.name + return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/ckpt.py b/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/ckpt.py new file mode 100644 index 00000000000..01f0f35b66f --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/ckpt.py @@ -0,0 +1,21 @@ +from pydantic import Field + +from prime_rl.configs.blocks.ckpt import BaseCheckpointConfig + + +class OrchestratorCheckpointConfig(BaseCheckpointConfig): + """Checkpointing of the orchestrator.""" + + rollouts: bool = False + """Also checkpoint the pipeline: the finished but unshipped train episodes, and the + running train rollouts, each as a memory checkpoint of its sandbox. A resumed run + continues them, so it starts with the batches the checkpointed run would have + shipped. A rollout that cannot take a memory checkpoint starts over. The checkpoint + of step N is then written when the trainer publishes the weights of N, not when N + ships. Eval rollouts are never checkpointed.""" + + rollouts_save_timeout: int = Field(120, ge=1) + """Seconds each running train rollout gets to take its memory checkpoint. A rollout + that takes longer has no restore point and starts over on resume. The trainer + waits in its weight broadcast for the whole save. The save takes at most this + long, plus the time the env worker pools take to write the restore files.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/curriculum.py b/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/curriculum.py new file mode 100644 index 00000000000..2657841ba0d --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/curriculum.py @@ -0,0 +1,96 @@ +from typing import Annotated, Literal, TypeAlias + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig + + +class StandardSamplerConfig(BaseConfig): + """Task sampler that cycles through the taskset in source order. A finite taskset yields a least-sampled task next.""" + + type: Literal["standard"] = "standard" + + +class DifficultyPoolConfig(BaseConfig): + """One pool of the difficulty-pool sampler.""" + + threshold: float + """Inclusive maximum reward assigned to this pool.""" + + weight: float = Field(ge=0) + """Relative per-task sampling weight.""" + + +def default_difficulty_pools() -> dict[str, DifficultyPoolConfig]: + return { + "hard": DifficultyPoolConfig(threshold=0.25, weight=0.2), + "normal": DifficultyPoolConfig(threshold=0.75, weight=1.0), + "easy": DifficultyPoolConfig(threshold=1.0, weight=0.2), + } + + +class DifficultyPoolSamplerConfig(BaseConfig): + """Task sampler that puts each scored task in a pool by its latest group mean reward, and samples + tasks by the weight of their pool. The pool with the highest threshold also takes higher rewards. + Requires a finite taskset.""" + + type: Literal["difficulty_pool"] = "difficulty_pool" + + pools: dict[str, DifficultyPoolConfig] = Field(default_factory=default_difficulty_pools) + """Named pools ordered by their reward thresholds.""" + + unseen_weight: float = Field(1.0, ge=0) + """Relative per-task sampling weight of tasks without a score yet.""" + + seed: int = 42 + """Seed of the sampler's random number generator.""" + + @model_validator(mode="after") + def validate_pools(self): + if not self.pools: + raise ValueError("DifficultyPoolSampler requires at least one pool") + thresholds = [pool.threshold for pool in self.pools.values()] + if len(set(thresholds)) != len(thresholds): + raise ValueError("Difficulty pool thresholds must be unique") + if not any(pool.weight > 0 for pool in self.pools.values()): + raise ValueError("At least one difficulty pool must have a positive weight") + return self + + +TaskSamplerConfig: TypeAlias = Annotated[ + StandardSamplerConfig | DifficultyPoolSamplerConfig, + Field(discriminator="type"), +] + + +class AdvRangeGateConfig(BaseConfig): + """Admission gate that rejects a group when all its advantages fall inside + ``[reject_min, reject_max]``. The ``[0, 0]`` range rejects groups with no learning signal. + A group without advantages passes.""" + + type: Literal["advantage_range"] = "advantage_range" + + reject_min: float = 0.0 + """Inclusive lower bound of the rejected advantage range.""" + reject_max: float = 0.0 + """Inclusive upper bound of the rejected advantage range.""" + + @model_validator(mode="after") + def validate_range(self): + if self.reject_min > self.reject_max: + raise ValueError("reject_min must be less than or equal to reject_max") + return self + + +AdmissionGateConfig: TypeAlias = AdvRangeGateConfig + + +class CurriculumConfig(BaseConfig): + """Task sampler and admission gates of a training source.""" + + sampler: TaskSamplerConfig = Field(default_factory=StandardSamplerConfig) + """Task selection policy. The default cycles through the task iterator in source order.""" + + gates: dict[str, AdmissionGateConfig] = Field(default_factory=dict) + """Named admission policies. Every gate observes every finalized group, + and a group trains only when every gate admits it.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/sampling.py b/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/sampling.py new file mode 100644 index 00000000000..5bca7128f19 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/sampling.py @@ -0,0 +1,58 @@ +from typing import Annotated, Any + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig +from prime_rl.utils.diff import Live + + +class TrainSamplingConfig(BaseConfig): + """Sampling parameters of train rollouts.""" + + temperature: Annotated[float, Live()] = Field(1.0, ge=0, le=2.0) + """Sampling temperature.""" + + top_p: float = Field(1.0, gt=0, le=1.0) + """Nucleus (top-p) sampling for train rollouts. Values below 1.0 truncate the sampling + distribution; the ``rl`` entrypoint auto-enables sampling replay so trainer and + rollout distributions stay consistent — see docs/inference.md (Sampling Replay).""" + + top_k: int | None = Field(None, ge=1) + """Top-k sampling for train rollouts. Truncation triggers sampling replay, and a default top-k + is set when only top-p truncates so every replayed support is bounded — see docs/inference.md + (Sampling Replay).""" + + max_completion_tokens: Annotated[int | None, Live()] = None + """Maximum output tokens per turn. If None, generates until max context length or EOS.""" + + logprobs: int | None = Field(None, ge=1) + """Record this many top sampler probabilities per token, in addition to its sampled logprob.""" + + # Strictly speaking, extra_body is not a sampling parameter, but it is the + # easiest way to pass arbitrary extra parameters to the server via verifiers + extra_body: Annotated[dict[str, Any], Live()] = {} + """Extra body forwarded with each request to the inference server.""" + + def truncates_distribution(self) -> bool: + return self.top_p < 1.0 or self.top_k is not None + + @model_validator(mode="after") + def validate_no_extra_body_truncation(self): + """Truncating values must come from the typed fields — the replay policy reads + them. Disabled values (``top_k = -1`` / ``min_p = 0.0``) pass, so configs + saved with these sentinels re-validate cleanly.""" + smuggled = [ + key + for key, truncates in ( + ("top_p", self.extra_body.get("top_p", 1.0) < 1.0), + ("top_k", self.extra_body.get("top_k") not in (None, -1, 0)), + ("min_p", self.extra_body.get("min_p", 0.0) > 0.0), + ) + if truncates + ] + if smuggled: + raise ValueError( + f"extra_body carries truncating {smuggled}; set them as fields on the train " + "sampling config instead (they drive sampling replay)." + ) + return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/sources.py b/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/sources.py new file mode 100644 index 00000000000..8f23a1593e7 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/orchestrator/sources.py @@ -0,0 +1,296 @@ +from typing import Annotated, Any, get_args + +import verifiers.v1 as vf +from pydantic import AliasChoices, BaseModel, Field, SerializeAsAny, TypeAdapter, ValidationError, model_validator +from pydantic.fields import FieldInfo +from verifiers.v1.configs.agent import agent_config_fields + +from prime_rl.configs.base import BaseConfig +from prime_rl.configs.blocks.algorithm import AlgoConfig, GRPOAlgoConfig +from prime_rl.configs.components.env_worker_pool import ServeConfig +from prime_rl.configs.components.orchestrator.curriculum import CurriculumConfig +from prime_rl.configs.components.orchestrator.sampling import TrainSamplingConfig +from prime_rl.utils.diff import Frozen, Live + + +class EnvConfig(BaseConfig): + """One environment a run pulls from: the verifiers blocks it composes (``env`` — what + runs, ``serve`` — how it's hosted) plus this orchestrator's own per-env knobs.""" + + env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig() + """The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id.""" + + serve: ServeConfig = ServeConfig() + """How this source's env worker pool is hosted. Each replica has a broker endpoint + and workers running the source's env configuration. An unset ``address`` lets the + launcher start the pool and discover its bound address. Setting ``address`` selects + one externally managed pool; the launcher neither writes its config nor starts it.""" + + name: str | None = None + """Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group.""" + + select: vf.SelectConfig = vf.SelectConfig() + """Which of the taskset's tasks this source uses: ``include``/``exclude`` by ``idx``, ``ids``, ``keys`` or ``names``, then ``shuffle``, ``skip`` and ``limit``, applied in that order.""" + + @model_validator(mode="before") + @classmethod + def _resolve_env(cls, data): + """Narrow ``env`` to the selected env's config class.""" + return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls)) + + @property + def env_id(self) -> str: + return self.env.env_id or "" + + @property + def resolved_name(self) -> str: + return self.name or self.env_id + + @model_validator(mode="after") + def validate_env(self): + if not self.env_id: + raise ValueError('no env configured — set env = { taskset = { id = "" } }') + if self.resolved_name == "agg": + raise ValueError( + 'Environment name "agg" is reserved for cross-env metric aggregation. Use a different name or id.' + ) + return self + + +def inherit_defaults(defaults: dict[str, Any], source: dict) -> dict: + """Fill in one raw source with its group's ``defaults`` (field name to validated + group value). A config block such as ``sampling`` is filled in key by key with + ``vf.merge_defaults``; a plain value such as ``group_size`` is used only when the + source leaves it unset. The source's own values always win, and a block that the + source passes as an already-built config is kept as is.""" + merged = dict(source) + for name, value in defaults.items(): + own = source.get(name) + if isinstance(value, BaseModel): + if own is None or isinstance(own, dict): + merged[name] = vf.merge_defaults(value, own) + elif name not in source: + merged[name] = value + return merged + + +def raw_field(data: dict, name: str, field: FieldInfo) -> tuple[bool, Any]: + """Whether raw ``data`` sets field ``name``, under its name or an alias (``-r`` + arrives as ``r``), and the value it sets.""" + alias = field.validation_alias + keys = [name, *(alias.choices if isinstance(alias, AliasChoices) else [alias] if alias else [])] + for key in keys: + if isinstance(key, str) and key in data: + return True, data[key] + return False, None + + +class TrainSourceConfig(EnvConfig): + """One training source: an environment plus its sampling, group size, algorithm and curriculum.""" + + sampling: TrainSamplingConfig = TrainSamplingConfig() + """Per-env sampling overrides. Unset fields inherit from the group-level train sampling config.""" + + ratio: Annotated[float, Live()] = Field(1.0, gt=0) + """Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent).""" + + group_size: Annotated[int, Live()] = Field(1, ge=1) + """Rollouts generated per example for GRPO group-relative advantages. Overrides the + train group's ``group_size`` for this env, so envs can use different sizes. A live + change applies to groups drawn after it; open groups keep the size they started with.""" + + algo: AlgoConfig = GRPOAlgoConfig() + """Training algorithm for this env: sampling plus the per-token training signal + (credit assignment and loss routing, fused — its ``type`` names the algorithm). + Setting only some params keeps the group's algorithm; a different ``type`` is + this env's own algorithm. Frozen except its live fields (the GRPO ``length_penalty``).""" + + curriculum: CurriculumConfig | None = None + """User-authored task sampler and admission gates. None cycles + through the taskset and admits every finalized group.""" + + @model_validator(mode="after") + def validate_policy_sampling(self): + if self.algo.rollout_model != "policy": + return self + # The source owns the distribution replayed by the trainer; agents may + # change generation limits and rendering without changing that distribution. + agent_options = {"max_tokens", "reasoning_effort", "chat_template_kwargs", "skip_special_tokens"} + supported = ( + agent_options + | TrainSamplingConfig.model_fields.keys() + | {"min_p", "logprobs", "return_token_ids", "cache_salt"} + ) + sampling = vf.SamplingConfig(**self.sampling.model_dump(exclude_none=True)) + if getattr(sampling, "extra_args", None) == {"prl_replay": self.sampling.truncates_distribution()}: + supported.add("extra_args") + if unsupported := sampling.model_dump(exclude_none=True).keys() - supported: + raise ValueError( + f"Policy source '{self.resolved_name}' has unsupported sampling parameters: {sorted(unsupported)}" + ) + for name, agent in agent_config_fields(self.env).items(): + # An agent with its own client does not sample from the policy. + if agent.sampling is None or agent.client is not None: + continue + if unsupported := agent.sampling.model_dump(exclude_unset=True).keys() - agent_options: + raise ValueError( + f"Agent '{name}' in policy source '{self.resolved_name}' sets sampling {sorted(unsupported)}. " + "Set distribution parameters on the source's sampling config; agent sampling only supports " + f"{sorted(agent_options)}." + ) + return self + + +class EvalSourceConfig(EnvConfig): + """One evaluation source: an environment plus its sampling and group size.""" + + sampling: vf.SamplingConfig = vf.SamplingConfig() + """Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config.""" + + group_size: int = Field(1, ge=1) + """Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8).""" + + +class OnlineEvalSourceConfig(EvalSourceConfig): + """An eval source of a training run: evaluated on a step interval.""" + + interval: Annotated[int, Live()] = Field(100, ge=1) + """Step interval at which to evaluate this env.""" + + +class SourceGroupConfig(BaseConfig): + """A list of sources plus defaults for them. + + Any field that both the group and its source type declare (``env``, ``sampling``, + ``select``, ``group_size``, ...) is a default. Before validation, each source gets + the group's value for every such field that the group sets: + + - a field the source sets itself keeps the source's value; + - a nested block is filled in key by key (``vf.merge_defaults``); + - a block with a different ``type``/``id`` (e.g. another ``algo``) is the source's + alone. + + A field the group leaves unset is not passed on, so each group field must default + to the same value as the source field it feeds.""" + + env: vf.SharedEnvConfig = vf.SharedEnvConfig() + """Env knobs that every source inherits: the fields every env and taskset has, such + as ``retries`` and ``timeout``.""" + + @model_validator(mode="before") + @classmethod + def inherit_group_defaults(cls, data: Any) -> Any: + """Pass the group's set defaults down into each raw source.""" + if not isinstance(data, dict) or not isinstance(data.get("source"), list): + return data + (source_type,) = get_args(cls.model_fields["source"].annotation) + defaults: dict[str, Any] = {} + for name, field in cls.model_fields.items(): + if name == "source" or name not in source_type.model_fields: + continue + is_set, raw = raw_field(data, name, field) + if not is_set: + continue + try: + defaults[name] = TypeAdapter(field.rebuild_annotation()).validate_python(raw) + except ValidationError: + continue # the group field reports its own errors once, not once per source + data["source"] = [ + inherit_defaults(defaults, source) if isinstance(source, dict) else source for source in data["source"] + ] + return data + + +class TrainConfig(SourceGroupConfig): + """Training sources and the defaults they inherit.""" + + source: list[TrainSourceConfig] = Field(default_factory=list) + """Training sources.""" + + sampling: Annotated[TrainSamplingConfig, Frozen()] = TrainSamplingConfig() + """Sampling that every training source inherits.""" + + select: vf.SelectConfig = vf.SelectConfig() + """Task selection that every training source inherits.""" + + group_size: int = Field(1, ge=1) + """Rollouts generated per example that every training source inherits unless it + sets its own. ``batch_size`` must be divisible by every source's group size.""" + + algo: Annotated[AlgoConfig, Frozen()] = GRPOAlgoConfig() + """Training algorithm that every training source inherits.""" + + @model_validator(mode="after") + def validate_unique_env_names(self): + env_names = [env.resolved_name for env in self.source] + duplicates = [n for n in env_names if env_names.count(n) > 1] + if duplicates: + raise ValueError( + f"Duplicate training environment names: {set(duplicates)}. Each env must have a unique name." + ) + return self + + +class EvalSourcesConfig(SourceGroupConfig): + """Eval sources and the defaults they inherit.""" + + source: list[EvalSourceConfig] = Field(default_factory=list) + """Evaluation sources.""" + + sampling: vf.SamplingConfig = Field(default_factory=vf.SamplingConfig) + """Sampling that every eval source inherits; can differ from training sampling.""" + + select: vf.SelectConfig = vf.SelectConfig() + """Task selection that every eval source inherits, e.g. ``limit = 128`` to evaluate + 128 tasks of each taskset.""" + + group_size: int = Field(1, ge=1) + """Rollouts per example that every eval source inherits.""" + + @model_validator(mode="after") + def validate_non_empty_sources(self): + if not self.source: + raise ValueError( + "At least one eval source is required. Add a source block " + "(e.g. [[source]] or [[orchestrator.eval.source]]) or drop the eval block entirely to disable eval." + ) + return self + + @model_validator(mode="after") + def validate_unique_env_names(self): + env_names = [source.resolved_name for source in self.source] + duplicates = [n for n in env_names if env_names.count(n) > 1] + if duplicates: + raise ValueError( + f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name." + ) + return self + + +class ScheduledEvalConfig(EvalSourcesConfig): + """Eval sources evaluated on a step interval next to training.""" + + source: list[OnlineEvalSourceConfig] = Field(default_factory=list) + """Evaluation sources, each with its own step interval.""" + + interval: int = Field(100, ge=1) + """Step interval that every eval source inherits.""" + + skip_first_step: bool = False + """If True, skip the startup eval that otherwise runs before any + train rollouts.""" + + retrigger_on_resume: bool = False + """If True, re-trigger evals at the checkpoint step on resume (e.g. after a + crash that left in-flight evals unfinished). If False, assume a clean + exit where all evals already completed.""" + + @property + def intervals(self) -> dict[str, int]: + """Step interval per eval env, by resolved name.""" + return {source.resolved_name: source.interval for source in self.source} + + +class RLOnlineEvalConfig(ScheduledEvalConfig): + """The ``[orchestrator.eval]`` block: online evals against the orchestrator's + inference pool, on the policy the train rollouts see.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/router.py b/packages/prime-rl-configs/src/prime_rl/configs/components/router.py new file mode 100644 index 00000000000..ad8af57eb57 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/router.py @@ -0,0 +1,120 @@ +from typing import Annotated, Literal, TypeAlias + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig, ComponentConfig + +# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos). +KNOWN_SCORERS = frozenset( + { + "prefix-cache-scorer", + "precise-prefix-cache-scorer", + "queue-scorer", + "kv-cache-utilization-scorer", + "active-request-scorer", + "load-aware-scorer", + "running-requests-size-scorer", + "token-load-scorer", + "latency-scorer", + "session-affinity-scorer", + "lora-affinity-scorer", + } +) + + +class VllmRouterConfig(BaseConfig): + """PrimeIntellect vllm-router.""" + + type: Literal["vllm-router"] = "vllm-router" + + request_timeout_secs: int = Field(14400, ge=1) + """Maximum lifetime of a routed request, including streamed completions.""" + + policy: str = "sticky_least_loaded" + """Routing policy. ``sticky_least_loaded`` is session-affine least-loaded routing; alternatives include ``consistent_hash`` and ``round_robin``.""" + + pd_turn_retries: int = Field(2, ge=0) + """Disaggregated P/D only: how often the router reruns a turn whose prefill or decode request failed with a connection error (``--pd-turn-retries``). A retry runs a fresh prefill and then decode, without the previous turn's decode KV. 0 returns the first error to the client.""" + + +class LlmdRouterConfig(BaseConfig): + """llm-d router backend (EPP + Envoy).""" + + type: Literal["llm-d"] = "llm-d" + + scorers: dict[str, float] = { + "prefix-cache-scorer": 3.0, + "active-request-scorer": 2.0, + } + """EPP scorer name → weight, applied to every routing profile (before the per-profile P/D overrides). Unknown scorer names are rejected.""" + + prefill_scorer_overrides: dict[str, float] = { + "queue-scorer": 2.0, + "kv-cache-utilization-scorer": 2.0, + } + """P/D only: scorer → weight merged onto ``scorers`` for the prefill profile (a per-profile weight overrides the base).""" + + decode_scorer_overrides: dict[str, float] = {} + """P/D only: scorer → weight merged onto ``scorers`` for the decode profile (a per-profile weight overrides the base).""" + + non_cached_tokens: int = 16 + """P/D only: requests with fewer than this many non-cached prompt tokens skip remote prefill and run decode-only.""" + + decode_sidecar_port: int = 8300 + """P/D only: port the decode-side llm-d sidecar listens on.""" + + @property + def prefill_scorers(self) -> dict[str, float]: + """Effective prefill-profile scorers: ``scorers`` merged with ``prefill_scorer_overrides``.""" + return {**self.scorers, **self.prefill_scorer_overrides} + + @property + def decode_scorers(self) -> dict[str, float]: + """Effective decode-profile scorers: ``scorers`` merged with ``decode_scorer_overrides``.""" + return {**self.scorers, **self.decode_scorer_overrides} + + @model_validator(mode="after") + def validate_scorers(self): + unknown = ( + set(self.scorers) | set(self.prefill_scorer_overrides) | set(self.decode_scorer_overrides) + ) - KNOWN_SCORERS + if unknown: + raise ValueError(f"Unknown llm-d scorer(s): {sorted(unknown)}. Known scorers: {sorted(KNOWN_SCORERS)}.") + return self + + +# Discriminated on ``type`` so the launch path can pick the router backend. +RouterBackendConfig: TypeAlias = Annotated[VllmRouterConfig | LlmdRouterConfig, Field(discriminator="type")] + + +class RouterConfig(ComponentConfig): + """Config of the router process: a vllm-router fronting the engines. The llm-d router has no router process; + the SLURM templates start it.""" + + router: VllmRouterConfig = VllmRouterConfig() + """Settings of the vllm-router backend.""" + + host: str = "0.0.0.0" + """Host the router binds.""" + + port: int = Field(8000, ge=1, le=65535) + """Client-facing port.""" + + worker_urls: list[str] = [] + """Engine URLs of a colocated deployment. A multi-node launcher passes them at start (``--worker-urls``).""" + + prefill_urls: list[str] = [] + """Prefill engine URLs of a disaggregated deployment. The launcher passes them at start (``--prefill-urls``).""" + + decode_urls: list[str] = [] + """Decode engine URLs of a disaggregated deployment. The launcher passes them at start (``--decode-urls``).""" + + intra_node_data_parallel_size: int = Field(1, ge=1) + """Data-parallel ranks behind each URL.""" + + pd_bidirectional_ttl_s: int | None = Field(None, ge=1) + """How long the router keeps a session's decode KV blocks for its next prefill. None disables + bidirectional KV transfer.""" + + prometheus_port: int | None = Field(None, ge=1, le=65535) + """Port of the router's Prometheus metrics endpoint (None = the vllm-router default).""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/__init__.py b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/__init__.py new file mode 100644 index 00000000000..474c4441626 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/__init__.py @@ -0,0 +1,100 @@ +from pathlib import Path + +from pydantic import Field, model_validator + +from prime_rl.configs.base import ComponentConfig +from prime_rl.configs.blocks.ckpt import ResumeConfig +from prime_rl.configs.blocks.monitors import MonitorsConfig +from prime_rl.configs.blocks.transport import ZMQTransportConfig +from prime_rl.configs.blocks.weight_broadcast import FileSystemWeightBroadcastConfig, WeightBroadcastConfig +from prime_rl.configs.components.trainer.base import BaseTrainerConfig, TrainerRunConfig +from prime_rl.configs.components.trainer.data import DataLoaderConfig +from prime_rl.configs.components.trainer.loss import IPOLossConfig, LossConfig +from prime_rl.configs.components.trainer.model import rl_micro_batch_multiple +from prime_rl.configs.components.trainer.moe import mega_moe_max_tokens_per_rank +from prime_rl.utils.config import default_output_dir + + +class TrainerSection(BaseTrainerConfig): + """The ``[trainer]`` block of the ``rl`` entrypoint.""" + + # RL keeps the pretrained router. + auto_freeze_moe_router = True + # RL optimizes the reward objective, not a fixed dataset; L2 decay toward zero fights it. + auto_weight_decay = 0.0 + + data: DataLoaderConfig = DataLoaderConfig() + """How the trainer loads the micro batches of each step.""" + + loss: LossConfig = IPOLossConfig() + """Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this.""" + + annotations: bool = True + """Write the trainer's recomputed per-token logprobs and entropies as trace annotations, + so a trace can show trainer against sampler token by token. Needs ``monitors.file``. + Each step gathers every trained token to the master rank before the optimizer step; + disable with ``--no-annotations`` to skip that work.""" + + warmup: bool = True + """Before waiting for the first batch, run the training step's forward and backward on synthetic micro batches + that train nothing, so compilation, kernel JIT and communicator setup happen while the trainer would idle. The + warmup leaves the weights and the optimizer state unchanged.""" + + enable_router_replay: bool = False + """Return routed experts in the batch so the trainer can replay routing. Requires ``enable_return_routed_experts=true`` on the vLLM server (or ``--enable-return-routed-experts``) and is only supported for custom models.""" + + @model_validator(mode="after") + def resolve_mega_moe_max_tokens_per_rank(self): + """RL micro batches are one packed sequence of up to ``model.seq_len`` tokens, padded to + ``rl_micro_batch_multiple`` and split over the CP ranks.""" + dispatch = self.model.moe.dispatch + if dispatch.type == "mega_moe": + multiple = rl_micro_batch_multiple(self.model) + micro_batch_tokens = -(-self.model.seq_len // multiple) * multiple + dispatch.max_tokens_per_rank = mega_moe_max_tokens_per_rank( + dispatch.max_tokens_per_rank, micro_batch_tokens, self.model.cp + ) + return self + + +class TrainerConfig(TrainerSection, TrainerRunConfig, ComponentConfig): + """Config of the RL trainer process. The ``rl`` launcher fills the fields it adds to ``TrainerSection``: the + run-level settings of ``rl`` and the wiring to the other components.""" + + resume: ResumeConfig | None = None + """Resume training from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints. The checkpoint supplies the training state; the hyperparameters and the learning rate schedule come from this config.""" + + rollout_transport: ZMQTransportConfig = ZMQTransportConfig() + """Transport used to ship rollouts from orchestrator to trainer.""" + + monitors: MonitorsConfig = MonitorsConfig() + """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).""" + + weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig() + """Transport used to broadcast updated weights from trainer to inference.""" + + output_dir: Path = Field(default_factory=default_output_dir) + """The run directory: checkpoints, weights, rollouts, and logs are written as subdirectories. The ``rl`` entrypoint sets it to its ``output_dir / run.name``. Standalone, it defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" + + @model_validator(mode="after") + def validate_lora_broadcast(self): + if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "modelexpress"): + raise ValueError( + "LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a " + "PEFT-shaped directory on disk - in-memory transports have no disk artifact to load from." + ) + return self + + @model_validator(mode="after") + def validate_retain(self): + if not self.rollout_transport.retain: + return self + if not (self.ckpt and self.ckpt.interval): + raise ValueError("rollout_transport.retain needs ckpt.interval: only a checkpoint releases a retained step") + if self.weight_broadcast.type != "filesystem": + raise ValueError( + f"rollout_transport.retain is not yet supported with weight_broadcast.type = " + f"'{self.weight_broadcast.type}': a restarted trainer cannot rejoin its transfer group. " + "Use weight_broadcast.type = 'filesystem'." + ) + return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/base.py b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/base.py new file mode 100644 index 00000000000..b7cac6fac7e --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/base.py @@ -0,0 +1,257 @@ +import uuid +import warnings +from pathlib import Path +from typing import ClassVar, Literal + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig +from prime_rl.configs.blocks.ckpt import ResumeConfig +from prime_rl.configs.blocks.log import SupervisedLogConfig, TrainerLogConfig +from prime_rl.configs.blocks.model import TokenizerConfig +from prime_rl.configs.blocks.monitors import MonitorsConfig +from prime_rl.configs.blocks.run import ControlConfig, EnvVars, GCConfig, HeartbeatConfig, RunConfig +from prime_rl.configs.blocks.weight_broadcast import WeightBroadcastSection +from prime_rl.configs.components.online_eval import SFTOnlineEvalSection +from prime_rl.configs.components.trainer.ckpt import TrainerCheckpointConfig +from prime_rl.configs.components.trainer.data import BaseDataConfig, BaseValConfig, ValConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig +from prime_rl.configs.components.trainer.moe import mega_moe_max_tokens_per_rank +from prime_rl.configs.components.trainer.optim import ( + AdamWConfig, + ConstantSchedulerConfig, + OptimizerConfig, + SchedulerConfig, + validate_scheduler, +) +from prime_rl.utils.config import default_output_dir + + +class BaseTrainerConfig(BaseConfig): + """Fields and validators shared by the RL trainer (``TrainerConfig``) and the SFT and pretraining trainer + (``SupervisedTrainerConfig``).""" + + auto_freeze_moe_router: ClassVar[bool] + auto_weight_decay: ClassVar[float] + + model: TrainerModelConfig = TrainerModelConfig() + """The model to train, its parallelism, precision and kernels.""" + + tokenizer: TokenizerConfig = TokenizerConfig() + """Tokenizer. Unset ``name`` and ``trust_remote_code`` take their values from ``model``.""" + + optim: OptimizerConfig = AdamWConfig() + """Optimizer.""" + + scheduler: SchedulerConfig = ConstantSchedulerConfig() + """Learning rate schedule.""" + + log: TrainerLogConfig = TrainerLogConfig() + """Logging.""" + + matmul_precision: Literal["highest", "high", "medium"] = "high" + """Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``.""" + + memory_profiler_path: Path | None = None + """Path to write the memory profile to. If None, does not profile memory.""" + + gc: GCConfig | None = GCConfig() + """Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior.""" + + trace_path: Path | None = None + """Path to write the PyTorch profiler trace to. If None, does not trace.""" + + dist_timeout_seconds: int = 900 + """Timeout in seconds for torch distributed ops: a hung collective (e.g. a dead rank) fails the run after this long.""" + + heartbeat: HeartbeatConfig | None = None + """BetterStack heartbeat configuration for monitoring training progress. If None, sends no heartbeats.""" + + control: ControlConfig | None = None + """Serve the run control API on the master rank (pause or checkpoint the run + after the next step). If None, the run takes no control requests.""" + + env_vars: EnvVars = {} + """Extra environment variables for the trainer process(es). Merged on top of the launcher defaults.""" + + @model_validator(mode="after") + def resolve_auto_defaults(self): + if self.model.freeze_moe_router == "auto": + self.model.freeze_moe_router = self.auto_freeze_moe_router + if self.optim.weight_decay == "auto": + self.optim.weight_decay = self.auto_weight_decay + return self + + @model_validator(mode="after") + def full_optimizer_offload_requires_supported_optimizer(self): + if self.model.offload == "full" and self.optim.type not in ("adamw", "sign_sgd"): + raise ValueError("Full optimizer offload only supports AdamW and SignSGD") + return self + + @model_validator(mode="after") + def full_optimizer_offload_disables_grad_clipping(self): + if self.model.offload == "full" and self.optim.max_norm is not None: + warnings.warn( + "Gradient clipping prevents optimizer-in-backward overlap with CPU optimizer offload. " + "Automatically setting optim.max_norm to None (disabled).", + stacklevel=1, + ) + self.optim.max_norm = None + return self + + @model_validator(mode="after") + def vlm_freeze_incompatible_with_lora(self): + if self.model.vlm is not None and not self.model.vlm.freeze_vision_encoder and self.model.lora is not None: + raise ValueError( + "freeze_vision_encoder=false is incompatible with LoRA. " + "LoRA freezes all non-adapter parameters including the vision encoder." + ) + return self + + @model_validator(mode="after") + def auto_setup_tokenizer(self): + if self.tokenizer.name is None: + self.tokenizer.name = self.model.name + if self.tokenizer.trust_remote_code is None: + self.tokenizer.trust_remote_code = self.model.trust_remote_code + return self + + +class TrainerRunConfig(BaseTrainerConfig): + """A trainer with the run-level settings: checkpointing and the step count. ``rl`` sets these once for the + whole run, so its ``[trainer]`` block leaves them out.""" + + ckpt: TrainerCheckpointConfig | None = None + """Checkpointing. If None, the run saves no checkpoints.""" + + max_steps: int | None = None + """Maximum number of training steps. If None, runs indefinitely.""" + + @model_validator(mode="after") + def dont_do_massive_traces(self): + if self.trace_path: + if self.max_steps is None: + raise ValueError("Must specify max_steps when tracing") + if self.max_steps >= 10: + raise ValueError( + "Tracing more than 10 steps is not recommended as your trace will be massive. Remove this line if you really want to trace more steps." + ) + return self + + @model_validator(mode="after") + def validate_scheduler_steps(self): + validate_scheduler(self.scheduler, self.max_steps) + return self + + +class SupervisedTrainerSection(TrainerRunConfig): + """The trainer fields of SFT and pretraining (next-token loss on a fixed dataset, as opposed to RL), at the top + level of their entrypoints.""" + + auto_freeze_moe_router = False + # Standard L2 regularization for supervised training. + auto_weight_decay = 0.01 + data: BaseDataConfig + """Training data and its batching.""" + + log: SupervisedLogConfig = SupervisedLogConfig() + """Logging.""" + + val: BaseValConfig | ValConfig | None = None + """Validation configuration. If None, no validation runs.""" + + eval: SFTOnlineEvalSection | None = None + """Online evaluation configuration: rollout-based evals against a live inference + server that receives the trainer's weight broadcasts. If None, no online evals run.""" + + weight_broadcast: WeightBroadcastSection | None = None + """Trainer-to-inference weight transport for online evals. Defaults to NCCL; set + ``type = "modelexpress"`` to send weights through ModelExpress. LoRA and external + inference use filesystem broadcast.""" + + resume: ResumeConfig | None = None + """Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. The checkpoint supplies the training state; the hyperparameters and the learning rate schedule come from this config. If None, does not resume.""" + + monitors: MonitorsConfig = MonitorsConfig() + """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).""" + + run: RunConfig = Field(default_factory=RunConfig) + """Run metadata. ``run.name`` names the run directory under ``output_dir``.""" + + output_dir: Path = Field(default_factory=default_output_dir) + """Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" + + @property + def run_dir(self) -> Path: + assert self.run.dir is not None # resolved at construction + return self.output_dir / self.run.dir + + @model_validator(mode="after") + def auto_setup_run_identity(self): + """Auto-generate the run name (``----``, with the source only if it is the only + one) when unset and default the run directory, W&B run name and platform run name to it when not set + explicitly.""" + if self.run.name is None: + sources = getattr(self.data, "source", []) + dataset = "fake" if getattr(self.data, "fake", None) else sources[0].name if len(sources) == 1 else "" + model = self.model.name.split("/")[-1] + parts = [part for part in (dataset, model) if part] + self.run.name = "--".join([*parts, uuid.uuid4().hex[:8]]).lower() + if self.run.dir is None: + self.run.dir = self.run.name + if self.monitors.wandb is not None and self.monitors.wandb.name is None: + self.monitors.wandb.name = self.run.name + if self.monitors.prime is not None and self.monitors.prime.name is None: + self.monitors.prime.name = self.run.name + return self + + @model_validator(mode="after") + def auto_setup_val(self): + if not isinstance(self.val, ValConfig): + return self + for val_set in self.val.set: + if val_set.seq_len is None: + val_set.seq_len = self.data.seq_len + longest = max(val_set.seq_len for val_set in self.val.set) + if self.val.micro_batch_tokens is None: + row_len = max(self.data.seq_len * self.data.micro_batch_size, longest) + self.val.micro_batch_tokens = -(-row_len // self.model.cp) * self.model.cp + elif self.val.micro_batch_tokens < longest: + raise ValueError(f"val.micro_batch_tokens must be at least the longest set seq_len ({longest})") + return self + + @model_validator(mode="after") + def validate_cp_seq_len(self): + if self.model.cp > 1: + if self.data.seq_len % self.model.cp != 0: + raise ValueError("Sequence length must be divisible by CP degree") + if isinstance(self.val, ValConfig) and self.val.micro_batch_tokens % self.model.cp != 0: + raise ValueError("val.micro_batch_tokens must be divisible by CP degree") + if isinstance(self.val, BaseValConfig) and self.val.data.seq_len % self.model.cp != 0: + raise ValueError("Validation sequence length must be divisible by CP degree") + return self + + @model_validator(mode="after") + def resolve_mega_moe_max_tokens_per_rank(self): + dispatch = self.model.moe.dispatch + if dispatch.type == "mega_moe": + row_lens = [self.data.micro_batch_size * self.data.seq_len] + if isinstance(self.val, ValConfig): + row_lens.append(self.val.micro_batch_tokens) + elif self.val is not None: + row_lens.append(self.val.data.micro_batch_size * self.val.data.seq_len) + dispatch.max_tokens_per_rank = mega_moe_max_tokens_per_rank( + dispatch.max_tokens_per_rank, + max(row_lens), + self.model.cp, + ) + return self + + @model_validator(mode="after") + def validate_cp_micro_batch_size(self): + if self.model.cp > 1: + if self.data.micro_batch_size != 1: + raise ValueError("Micro batch size must be 1 when CP is enabled") + if isinstance(self.val, BaseValConfig) and self.val.data.micro_batch_size != 1: + raise ValueError("Validation micro batch size must be 1 when CP is enabled") + return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/ckpt.py b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/ckpt.py new file mode 100644 index 00000000000..092db49bd5c --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/ckpt.py @@ -0,0 +1,38 @@ +from pydantic import Field + +from prime_rl.configs.base import BaseConfig +from prime_rl.configs.blocks.ckpt import BaseCheckpointConfig + + +class RemoteCheckpointConfig(BaseConfig): + """Object store that the trainer mirrors its checkpoints to.""" + + dir: str + """Object store URL checkpoints are mirrored to, e.g. ``s3://bucket/run/checkpoints`` (credentials and endpoint from the ``AWS_*`` environment).""" + + keep_last: int | None = Field(None, ge=1) + """Keep at most this many recent step checkpoints in the remote. If None, never clean old remote checkpoints based on recency.""" + + keep_interval: int | None = Field(None, ge=1) + """Keep remote checkpoints at every N steps permanently. If None, no interval-based keeping.""" + + +class TrainerCheckpointConfig(BaseCheckpointConfig): + """Trainer checkpoints: the model, optimizer, scheduler and dataloader state of a step.""" + + remote: RemoteCheckpointConfig | None = None + """Mirror checkpoints to an object store. A sync process per node uploads each step once it is on disk, with ``.metadata`` last; ``keep_last``/``keep_interval`` apply to the disk and ``remote.keep_last``/``remote.keep_interval`` to the remote. Resume pulls a step that is not complete on disk while the trainer starts up.""" + + skip_dataloader: bool = False + """Skip loading the dataloader from checkpoint.""" + + skip_optimizer: bool = False + """Start the optimizer state fresh: new moments and Muon step counts. Loads none of the checkpoint's param + groups, so it has no hyperparameters to compare and logs no mismatch warning.""" + + async_save: bool = False + """Write checkpoints in the background. A save copies this rank's model and optimizer state into pinned host + buffers and returns; a background thread writes the copy while training continues. The buffers are kept for + the next save, so this costs pinned host memory about the size of the rank's checkpoint shard. Without + optimizer offload the copy also overlaps the next step, until its optimizer step. A save first waits for the + previous write to finish.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/data.py b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/data.py new file mode 100644 index 00000000000..655bc4fd1aa --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/data.py @@ -0,0 +1,309 @@ +from pathlib import Path +from typing import Any, Literal + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig + + +class FakeDataLoaderConfig(BaseConfig): + """Fake data loader that samples random micro batches, for debugging.""" + + batch_size: int = Field(2, ge=1) + """Batch size of the fake data loader.""" + + generate_samples: bool = False + """Generate separate samples and pack them into a single micro-batch instead of using random tensors.""" + + doc_len: int | None = Field(None, ge=1) + """Length of each generated sample, the last one cut to fill the micro batch. If None, lengths are random up to a micro batch's length / 8. Requires generate_samples.""" + + @model_validator(mode="after") + def doc_len_requires_generate_samples(self): + if self.doc_len is not None and not self.generate_samples: + raise ValueError("data.fake.doc_len requires data.fake.generate_samples") + return self + + +class DataLoaderConfig(BaseConfig): + """How the RL trainer loads the micro batches of each step.""" + + fake: FakeDataLoaderConfig | None = None + """Use a fake data loader sampling random micro-batches (for debugging).""" + + num_workers: int = Field(1, ge=0) + """Number of background threads that prepare micro batches ahead of the training loop, analogous to torch DataLoader's ``num_workers`` but with threads instead of processes. 0 prepares them on the main thread.""" + + pad_to_seq_len: bool = False + """Pad every micro batch to ``model.seq_len`` instead of to a multiple of the context-parallel degree. Rows then have one static shape, which avoids recompilation on dynamic sequence lengths (torch.compile, DeepGEMM JIT kernels, ...) at the cost of extra padding.""" + + +class BaseDataConfig(BaseConfig): + """Batching and loading of the supervised training data.""" + + batch_size: int = Field(128, ge=1) + """Global batch size.""" + + seq_len: int = Field(128, ge=1) + """Sequence length.""" + + micro_batch_size: int = Field(1, ge=1) + """Per-step micro batch size. ``batch_size`` must be divisible by this.""" + + num_workers: int = Field(1, ge=1) + """Number of dataloader worker processes. Batches are prepared and pinned in the background so tokenization/packing overlaps with training.""" + + pad_to_seq_len: bool = False + """Pad every packed row to ``seq_len * micro_batch_size`` instead of to a multiple of ``model.cp``. Rows then have + one static shape, which avoids recompilation on dynamic sequence lengths (torch.compile, DeepGEMM JIT kernels, ...) + at the cost of extra padding.""" + + @model_validator(mode="after") + def validate_batch_size(self): + if self.batch_size % self.micro_batch_size != 0: + raise ValueError("Batch size must be divisible by micro batch size") + if self.batch_size < self.micro_batch_size: + raise ValueError("Batch size must be greater than or equal to micro batch size") + return self + + +class BaseSourceConfig(BaseConfig): + """One named source of the training data (``[[data.source]]``), in pretraining and SFT.""" + + name: str = Field(pattern=r"^[^/]+$") + """Names the source in the ``progress//*`` metrics.""" + + weight: float | None = Field(None, ge=0) + """The source's relative weight: its share of the training data (tokens in pretraining, samples in SFT) is its + weight over the sum of all weights. If None on every source, the share is the source's share of all sources' data + (tokens in pretraining, rows in SFT).""" + + +def check_sources(sources: list[BaseSourceConfig]) -> None: + """Raise if two sources share a name, or the weights are set on only some sources or sum to 0.""" + names = [source.name for source in sources] + if len(set(names)) < len(names): + raise ValueError(f"data.source: the names must be unique, got {names}") + weights = [source.weight for source in sources] + if None in weights and any(weight is not None for weight in weights): + raise ValueError("data.source: set weight on every source or on none (natural shares)") + if None not in weights and sum(weights) <= 0: + raise ValueError("data.source: the weights must sum to more than 0") + + +class BaseValConfig(BaseConfig): + """Validation on held-out data, run every ``interval`` training steps.""" + + interval: int = Field(50, ge=1) + """Run validation every N training steps.""" + + eval_on_start: bool = False + """Run validation before the first training step.""" + + data: BaseDataConfig + """The held-out data to validate on.""" + + +class DocumentsValSetConfig(BaseConfig): + """Pre-tokenized documents. Every document is scored on its own, from its first token, in non-overlapping windows + of ``seq_len`` scored tokens: a longer document continues in the next window, which does not see the tokens + before it.""" + + type: Literal["documents"] = "documents" + + name: str = Field(pattern=r"^[^/]+$") + """Names the set's metrics, ``val//@``, e.g. ``val/fineweb-edu/bpb@2k``.""" + + path: Path + """Folder of datatrove tokenized shards, as for a pretraining source's ``path``. The tokens are scored as stored.""" + + seq_len: int | None = Field(None, ge=1) + """Context length: the most input tokens a scored sequence has. Defaults to the training ``data.seq_len``.""" + + +class ValConfig(BaseConfig): + """Validation on held-out document sets, run every ``interval`` training steps.""" + + interval: int = Field(50, ge=1) + """Run validation every N training steps.""" + + eval_on_start: bool = False + """Run validation before the first training step.""" + + set: list[DocumentsValSetConfig] = Field(min_length=1) + """The validation sets (``[[val.set]]``). Each logs ``val//loss@``, the mean loss per scored + token, and with a byte-level BPE tokenizer ``val//bpb@``, bits per UTF-8 byte of the scored + tokens.""" + + num_samples: int | None = Field(None, ge=1) + """Items per set and validation: the first ``num_samples`` documents of each set, the same ones every time. If + None, every item.""" + + micro_batch_tokens: int | None = Field(None, ge=1) + """Tokens per packed row of the sets (one forward pass). Defaults to the training micro-batch + (``data.seq_len * data.micro_batch_size``) or the longest set ``seq_len``, whichever is larger, rounded up to a + multiple of ``model.cp``; must be at least that longest ``seq_len``.""" + + save_arrays: bool = False + """Write the per-item arrays (npz) and summary (json) of every set to ``/val/step_N/``.""" + + @model_validator(mode="after") + def validate_unique_names(self): + names = [val_set.name for val_set in self.set] + if len(set(names)) < len(names): + raise ValueError(f"val.set names must be unique: {names}") + return self + + +class LossMaskConfig(BaseConfig): + """Message types that contribute to the loss.""" + + system: bool = False + """System messages contribute to the loss.""" + + user: bool = False + """User messages contribute to the loss.""" + + assistant: bool = True + """Assistant messages contribute to the loss.""" + + tool: bool = False + """Tool messages contribute to the loss.""" + + +class SFTColumnsConfig(BaseConfig): + """Dataset columns the trainer reads. Set a field to read a column under another name.""" + + messages: str = "messages" + """Column with the whole chat as a list of OpenAI chat messages.""" + + prompt: str = "prompt" + """Column with the prompt as a list of OpenAI chat messages, read with ``completion`` when a row has no messages.""" + + completion: str = "completion" + """Column with the completion as a list of OpenAI chat messages.""" + + tools: str = "tools" + """Column with the tool schemas in OpenAI function-calling format.""" + + message_loss_mask: str = "message_loss_mask" + """Optional column of booleans or integer 0/1 flags, one per resolved message (prompt + completion for split rows). Zero excludes a message from loss; one preserves its normal supervision. Missing or null masks leave supervision unchanged.""" + + renderer: dict[str, str] = {"reasoning_effort": "reasoning_effort"} + """Per-sample renderer arguments as ``renderer field = dataset column``, e.g. ``reasoning_effort = "effort"``. A row's non-null value overrides the ``[renderer]`` setting; rows and datasets without the column use it unchanged.""" + + +class HFDatasetSourceConfig(BaseSourceConfig): + """One ``(dataset, subset, split)`` of a Hugging Face dataset.""" + + dataset: str + """HF dataset name or local path.""" + + revision: str | None = None + """HF dataset revision to load. Ignored for a local path.""" + + subset: str | None = None + """Subset (config name) of the dataset.""" + + split: str = "train" + """Split of the dataset.""" + + columns: SFTColumnsConfig | None = None + """Columns of this source. Unset fields keep ``data.columns``.""" + + renderer: dict[str, Any] = {} + """Chat-template kwargs for this source's rows, applied over ``[renderer]`` and under a row's ``columns.renderer`` + values, e.g. ``{ reasoning_effort = "high" }``.""" + + +class FakeDataConfig(BaseConfig): + """Synthetic token sequences of up to ``data.seq_len`` tokens, for throughput and plumbing tests.""" + + length: Literal["fixed", "variable"] = "fixed" + """Use fixed-length samples or variable-length samples.""" + + input_ids: Literal["increasing", "random"] = "increasing" + """Token id generator: ``increasing`` for deterministic sequences, ``random`` for random ids.""" + + +class SFTDataConfig(BaseDataConfig): + """Samples drawn from one or more sources into packed rows of ``seq_len`` tokens.""" + + source: list[HFDatasetSourceConfig] = Field( + default_factory=lambda: [HFDatasetSourceConfig(name="reverse-text", dataset="PrimeIntellect/Reverse-Text-SFT")], + min_length=1, + ) + """The sources to draw samples from (``[[data.source]]``).""" + + fake: FakeDataConfig | None = None + """Train on synthetic token sequences instead of the sources. Needs no renderer.""" + + shuffle: bool = True + """Shuffle every source at the start of each of its passes.""" + + seed: int = 0 + """Seed for the order of every source, re-shuffled per pass by adding the pass count, and for fake tokens.""" + + columns: SFTColumnsConfig = SFTColumnsConfig() + """Columns of every source. A source's ``columns`` override single fields.""" + + loss_mask: LossMaskConfig = LossMaskConfig() + """Which message types contribute to the loss.""" + + @model_validator(mode="after") + def validate_sources(self): + check_sources(self.source) + for source in self.source: + overrides = source.columns.model_dump(exclude_unset=True) if source.columns is not None else {} + source.columns = SFTColumnsConfig.model_validate({**self.columns.model_dump(), **overrides}) + return self + + +class SFTValConfig(BaseValConfig): + """SFT validation: the loss on the rows of held-out sources.""" + + data: SFTDataConfig + """The held-out sources to validate on. Fake data is not allowed.""" + + @model_validator(mode="after") + def validate_sources(self): + if self.data.fake is not None: + raise ValueError("val.data.fake: validation scores the rows of its sources, not fake data") + return self + + +class TokenSourceConfig(BaseSourceConfig): + """A folder of datatrove tokenized shards, one source of the training data.""" + + path: Path + """Folder of ``*.ds`` token files, each with its ``.ds.index`` and ``.ds.metadata``.""" + + repetitions: float | None = Field(None, ge=1) + """How often every token of a fixed subset of the source is seen over the run (needs ``max_steps``). If None, the + whole source is read.""" + + +class PretrainDataConfig(BaseDataConfig): + """Training shards: documents sampled from one or more sources into rows of ``seq_len`` tokens.""" + + type: Literal["datatrove"] = "datatrove" + + source: list[TokenSourceConfig] = Field(min_length=1) + """The folders to sample documents from (``[[data.source]]``).""" + + seed: int = Field(0, ge=0) + """Seed for the order of the documents, within rows too, and for the subsets.""" + + document_masking: bool = True + """Attention and positions restart at every document and piece. If False, a row is one sequence.""" + + eod_mask_loss: bool = True + """Don't train the model to predict the first token of the next, unrelated document: no loss where the input is + the document separator. The separator is the special token the training shards' documents end with, detected at + startup; startup fails if they don't all end with one, unless they start with BOS (then there is nothing to + mask).""" + + @model_validator(mode="after") + def validate_sources(self): + check_sources(self.source) + return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/loss.py b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/loss.py new file mode 100644 index 00000000000..c03dba293de --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/loss.py @@ -0,0 +1,68 @@ +from typing import Annotated, Any, Literal, TypeAlias + +from pydantic import Field, model_validator + +from prime_rl.configs.base import BaseConfig + + +class IPOLossConfig(BaseConfig): + """IPO loss: policy gradient with a capped importance ratio. A symmetric trust region masks tokens whose + probability moved more than ``eps``.""" + + type: Literal["ipo"] = "ipo" + eps: float = Field(0.3, ge=0) + """Maximum absolute probability change before a token is masked.""" + + max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False) + """Cap the importance weight of accepted tokens while preserving its policy gradient.""" + + adv_tau: float = Field(1.0, ge=0) + """Temperature for the advantage term.""" + + +class IcePopLossConfig(BaseConfig): + """IcePop loss: policy gradient that masks tokens whose trainer-to-inference probability ratio is outside + ``[ratio_low, ratio_high]``.""" + + type: Literal["icepop"] = "icepop" + + ratio_low: float = Field(0.2, gt=0) + """Lower accepted trainer-to-inference probability ratio.""" + + ratio_high: float = Field(5.0, gt=0) + """Upper accepted trainer-to-inference probability ratio.""" + + adv_tau: float = Field(1.0, ge=0) + """Temperature for the advantage term.""" + + score_centering: bool = False + """Center the ratio-masked importance-weighted score under the sampler.""" + + score_centering_topk: int = Field(128, ge=1) + """Captured head size for an untruncated sampler with a proportional tail. + Probabilities retain full-vocabulary normalization. With sampling replay, the + complete recorded support is captured instead.""" + + @model_validator(mode="after") + def validate_ratio_bounds(self): + if self.ratio_low > self.ratio_high: + raise ValueError("ratio_low must not exceed ratio_high") + return self + + +class CustomLossConfig(BaseConfig): + """Custom loss: the function at ``import_path``, called as ``fn(inputs, **kwargs)``.""" + + type: Literal["custom"] = "custom" + + import_path: str + """Import path to the loss function (e.g. ``my_module.my_loss``).""" + + kwargs: dict[str, Any] = Field(default_factory=dict) + """Kwargs forwarded to the loss function.""" + + +LossConfig: TypeAlias = Annotated[ + IPOLossConfig | IcePopLossConfig | CustomLossConfig, + Field(discriminator="type"), +] diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/model.py b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/model.py new file mode 100644 index 00000000000..a8dd3945db4 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/model.py @@ -0,0 +1,312 @@ +from pathlib import Path +from typing import Annotated, Literal, TypeAlias + +from pydantic import Field, field_validator, model_validator + +from prime_rl.configs.base import BaseConfig +from prime_rl.configs.blocks.model import BaseModelConfig, VLMConfig +from prime_rl.configs.components.trainer.moe import ( + MoERuntimeConfig, + MXFP8MoEComputeConfig, + MXFP8Recipe, + TorchMoEDispatchConfig, +) + +AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"] + +DSABackend: TypeAlias = Literal["tilelang", "cudnn_flashmla"] + +MODULE_TARGET_SEPARATOR = "@" + + +class ActivationCheckpointConfig(BaseConfig): + """Activation checkpointing: recompute activations in the backward pass instead of keeping them in memory.""" + + mode: Literal["full", "selective"] = "full" + """Both modes checkpoint whole transformer blocks. ``selective`` additionally retains selected operations.""" + + freq: int = Field(1, ge=1) + """Apply activation checkpointing to every N layers.""" + + targets: list[str] | None = None + """Operator names or namespaces retained in selective mode. ``None`` uses the default targets; an explicit list replaces them. Append ``@`` to retain an operator only inside matching modules, for example ``"prime_rl::fp8_blockwise_mm@self_attn.o_b_proj"``. The pattern is an ``fnmatch`` glob over module paths relative to the checkpointed block, and it also covers the matching modules' descendants. Module-qualified targets require ``model.compile``, and the trainer raises after the first training forward if one matched no traced operation.""" + + @field_validator("targets") + @classmethod + def validate_targets(cls, targets: list[str] | None) -> list[str] | None: + for target in targets or []: + operation, separator, module_pattern = target.partition(MODULE_TARGET_SEPARATOR) + if not operation or (separator and (not module_pattern or MODULE_TARGET_SEPARATOR in module_pattern)): + raise ValueError( + f"Invalid activation checkpointing target {target!r}: expected an operator or namespace, " + "optionally followed by '@'." + ) + return targets + + token_chunk_size: int | None = Field(None, ge=3) + """Experimental. Checkpoint token-local blocks in chunks of this many tokens per rank, so their recompute and backward hold one chunk's activations at a time. Only supported for Nemotron-H, whose MoE layers are the only blocks it chunks; it has no effect on other models. Requires ``ep == 1`` or ``ep == cp``. ``None`` checkpoints every block whole.""" + + +class ActivationOffloadingConfig(BaseConfig): + """Offload tensors saved for backward to pinned CPU memory during the forward pass.""" + + max_inflight_activations: int = Field(5, ge=1) + """Max activations kept on GPU while their offload copies are in flight on the side stream. Higher values give more copy/compute overlap at the cost of GPU memory.""" + + +OffloadMode: TypeAlias = Literal["none", "optimizer", "full"] + + +class CompileConfig(BaseConfig): + """``torch.compile`` of the transformer blocks.""" + + fullgraph: bool = False + """Compile transformer blocks with ``fullgraph=True``.""" + + mode: Literal["reduce-overhead", "max-autotune", "max-autotune-no-cudagraphs", "lite"] | None = None + """``torch.compile`` mode. ``reduce-overhead`` records CUDA graphs to cut kernel launch overhead; ``max-autotune`` modes trade longer compile times for tuned kernels (``max-autotune`` also records CUDA graphs, ``max-autotune-no-cudagraphs`` does not). CUDA-graphed layers re-record on new input shapes. ``None`` uses PyTorch's default mode.""" + + +class FusionsConfig(BaseConfig): + """Runtime parameter fusions.""" + + enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"] + """Runtime parameter fusions. ``gate_up`` runs each MoE expert's gate and up projections as one grouped GEMM; ``qkv`` runs attention's q, k and v projections as one GEMM. Only modules that support a fusion are packed, checkpoints keep the canonical parameter names and shapes, and fusions are skipped when LoRA is enabled. Set to ``[]`` to disable.""" + + shard_fused_on_dim1: bool = False + """Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size.""" + + +class LoRAConfig(BaseConfig): + """LoRA adapters. The trainer freezes all non-adapter parameters.""" + + rank: int = Field(16, ge=1) + """Rank of the low-rank decomposition matrices.""" + + alpha: float = Field(32.0, ge=0) + """LoRA scaling parameter.""" + + dropout: float = Field(0.0, ge=0, le=1) + """LoRA dropout rate.""" + + target_modules: list[str] = [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "up_proj", + "down_proj", + "experts", + "fc1_latent_proj", + "fc2_latent_proj", + ] + """Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches the ReLU² grouped experts; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba.""" + + +class DebugModelConfig(BaseConfig): + """Debugging knobs for the model and distributed training.""" + + num_layers: int | None = None + """Override the number of transformer layers (truncates the model). If None, loads all layers.""" + + force_balanced_routing: bool = False + """Replace MoE token-choice routing with a round-robin assignment so every expert sees an equal share. Intended for fake-data smoke tests where untrained routing would otherwise OOM under severe imbalance. Gating scores are still gathered from the override indices so the forward pass stays consistent.""" + + +_DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [ + "lm_head", + "router", + # Use escaped dots — re.search treats `.` as any-char, so the previous + # "mlp.gate." pattern was also matching dense MLP `mlp.gate_proj` (the + # trailing `.` was matching `_`). That left the dense MLP gate projection + # in BF16 on the trainer while inference quantized it to FP8, causing + # hidden-state drift before the MoE router. + r"mlp\.gate\.", + r"shared_expert\.output_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False) + "eh_proj", + "weights_proj", + "in_proj_a", + "in_proj_b", +] + + +class FP8Config(BaseConfig): + """Replace dense linear modules with DeepGEMM FP8 linears.""" + + type: Literal["fp8"] = "fp8" + ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS + """Dense linear module names excluded from DeepGEMM FP8 replacement.""" + + extra_ignore_patterns: list[str] = [] + """Patterns appended to `ignore_patterns`, to exclude model-specific modules while keeping the defaults.""" + + +class MXFP8Config(BaseConfig): + """Replace dense linear modules with torchao MXFP8 linears.""" + + type: Literal["mxfp8"] = "mxfp8" + recipe: MXFP8Recipe = "mxfp8_rceil" + """MXFP8 recipe for dense linear modules.""" + + ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS + """Dense linear module names excluded from torchao MXFP8 replacement.""" + + extra_ignore_patterns: list[str] = [] + """Patterns appended to `ignore_patterns`, to exclude model-specific modules while keeping the defaults.""" + + +QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")] + + +class ScratchInit(BaseConfig): + """The model's own random init (its ``_init_weights``, with the ``initializer_range`` of ``model.name``'s + config.json); ``model.name`` supplies only the architecture and the tokenizer.""" + + type: Literal["scratch"] = "scratch" + + seed: int = 0 + """Seed of the init: the same seed gives the same weights on the same GPU layout.""" + + +class PretrainedInit(BaseConfig): + """The weights stored at ``model.name``: an HF model (Hub id or local directory), or a checkpoint step directory + (``.../step_``) of another run, whose ``trainer/`` weights load and whose ``config.json`` and tokenizer files + supply the architecture and the tokenizer. A step directory starts the run at step 0 with a fresh optimizer, + scheduler and data.""" + + type: Literal["pretrained"] = "pretrained" + + +InitConfig: TypeAlias = Annotated[ScratchInit | PretrainedInit, Field(discriminator="type")] + + +class TrainerModelConfig(BaseModelConfig): + """The model to train, its parallelism, precision and kernels.""" + + vlm: VLMConfig | None = None + """VLM configuration. Setting this enables vision-language model support.""" + + conversion_dir: Path | None = None + """Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory.""" + + init: InitConfig = PretrainedInit() + """Where the weights start. A resumed run loads its own checkpoint instead, whatever the type.""" + + seq_len: int = 2048 + """Sequence length the model is trained on.""" + + attn: AttnImplementation = "auto" + """Attention implementation. ``auto`` selects FA3 on Hopper (SM90) and FA4 on Blackwell (SM100+).""" + + compile: CompileConfig | None = CompileConfig() + """Compile the model with ``torch.compile``. If None, the model runs eagerly.""" + + fusions: FusionsConfig = FusionsConfig() + """Runtime parameter fusions.""" + + ac: ActivationCheckpointConfig | None = ActivationCheckpointConfig() + """Activation checkpointing configuration. If None, activation checkpointing is disabled.""" + + ac_offloading: ActivationOffloadingConfig | None = ActivationOffloadingConfig() + """Activation offloading configuration. If None, activation offloading is disabled.""" + + offload: OffloadMode = "optimizer" + """CPU offloading. ``optimizer`` keeps optimizer states (momentum, variance) in CPU RAM and weights on GPU. ``full`` keeps FP32 masters, optimizer states, and accumulated gradients in CPU RAM and runs each optimizer chunk on CPU as soon as its last gradient arrives, overlapped with backward; it supports AdamW and SignSGD only, disables gradient clipping, and rounds each gradient to BF16 once before the FP32 CPU update. ``none`` keeps everything on GPU.""" + + reshard_after_forward: bool = True + """Reshard the model after each forward pass.""" + + dp_replicate: int = 1 + """Data parallel dim where model weights are replicated.""" + + ep: int | Literal["auto"] = "auto" + """Expert parallelism degree for MoE layers. 1 disables EP. ``auto`` resolves for MoE models to the largest degree up to 8 that divides both ``fsdp_island_size = world_size // dp_replicate`` and the expert count and is a multiple of ``cp``, and to 1 for non-MoE models. Set an explicit integer to override.""" + + moe: MoERuntimeConfig = MoERuntimeConfig() + """Routed-expert compute and token-dispatch runtime.""" + + cp: int = 1 + """Context parallelism degree. 1 disables CP.""" + + optimization_dtype: Literal["bfloat16", "float32"] = "float32" + """dtype for model optimization.""" + + reduce_dtype: Literal["bfloat16", "float32"] = "float32" + """dtype for gradient/parameter reductions.""" + + reduce_scatter_max_input_buffers: int = Field(1, ge=1) + """Maximum number of FSDP gradient reduce-scatter input buffers kept in flight. Raising it trades memory (about one layer's gradients per extra buffer) for overlap when reduce-scatters are exposed, e.g. MoE without EP or full activation checkpointing.""" + + quantization: QuantizationConfig | None = None + """Low-precision replacement of dense linear modules. If None, no dense linear is quantized.""" + + dsa_backend: DSABackend = "cudnn_flashmla" + """Kernels for the sparse attention of ``glm_moe_dsa`` (DSA sparse MLA, e.g. GLM-5) and ``deepseek_v4``. ``cudnn_flashmla`` runs the FlashMLA sparse prefill forward with the cuDNN frontend CuTe-DSL backward; it needs an SM90, SM100 or SM103 GPU, vLLM's bundled FlashMLA (installed with the ``gpu`` extra), 64 or 128 attention heads and head_dim 512, and setup fails otherwise. ``tilelang`` runs the TileLang forward and backward.""" + + dsv4_kv_precision: Literal["bf16", "fp8"] = "fp8" + """Precision DeepSeek V4 attention reads keys and values at. ``fp8`` rounds them as vLLM's ``fp8_ds_mla`` KV cache stores them, with a straight-through gradient.""" + + dsv4_compressor_backend: Literal["cudnn", "torch"] = "cudnn" + """Backend of the DeepSeek V4 compressors' softmax-gated pooling. ``cudnn`` runs the cuDNN frontend's fused CSA/HCA compressor where its kernels apply: an SM100 or newer GPU, bf16 activations, and a compress rate of 2 or 4, or 128 with head_dim 128 or 512. Elsewhere it silently runs the torch ops, so on SM90 GPUs such as the H100 and H200 ``cudnn`` runs torch. ``cudnn`` scans each entry's document list, so it wins on rows of few long documents and loses to the flat torch ops on rows of many short documents. ``torch`` always runs the torch ops.""" + + freeze_moe_router: bool | Literal["auto"] = "auto" + """Freeze MoE router gate parameters. ``auto``: ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys.""" + + lora: LoRAConfig | None = None + """LoRA configuration. If None, LoRA is disabled.""" + + debug: DebugModelConfig = DebugModelConfig() + """Debugging knobs for the model and distributed training.""" + + fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192 + """Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. In SFT the fused head computes the summed cross-entropy and its gradients chunk by chunk, holding one chunk's full-vocab logits at a time.""" + + @model_validator(mode="after") + def validate_scratch_lora(self): + if self.init.type == "scratch" and self.lora is not None: + raise ValueError('model.lora adapts pretrained weights, which model.init.type = "scratch" does not load') + return self + + @model_validator(mode="after") + def validate_cp(self): + if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]: + raise ValueError("CP is only supported with flash attention 2, 3, or 4") + return self + + @model_validator(mode="after") + def module_qualified_ac_targets_require_compile(self): + if ( + self.compile is None + and self.ac is not None + and any(MODULE_TARGET_SEPARATOR in target for target in self.ac.targets or []) + ): + raise ValueError("Module-qualified model.ac.targets require model.compile.") + return self + + @model_validator(mode="after") + def ac_offloading_requires_ac(self): + """Activation offloading requires activation checkpointing, so ``ac = None`` disables both.""" + if self.ac is None: + self.ac_offloading = None + return self + + @model_validator(mode="after") + def validate_moe_runtime(self): + if self.ep == 1: + return self + + compute = self.moe.compute + dispatch = self.moe.dispatch + if isinstance(dispatch, TorchMoEDispatchConfig) and dispatch.transport == "mxfp8": + if not isinstance(compute, MXFP8MoEComputeConfig): + raise ValueError("MXFP8 transport requires model.moe.compute.type='mxfp8'.") + return self + + +def rl_micro_batch_multiple(model: TrainerModelConfig) -> int: + """RL micro batches are padded to a multiple of this: one shard per CP rank, and MXFP8 linears quantize + grad_output in 32-token blocks per CP rank.""" + if isinstance(model.quantization, MXFP8Config): + return model.cp * 32 + return model.cp diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/moe.py b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/moe.py new file mode 100644 index 00000000000..7bbe4812649 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/moe.py @@ -0,0 +1,215 @@ +import re +from typing import Annotated, Literal, TypeAlias + +from pydantic import Field, field_validator, model_validator + +from prime_rl.configs.base import BaseConfig + +MXFP8Recipe: TypeAlias = Literal["mxfp8_rceil", "mxfp8_rceil_wgrad_with_hp"] + + +class MoEComputeConfigBase(BaseConfig): + """Fields shared by the routed-expert compute backends.""" + + apply_to: str | list[Annotated[int, Field(ge=0, strict=True)]] = "all" + """Model layers to use this backend for: ``"all"``, a percentage such as ``"85%"``, + or zero-based layer indices such as ``[0, 1, 2]``. Percentages select the first fraction + of model layers, rounded down. Other expert groups use BF16 compute and transport. + """ + + @field_validator("apply_to") + @classmethod + def validate_apply_to(cls, value: str | list[int]) -> str | list[int]: + if isinstance(value, str) and value != "all": + if re.fullmatch(r"\d+(?:\.\d+)?%", value) is None or float(value[:-1]) > 100: + raise ValueError('apply_to must be "all", a percentage from "0%" to "100%", or a list of layer indices') + return value + + def resolve_layers(self, num_layers: int) -> set[int]: + if isinstance(self.apply_to, list): + invalid = [index for index in self.apply_to if index >= num_layers] + if invalid: + raise ValueError( + f"apply_to layer indices {invalid} are out of range for a model with {num_layers} layers" + ) + return set(self.apply_to) + count = num_layers if self.apply_to == "all" else int(num_layers * float(self.apply_to[:-1]) / 100) + return set(range(count)) + + +class BF16MoEComputeConfig(MoEComputeConfigBase): + """Run routed experts in bfloat16.""" + + type: Literal["bf16"] = "bf16" + backend: Literal["torch", "sonicmoe"] = "torch" + """Expert compute implementation.""" + + +class DeepGemmFP8MoEComputeConfig(MoEComputeConfigBase): + """Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels.""" + + type: Literal["deepgemm_fp8"] = "deepgemm_fp8" + + +class MXFP8MoEComputeConfig(MoEComputeConfigBase): + """Run routed-expert grouped GEMMs with Prime's vendored MXFP8 implementation.""" + + type: Literal["mxfp8"] = "mxfp8" + recipe: MXFP8Recipe = "mxfp8_rceil" + """MXFP8 expert-compute recipe.""" + + +class NVFP4MoEComputeConfig(MoEComputeConfigBase): + """Run routed experts with the numerics of vLLM's online ``nvfp4_per_token`` MoE: NVFP4 forward with per-token + activation scales and the engines' load-time weight quantizer, MXFP8 backward on the dequantized operands (SM100). + In ``rl`` the engines must run ``quantization = "online"`` with ``quantization_config.moe = "nvfp4_per_token"``.""" + + type: Literal["nvfp4"] = "nvfp4" + four_over_six: bool = False + """Choose each activation block's scale with 4/6 (the lower-error of the max-6 and max-4 scales), as FlashInfer's + ``FLASHINFER_NVFP4_4OVER6``. ``rl`` applies the same setting to the engines. Weights never use it.""" + + @property + def flashinfer_env(self) -> dict[str, str]: + """FlashInfer quantizer settings the trainer and the engines share: IEEE division, 4/6 on or off.""" + return { + "FLASHINFER_DISABLE_FP4_QUANT_FAST_MATH": "1", + "FLASHINFER_NVFP4_4OVER6": "1" if self.four_over_six else "0", + } + + +MoEComputeConfig: TypeAlias = Annotated[ + BF16MoEComputeConfig | DeepGemmFP8MoEComputeConfig | MXFP8MoEComputeConfig | NVFP4MoEComputeConfig, + Field(discriminator="type"), +] + + +class TorchMoEDispatchConfig(BaseConfig): + """Dispatch and combine routed tokens with torch all-to-all collectives.""" + + type: Literal["torch"] = "torch" + transport: Literal["bf16", "mxfp8"] = "bf16" + """Wire format for routed activations and their reverse-path gradients.""" + + +class DeepEPMoEDispatchConfig(BaseConfig): + """Dispatch and combine routed tokens with DeepEP.""" + + type: Literal["deepep"] = "deepep" + num_sms: int = Field(32, ge=1) + """SMs allocated to DeepEP communication kernels.""" + + +class LLEPConfig(BaseConfig): + """Least-loaded expert parallelism (https://arxiv.org/abs/2601.17111): a rank whose experts are overloaded hands + part of their routes, with a copy of the experts' weights, to the least-loaded ranks. The computation stays exact.""" + + alpha: float = Field(1.05, ge=1.0) + """A rank counts as full at ``alpha`` times the mean routes per rank.""" + + min_chunk: int = Field(1024, ge=1) + """Fewest routes worth copying an expert's weights to another rank.""" + + lam: float = Field(1.1, ge=0.0) + """Below this busiest-rank over mean-rank load, every expert stays on its own rank (standard EP).""" + + max_foreign: int = Field(8, ge=1) + """Experts a rank can compute for other ranks; each costs one expert's weights (and gradients) of memory.""" + + chunk_tokens: int | None = Field(None, ge=1) + """Tokens per rank per kernel call. A larger batch runs as several calls, so the symmetric buffers hold one chunk + instead of the whole batch (for long sequences). ``None``: one call per layer.""" + + max_recv: float = Field(1.3, gt=0.0) + """Routes a rank's buffers hold, as a multiple of its own routes (``max_tokens_per_rank * top_k``). The plan keeps + every rank within about ``max(alpha, lam)`` of the mean, so this can be far below the ``ep`` multiple plain Mega MoE + reserves. A plan that would exceed it (only when helpers run out of foreign slots) stops the kernel with an error.""" + + @model_validator(mode="after") + def validate_max_recv(self): + if self.max_recv < max(self.alpha, self.lam): + raise ValueError("model.moe.dispatch.llep.max_recv must be at least max(alpha, lam).") + return self + + +class MegaMoeMoEDispatchConfig(BaseConfig): + """Dispatch routed tokens, run the experts and combine their outputs in DeepGEMM's fused Mega MoE kernels.""" + + type: Literal["mega_moe"] = "mega_moe" + precision: Literal["bf16", "mxfp8", "mxfp8_qat", "fp8", "fp8_bwd", "nvfp4"] = "bf16" + """Expert GEMM precision. ``mxfp8``: forward and backward in MXFP8 (SM100). ``mxfp8_qat``: MXFP8 forward, BF16 + backward on the forward's dequantized weights, as MXFP8 quantization-aware training computes (SM100). ``fp8``: + forward and backward in blockwise FP8 (SM90). ``fp8_bwd``: BF16 forward, blockwise FP8 backward (SM90). + ``nvfp4``: NVFP4 forward as vLLM's online ``nvfp4_per_token`` MoE computes it (per-token activation and per-expert + weight scales), MXFP8 backward on the forward's NVFP4 operands (SM100). In ``rl`` the engines must run that MoE + quantization with the same ``four_over_six``.""" + + four_over_six: bool = False + """``nvfp4`` only: choose each activation block's scale with 4/6, as FlashInfer's ``FLASHINFER_NVFP4_4OVER6``.""" + + max_tokens_per_rank: int | None = Field(None, ge=1) + """Tokens per rank per MoE call that the symmetric buffer is sized for. Defaults to the rank's share of the + micro batch under context parallelism (``model.seq_len / model.cp`` for RL, + ``data.micro_batch_size * data.seq_len / model.cp`` for SFT) and cannot be smaller.""" + + num_reserved_sms: int = Field(16, ge=2) + """SMs left free for concurrent NCCL kernels. In the worst case each NCCL kernel uses all ``NCCL_MAX_CTAS``, so + at most ``num_reserved_sms // NCCL_MAX_CTAS`` NCCL kernels can run concurrently. FSDP overlaps an all-gather and + a reduce-scatter, and HSDP (``dp_replicate > 1``) adds an all-reduce, so the trainer sets ``NCCL_MAX_CTAS`` to + this value divided by 2 (3 under HSDP) when it is unset and requires it to be at most that. Defaults to 32 with + ``llep``, whose weight copies run next to the grid.""" + + llep: LLEPConfig | None = None + """Balance imbalanced routing with least-loaded expert parallelism. Requires ``precision = "bf16"`` (SM90), + ``"mxfp8"``, ``"mxfp8_qat"`` or ``"nvfp4"`` (SM100).""" + + @model_validator(mode="after") + def validate_llep_precision(self): + if self.llep is not None and self.precision not in ("bf16", "mxfp8", "mxfp8_qat", "nvfp4"): + raise ValueError( + "model.moe.dispatch.llep requires model.moe.dispatch.precision 'bf16', 'mxfp8', 'mxfp8_qat' or 'nvfp4'." + ) + return self + + @model_validator(mode="after") + def validate_four_over_six(self): + if self.four_over_six and self.precision != "nvfp4": + raise ValueError("model.moe.dispatch.four_over_six requires model.moe.dispatch.precision 'nvfp4'.") + return self + + @model_validator(mode="after") + def llep_reserved_sms(self): + if self.llep is not None and "num_reserved_sms" not in self.model_fields_set: + self.num_reserved_sms = 32 + return self + + +def mega_moe_max_tokens_per_rank(max_tokens_per_rank: int | None, micro_batch_tokens: int, cp: int) -> int: + """A rank with more tokens than its buffer fails alone while its peers wait in the kernel, so the + buffer must hold the rank's full share of the micro batch. Context parallelism splits every micro + batch evenly over the ``cp`` ranks, so that share is ``micro_batch_tokens / cp``.""" + rank_tokens = -(-micro_batch_tokens // cp) + if max_tokens_per_rank is None: + return rank_tokens + if max_tokens_per_rank < rank_tokens: + raise ValueError( + f"model.moe.dispatch.max_tokens_per_rank ({max_tokens_per_rank}) must be at least the tokens a rank " + f"holds per micro batch ({micro_batch_tokens} tokens over cp={cp}: {rank_tokens})." + ) + return max_tokens_per_rank + + +MoEDispatchConfig: TypeAlias = Annotated[ + TorchMoEDispatchConfig | DeepEPMoEDispatchConfig | MegaMoeMoEDispatchConfig, + Field(discriminator="type"), +] + + +class MoERuntimeConfig(BaseConfig): + """Independent routed-expert compute and token-dispatch choices.""" + + compute: MoEComputeConfig = BF16MoEComputeConfig() + """Routed-expert compute backend.""" + + dispatch: MoEDispatchConfig = TorchMoEDispatchConfig() + """How routed tokens move to and from the expert-parallel ranks.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/optim.py b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/optim.py new file mode 100644 index 00000000000..f1dd50a5cb8 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/optim.py @@ -0,0 +1,151 @@ +from typing import Annotated, Literal, TypeAlias + +from pydantic import Field + +from prime_rl.configs.base import BaseConfig + + +class ConstantSchedulerConfig(BaseConfig): + """Constant learning rate at ``optim.lr``.""" + + type: Literal["constant"] = "constant" + + start_step: int = Field(0, ge=0) + """The step the schedule starts at. A constant schedule is the same at every step.""" + + +class LinearSchedulerConfig(BaseConfig): + """Linear warmup to ``optim.lr``, a constant phase, then a linear decay to ``min_lr`` (WSD).""" + + type: Literal["linear"] = "linear" + + warmup_steps: int = Field(10, ge=0) + """Warmup steps for the learning rate scheduler.""" + + decay_steps: int = Field(10, ge=0) + """Steps to decay the learning rate during the final portion of training.""" + + min_lr: float = Field(0.0, ge=0) + """Learning rate the base param group, whose peak is ``optim.lr``, warms up from and decays to. Every other param + group warms up from and decays to ``min_lr / optim.lr`` times its own peak. 0 means a factor of ``1e-8``.""" + + start_step: int = Field(0, ge=0) + """The step the schedule starts at: its warmup and decay span the ``max_steps - start_step`` steps after it. Set + it to a resume step to start a fresh schedule there.""" + + +class CosineSchedulerConfig(BaseConfig): + """Linear warmup to ``optim.lr``, then a cosine decay to ``min_lr`` at ``max_steps``.""" + + type: Literal["cosine"] = "cosine" + + warmup_steps: int = Field(10, ge=0) + """Warmup steps for the learning rate scheduler.""" + + min_lr: float = Field(0.0, ge=0) + """Learning rate the base param group, whose peak is ``optim.lr``, warms up from and decays to. Every other param + group warms up from and decays to ``min_lr / optim.lr`` times its own peak. 0 means a warmup from ``1e-8`` times + the peak and a decay to 0.""" + + start_step: int = Field(0, ge=0) + """The step the schedule starts at: its warmup and decay span the ``max_steps - start_step`` steps after it. Set + it to a resume step to start a fresh schedule there.""" + + +SchedulerConfig: TypeAlias = Annotated[ + ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type") +] + + +def validate_scheduler(scheduler: SchedulerConfig, max_steps: int | None) -> None: + """Check scheduler phases against max_steps so misconfigurations fail at config time.""" + if max_steps is not None and scheduler.start_step >= max_steps: + raise ValueError(f"start_step ({scheduler.start_step}) must be less than max_steps ({max_steps})") + # The steps the schedule spans + horizon = max_steps - scheduler.start_step if max_steps is not None else None + if isinstance(scheduler, LinearSchedulerConfig): + if scheduler.warmup_steps == 0 and scheduler.decay_steps == 0: + raise ValueError( + "Linear scheduler requires warmup_steps > 0 or decay_steps > 0 (use the constant scheduler instead)" + ) + if scheduler.decay_steps == 1: + raise ValueError("decay_steps must be 0 or at least 2") + if scheduler.decay_steps > 0: + if horizon is None: + raise ValueError("Must specify max_steps when using a linear scheduler with decay_steps > 0") + if scheduler.warmup_steps + scheduler.decay_steps > horizon: + raise ValueError( + f"warmup_steps ({scheduler.warmup_steps}) + decay_steps ({scheduler.decay_steps}) " + f"must not exceed max_steps - start_step ({horizon})" + ) + if isinstance(scheduler, CosineSchedulerConfig): + if horizon is None: + raise ValueError("Must specify max_steps when using a cosine scheduler") + if scheduler.warmup_steps >= horizon: + raise ValueError( + f"warmup_steps ({scheduler.warmup_steps}) must be less than max_steps - start_step ({horizon})" + ) + + +class BaseOptimizerConfig(BaseConfig): + """Fields shared by all optimizers.""" + + lr: float = Field(1e-6, ge=0) + """Peak learning rate.""" + + weight_decay: Annotated[float, Field(ge=0)] | Literal["auto"] = "auto" + """L2 weight-decay coefficient. ``"auto"`` resolves to ``0.0`` for RL and ``0.01`` for SFT and pretraining.""" + + max_norm: float | None = Field(1.0, ge=0) + """Maximum gradient norm to clip to. If None, gradient clipping is disabled.""" + + +class AdamWConfig(BaseOptimizerConfig): + """AdamW optimizer.""" + + type: Literal["adamw"] = "adamw" + + betas1: float = Field(0.9, ge=0) + """Adam first-moment (β1) decay.""" + + betas2: float = Field(0.999, ge=0) + """Adam second-moment (β2) decay.""" + + eps: float = Field(1e-8, gt=0) + """Adam epsilon, added to the denominator of the update.""" + + +class MuonConfig(BaseOptimizerConfig): + """Muon on the weight matrices and an AdamW sub-optimizer on the other params.""" + + type: Literal["muon"] = "muon" + + mu: float = Field(0.95, ge=0) + """Momentum factor for the Muon algorithm.""" + + nesterov: bool = True + """Nesterov momentum for the Muon updates.""" + + betas1: float = Field(0.9, ge=0) + """β1 for the AdamW sub-optimizer used on non-Muon params.""" + + betas2: float = Field(0.95, ge=0) + """β2 for the AdamW sub-optimizer used on non-Muon params.""" + + eps: float = Field(1e-8, gt=0) + """Epsilon for the AdamW sub-optimizer used on non-Muon params, and for the Newton-Schulz normalization.""" + + update_rms: float = Field(0.2, gt=0) + """RMS of each Muon update matrix, so Muon reuses the AdamW learning rate. DeepSeek-V4.1 uses 0.18.""" + + newton_schulz_schedule: Literal["default", "deepseek_v4", "polar_express", "step3p5"] = "default" + """Coefficient schedule of the Newton-Schulz iteration that orthogonalizes the updates. ``default``: 5 quintic steps with per-step coefficients. ``deepseek_v4``: 8 steps of (3.4445, -4.7750, 2.0315), then 2 steps of (2, -1.5, 0.5) that pin the singular values at 1. ``polar_express``: 5 steps of Polar Express (arXiv 2505.16932) in bf16, with its 1.01 safety factor. ``step3p5``: 6 Polar Express steps in fp16, as in Step 3.5 Flash.""" + + +class SignSGDConfig(BaseOptimizerConfig): + """SignSGD: steps each param by the sign of its gradient. Keeps no optimizer state.""" + + type: Literal["sign_sgd"] = "sign_sgd" + + +OptimizerConfig: TypeAlias = Annotated[AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")] diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/pretrain.py b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/pretrain.py new file mode 100644 index 00000000000..dec7eb6330a --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/pretrain.py @@ -0,0 +1,92 @@ +from typing import Annotated, TypeAlias + +from pydantic import Field, model_validator + +from prime_rl.configs.base import ComponentConfig +from prime_rl.configs.blocks.weight_broadcast import WeightBroadcastConfig +from prime_rl.configs.components.trainer.base import SupervisedTrainerSection +from prime_rl.configs.components.trainer.data import PretrainDataConfig, ValConfig +from prime_rl.configs.components.trainer.model import InitConfig, ScratchInit, TrainerModelConfig +from prime_rl.configs.components.trainer.optim import ( + AdamWConfig, + ConstantSchedulerConfig, + CosineSchedulerConfig, + LinearSchedulerConfig, + MuonConfig, + SignSGDConfig, +) + + +class PretrainAdamWConfig(AdamWConfig): + """AdamW optimizer, with a peak learning rate for pretraining.""" + + lr: float = Field(1e-3, ge=0) + """Peak learning rate.""" + + +class PretrainMuonConfig(MuonConfig): + """Muon optimizer, with a peak learning rate for pretraining.""" + + lr: float = Field(1e-3, ge=0) + """Peak learning rate.""" + + +PretrainOptimizerConfig: TypeAlias = Annotated[ + PretrainAdamWConfig | PretrainMuonConfig | SignSGDConfig, Field(discriminator="type") +] + + +class PretrainLinearSchedulerConfig(LinearSchedulerConfig): + """Linear warmup to ``optim.lr``, a constant phase, then a linear decay to ``min_lr`` (WSD).""" + + decay_steps: int = Field(0, ge=0) + """Steps to decay the learning rate during the final portion of training. A decay needs ``max_steps``.""" + + +PretrainSchedulerConfig: TypeAlias = Annotated[ + ConstantSchedulerConfig | PretrainLinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type") +] + + +class PretrainModelConfig(TrainerModelConfig): + """The model to pretrain, its parallelism, precision and kernels.""" + + init: InitConfig = ScratchInit() + """Where the weights start. A resumed run loads its own checkpoint instead, whatever the type.""" + + +class PretrainTrainerSection(SupervisedTrainerSection): + """The pretraining trainer fields, at the top level of the ``pretrain`` entrypoint: next-token loss on tokenized + shards, with the weights initialized from scratch by default.""" + + model: PretrainModelConfig = PretrainModelConfig() + """The model to train, its parallelism, precision and kernels.""" + + data: PretrainDataConfig + """Training shards and their batching.""" + + val: ValConfig | None = None + """Validation on held-out document sets. If None, no validation runs.""" + + optim: PretrainOptimizerConfig = PretrainAdamWConfig() + """Optimizer.""" + + scheduler: PretrainSchedulerConfig = PretrainLinearSchedulerConfig() + """Learning rate schedule. From a random init, Adam's first updates at the full learning rate are unstable, so + warm up first.""" + + @model_validator(mode="after") + def validate_repetitions(self): + if self.max_steps is None and any(source.repetitions is not None for source in self.data.source): + raise ValueError( + "data.source: repetitions sizes a source's subset by the run's tokens, so it needs max_steps" + ) + return self + + +class PretrainTrainerConfig(PretrainTrainerSection, ComponentConfig): + """Config of the pretraining trainer process. The ``pretrain`` launcher builds it from the top-level trainer + fields.""" + + weight_broadcast: WeightBroadcastConfig | None = None + """Weight transport for online evals. None without online evals.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/sft.py b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/sft.py new file mode 100644 index 00000000000..3bc952a25eb --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/trainer/sft.py @@ -0,0 +1,60 @@ +from pydantic import model_validator +from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig +from renderers.base import MODEL_RENDERER_MAP + +from prime_rl.configs.base import ComponentConfig +from prime_rl.configs.blocks.weight_broadcast import WeightBroadcastConfig +from prime_rl.configs.components.trainer.base import SupervisedTrainerSection +from prime_rl.configs.components.trainer.data import SFTDataConfig, SFTValConfig + + +class SFTTrainerSection(SupervisedTrainerSection): + """The SFT trainer fields, at the top level of the ``sft`` entrypoint.""" + + renderer: RendererConfig = AutoRendererConfig() + """Renderer config. The ``auto`` renderer selects one from the tokenizer model name.""" + + data: SFTDataConfig = SFTDataConfig() + """Training data and its batching.""" + + val: SFTValConfig | None = None + """Validation configuration. If None, no validation runs.""" + + @model_validator(mode="after") + def validate_typed_renderer(self): + """Require a typed renderer whenever SFT renders real samples.""" + if self.data.fake is not None and self.val is None: + return self + + model_id = self.tokenizer.name or self.model.name + if isinstance(self.renderer, AutoRendererConfig): + if model_id in MODEL_RENDERER_MAP: + return self + reason = f"no typed renderer is registered for {model_id!r}" + elif isinstance(self.renderer, DefaultRendererConfig): + reason = "renderer.name='default' selects DefaultRenderer" + else: + return self + + raise ValueError( + f"SFT requires a typed renderer with sampled-token and content attribution, but {reason}. " + "Implement and register the renderer in the renderers package, or explicitly select an existing " + "typed renderer only when its template is verified to match." + ) + + @model_validator(mode="after") + def validate_vlm_constraints(self): + if self.model.vlm is None: + return self + if self.data.micro_batch_size != 1: + raise ValueError("VLM SFT requires data.micro_batch_size = 1.") + if self.val is not None and self.val.data.micro_batch_size != 1: + raise ValueError("VLM SFT requires val.data.micro_batch_size = 1.") + return self + + +class SFTTrainerConfig(SFTTrainerSection, ComponentConfig): + """Config of the SFT trainer process. The ``sft`` launcher builds it from the top-level trainer fields.""" + + weight_broadcast: WeightBroadcastConfig | None = None + """Weight transport for online evals. None without online evals.""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/__init__.py b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/_supervised.py b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/_supervised.py new file mode 100644 index 00000000000..a044ab280bc --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/_supervised.py @@ -0,0 +1,373 @@ +import warnings +from typing import Annotated, TypeAlias +from urllib.parse import urlparse + +from pydantic import Field, model_validator + +from prime_rl.configs.base import ComponentConfig, EntrypointConfig, Placement, build_component_config +from prime_rl.configs.blocks.ckpt import ckpt_output_dir +from prime_rl.configs.blocks.deployment import BaseMultiNodeDeploymentConfig, BaseSingleNodeDeploymentConfig +from prime_rl.configs.blocks.slurm import SlurmConfig +from prime_rl.configs.blocks.weight_broadcast import ( + FileSystemWeightBroadcastConfig, + NCCLWeightBroadcastSection, + weight_broadcast_config, +) +from prime_rl.configs.components.engine import ( + EngineConfig, + reject_explicit_data_parallel_size, + set_max_lora_rank, + setup_dummy_load, +) +from prime_rl.configs.components.env_worker_pool import EnvWorkerPoolConfig, env_worker_pool_config, env_worker_pool_key +from prime_rl.configs.components.modelexpress_server import ModelExpressServerConfig, modelexpress_server_config +from prime_rl.configs.components.online_eval import SFTOnlineEvalConfig +from prime_rl.configs.components.router import RouterConfig +from prime_rl.configs.components.trainer.base import SupervisedTrainerSection +from prime_rl.configs.entrypoints.inference import ServingSection +from prime_rl.utils.config import dump_resolved_config, find_package_resource + + +class SupervisedSingleNodeDeploymentConfig(BaseSingleNodeDeploymentConfig): + """Run the trainer, and the inference server of online evals, on one node.""" + + @model_validator(mode="after") + def validate_gpu_count(self): + if self.num_train_gpus > self.gpus_per_node: + raise ValueError(f"num_train_gpus ({self.num_train_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).") + return self + + +class SupervisedMultiNodeDeploymentConfig(BaseMultiNodeDeploymentConfig): + """Run the trainer, and the inference of online evals, on several nodes as one SLURM job.""" + + num_infer_nodes: int = Field(0, ge=0) + """Inference nodes for online evals. These nodes share one SLURM allocation with the + trainer nodes.""" + + +SupervisedDeploymentConfig: TypeAlias = Annotated[ + SupervisedSingleNodeDeploymentConfig | SupervisedMultiNodeDeploymentConfig, Field(discriminator="type") +] + + +class SupervisedConfig(SupervisedTrainerSection, EntrypointConfig): + """The launch fields of the ``sft`` and ``pretrain`` entrypoints: online-eval inference, deployment, SLURM.""" + + inference: ServingSection | None = None + """Inference server for online evals. If None (with ``eval`` set), the launcher + does not start a server and evals connect to ``eval.client.base_url``.""" + + clean: bool = False + """Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming.""" + + deployment: SupervisedDeploymentConfig = SupervisedSingleNodeDeploymentConfig() + """GPU and node placement of the trainer and the online-eval inference.""" + + slurm: SlurmConfig | None = None + """SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally.""" + + dashboard: bool = True + """Make sure a local dashboard daemon serves this run's output dir (started on + demand in interactive sessions; an already-running daemon's URL is logged).""" + + dry_run: bool = False + """Only validate and dump resolved configs, then exit early.""" + + ### Pre-validation normalization + + @model_validator(mode="before") + @classmethod + def propagate_model_to_inference(cls, data): + """Fill ``inference.vllm.model`` and ``tokenizer`` from ``model.name`` and ``tokenizer.name`` before + InferenceConfig construction, so its parser auto-resolution sees the right names.""" + if not isinstance(data, dict): + return data + inference = data.get("inference") + if not isinstance(inference, dict): + return data + vllm = inference.setdefault("vllm", {}) + if not isinstance(vllm, dict): + return data + for section, key in (("model", "model"), ("tokenizer", "tokenizer")): + config = data.get(section) + name = config.get("name") if isinstance(config, dict) else None + if name: + vllm.setdefault(key, name) + return data + + ### Validate configs (e.g. raise for unsupported (combinations of) configs) + + @model_validator(mode="after") + def validate_deployment(self): + if self.deployment.type == "multi_node" and self.slurm is None: + raise ValueError("Must use SLURM for multi-node deployment.") + return self + + @model_validator(mode="after") + def validate_router_deployment(self): + """The SLURM templates launch the llm-d router (EPP + Envoy) for the engines on dedicated nodes.""" + router = self.inference.router if self.inference is not None else None + if router is not None and router.type == "llm-d" and self.deployment.type == "single_node": + raise ValueError("The llm-d router backend requires a multi-node SLURM deployment.") + return self + + @model_validator(mode="after") + def validate_weight_broadcast_inference(self): + if self.weight_broadcast is not None and self.weight_broadcast.type != "filesystem" and self.inference is None: + raise ValueError( + f"{self.weight_broadcast.type} weight broadcast requires launcher-managed inference. " + "Add an [inference] block or set weight_broadcast.type = 'filesystem'." + ) + return self + + @property + def inference_world_size(self) -> int: + """Inference GPUs across all engines. Each one is a worker of the in-memory weight transfer.""" + if self.deployment.type == "multi_node": + return self.deployment.num_infer_nodes * self.deployment.gpus_per_node + if self.inference is None: + return 1 + return self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size + + def weight_broadcast_config(self, nccl_host: str = "localhost") -> dict | None: + """The ``weight_broadcast`` of a process that takes part in the weight transfer.""" + if self.weight_broadcast is None: + return None + return weight_broadcast_config(self.weight_broadcast, self.inference_world_size, nccl_host) + + def trainer_config(self) -> SupervisedTrainerSection: + """The trainer process's config: the trainer fields at the top level.""" + raise NotImplementedError + + def online_eval_config(self) -> SFTOnlineEvalConfig | None: + """The online-eval process's config: ``[eval]`` plus the run fields it reads.""" + if self.eval is None: + return None + return build_component_config( + SFTOnlineEvalConfig, + self.eval, + model=self.model.name, + weight_broadcast=self.weight_broadcast_config(), + max_steps=self.max_steps, + resume=dump_resolved_config(self.resume) if self.resume else None, + ckpt_output_dir=ckpt_output_dir(self.run_dir, self.ckpt), + # The dashboard reads the eval's file-monitor artifacts from the trainer's run directory. + output_dir=self.run_dir, + log={"level": self.log.level, "json_logging": self.log.json_logging}, + monitors=dump_resolved_config(self.monitors), + ) + + def engine_configs(self) -> dict[str, EngineConfig]: + """The engine process config of the online evals, keyed like ``components()``.""" + if self.inference is None: + return {} + engine = self.inference.engine_config(self.weight_broadcast.type) + # The launcher gives the engine the run's admin token, so it may not serve its admin routes open. + engine.server.require_admin_token = True + return {"engine": engine} + + def router_config(self) -> RouterConfig | None: + """The router process's config. A multi-node launcher passes the engine URLs at start.""" + if self.inference is None: + return None + return self.inference.router_config(local=self.deployment.type == "single_node") + + def env_worker_pool_configs(self) -> dict[str, EnvWorkerPoolConfig]: + """The config of every env worker pool the online evals start, keyed ``envs/eval/``.""" + if self.eval is None: + return {} + return { + env_worker_pool_key("eval", source.resolved_name): env_worker_pool_config(source, self.log, self.run_dir) + for source in self.eval.source + if source.serve.address is None + } + + def modelexpress_server_config(self) -> ModelExpressServerConfig | None: + """The config of the ModelExpress server that the online evals start, or None if they start none.""" + if self.eval is None or (self.slurm is not None and not self.slurm.launch_modelexpress): + return None + return modelexpress_server_config(self.weight_broadcast, self.run_dir / "logs") + + def components(self) -> dict[str, ComponentConfig]: + components: dict[str, ComponentConfig] = {"trainer": self.trainer_config()} + online_eval = self.online_eval_config() + if online_eval is None: + return components + components["online-eval"] = online_eval + modelexpress = self.modelexpress_server_config() + if modelexpress is not None: + components["modelexpress-server"] = modelexpress + components.update(self.engine_configs()) + router = self.router_config() + if router is not None: + components["router"] = router + components.update(self.env_worker_pool_configs()) + return components + + def placement(self) -> dict[str, Placement]: + deployment = self.deployment + if deployment.type == "single_node": + placement = {"trainer": Placement(gpus_per_node=deployment.num_train_gpus)} + engine = Placement(gpus_per_node=deployment.num_infer_gpus) + else: + placement = {"trainer": Placement(nodes=deployment.num_train_nodes, gpus_per_node=deployment.gpus_per_node)} + engine = Placement(nodes=max(deployment.num_infer_nodes, 1), gpus_per_node=deployment.gpus_per_node) + if self.eval is None: + return placement + placement["online-eval"] = Placement() + if self.modelexpress_server_config() is not None: + placement["modelexpress-server"] = Placement() + if self.inference is not None: + placement["engine"] = engine + if self.router_config() is not None: + placement["router"] = Placement() + for name in self.env_worker_pool_configs(): + placement[name] = Placement() + return placement + + @model_validator(mode="after") + def auto_setup_online_eval(self): + """Wire online evals and the trainer-to-inference weight transport.""" + if self.eval is None: + if self.inference is not None: + raise ValueError("[inference] is only used for online evals — add an [eval] block or remove it.") + return self + + # LoRA runs broadcast the raw adapter, which evals reload via /load_lora_adapter + if self.model.lora is not None: + if self.inference is not None: + self.inference.vllm.enable_lora = True + set_max_lora_rank(self.inference.vllm, self.model.lora.rank) + else: + warnings.warn( + "LoRA is enabled, but inference is not configured. When manually starting the inference server, " + "make sure to set --enable_lora and --max-lora-rank.", + stacklevel=2, + ) + + # A scratch init reaches the server with the trainer's startup broadcast. + if self.inference is not None: + setup_dummy_load(self.inference, self.model.init.type == "scratch") + + if self.weight_broadcast is None: + if self.model.lora is not None or self.inference is None: + self.weight_broadcast = FileSystemWeightBroadcastConfig() + else: + self.weight_broadcast = NCCLWeightBroadcastSection() + if self.weight_broadcast.type != "filesystem" and self.model.lora is not None: + raise ValueError( + "LoRA training is not yet supported with in-memory weight broadcast. " + "Set weight_broadcast.type = 'filesystem'." + ) + + if self.deployment.type == "multi_node": + # Dedicated nodes in the SFT allocation run the inference pool, router, + # env worker pools, and evals process. + if self.inference is None: + raise ValueError( + "Multi-node online evals require an [inference] block - dedicated nodes in the " + "SFT allocation run the inference pool and evals process." + ) + if self.deployment.num_infer_nodes < 1: + raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.") + if self.inference.router is None: + raise ValueError( + "Multi-node online evals require an inference router - the launcher starts one " + "router in front of the per-rank engines. Remove inference.router = 'None'." + ) + if self.inference.vllm.model != self.model.name: + raise ValueError( + f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name " + f"({self.model.name}). Remove inference.vllm.model to inherit it." + ) + if self.deployment.gpus_per_node % self.inference.vllm.tensor_parallel_size != 0: + raise ValueError( + f"deployment.gpus_per_node ({self.deployment.gpus_per_node}) must be divisible by " + f"inference.vllm.tensor_parallel_size ({self.inference.vllm.tensor_parallel_size})." + ) + if self.max_steps is None: + warnings.warn( + "Online evals without max_steps: the evals process never sees a final checkpoint, " + "so the SFT SLURM job holds its allocation until its walltime.", + stacklevel=2, + ) + # The client is wired at runtime by the SFT sbatch script (the router and + # per-rank admin URLs are only known once SLURM assigns hosts). + return self + + if self.inference is None: + warnings.warn( + "Online evals are configured without an [inference] block - the launcher will not " + f"start an inference server. Make sure one is running at eval.client.base_url " + f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', " + "otherwise the online-eval process will hang waiting for it. If a router fronts the " + "deployment, set eval.client.admin_base_url to the engine URLs - admin ops " + "(pause/update_weights/resume) must bypass the router.", + stacklevel=2, + ) + return self + + total_gpus = self.deployment.num_train_gpus + self.deployment.num_infer_gpus + if total_gpus > self.deployment.gpus_per_node: + raise ValueError( + f"Total GPU count ({total_gpus} = {self.deployment.num_train_gpus} train + " + f"{self.deployment.num_infer_gpus} infer) exceeds gpus_per_node " + f"({self.deployment.gpus_per_node})." + ) + + if self.inference.vllm.model != self.model.name: + raise ValueError( + f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name " + f"({self.model.name}). Remove inference.vllm.model to inherit it." + ) + + # Fill inference capacity with DP ranks (mirrors RLConfig.auto_setup_deployment). + num_infer_gpus = self.deployment.num_infer_gpus + vllm = self.inference.vllm + if num_infer_gpus != vllm.data_parallel_size * vllm.tensor_parallel_size: + reject_explicit_data_parallel_size(vllm, num_infer_gpus) + if num_infer_gpus % vllm.tensor_parallel_size != 0: + raise ValueError( + f"deployment.num_infer_gpus ({num_infer_gpus}) must be divisible by " + f"inference.vllm.tensor_parallel_size ({vllm.tensor_parallel_size})." + ) + vllm.data_parallel_size = num_infer_gpus // vllm.tensor_parallel_size + if vllm.api_server_count < vllm.data_parallel_size and not vllm.enable_lora: + vllm.api_server_count = vllm.data_parallel_size + + host = self.inference.server.host or "localhost" + client = self.eval.client + if "base_url" not in client.model_fields_set: + client.base_url = f"http://{host}:{self.inference.server.port}/v1" + elif urlparse(client.base_url).port != self.inference.server.port: + raise ValueError( + f"eval.client.base_url port ({urlparse(client.base_url).port}) does not match " + f"inference.server.port ({self.inference.server.port})." + ) + if self.inference.router is not None and "admin_base_url" not in client.model_fields_set: + # Admin ops (pause/update_weights/resume) must bypass the router and hit + # the engine directly. + client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"] + return self + + ### Auto-setup and validate shared configs + + @model_validator(mode="after") + def auto_setup_slurm_template(self): + if self.slurm is not None and self.slurm.job_name is None: + self.slurm.job_name = self.run.name + if self.slurm is not None and self.slurm.template_path is None: + templates_dir = find_package_resource("templates") + if templates_dir is not None: + if self.deployment.type == "single_node": + self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2" + else: + self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2" + return self + + @model_validator(mode="after") + def validate_components(self): + """Build every component config, so a config that resolves can always launch.""" + self.components() + return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/eval.py b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/eval.py new file mode 100644 index 00000000000..a6123d39441 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/eval.py @@ -0,0 +1,112 @@ +import uuid +from pathlib import Path +from typing import Literal + +import verifiers.v1 as vf +from pydantic import AliasChoices, Field, model_validator + +from prime_rl.configs.base import BaseConfig, ComponentConfig, EntrypointConfig, Placement +from prime_rl.configs.blocks.client import ClientConfig +from prime_rl.configs.blocks.log import PeriodicLogConfig +from prime_rl.configs.blocks.monitors import MonitorsConfig +from prime_rl.configs.blocks.run import RunConfig +from prime_rl.configs.components.env_worker_pool import env_worker_pool_config, env_worker_pool_key +from prime_rl.configs.components.online_eval import ServedEvalConfig +from prime_rl.configs.components.orchestrator import ConcurrencyConfig +from prime_rl.utils.config import default_output_dir + + +class EvalResumeConfig(BaseConfig): + """Resume an interrupted eval run.""" + + skip_checks: bool = False + """Reuse saved episodes even when resolved configs differ or snapshots are missing.""" + + +class EvalConfig(ServedEvalConfig, EntrypointConfig): + """``uv run eval``: evaluate the configured sources once against a live inference + pool, then exit. Every source's env worker pool is spawned by the eval process unless + the source sets ``serve.address``. Defaults to Prime Inference (``PRIME_API_KEY`` or + ``prime login``) with the concurrency pinned at 128.""" + + mode: Literal["eval"] | None = None + """Run kind of this config. ``uv run launch`` picks the entrypoint from it; ``uv run eval`` accepts only + "eval" (or no mode).""" + + model: str = Field("deepseek/deepseek-v4.1-flash-1017", validation_alias=AliasChoices("model", "m")) + """Model id — the ``model`` field of every eval request and the startup model check.""" + + client: ClientConfig = Field(default_factory=ClientConfig) + """Client of the inference server. Defaults to Prime Inference.""" + + select: vf.SelectCLIConfig = vf.SelectCLIConfig() + """Task selection that every source inherits (``-n`` sets ``limit``, ``-s`` sets + ``shuffle``). Each field a source sets on its own ``select`` wins over this one.""" + + concurrency: ConcurrencyConfig = ConcurrencyConfig(min_inflight=128, max_inflight=128) + """In-flight episodes, pinned at 128 (``-c N`` repins). External APIs expose no vLLM + ``/metrics`` to adapt to; against a vLLM server set ``min_inflight < max_inflight`` to + let the band adapt to the engines' load like the orchestrator's.""" + + group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "r")) + """Default rollouts per example. Can be overridden per env.""" + + run: RunConfig = Field(default_factory=RunConfig) + """Run metadata. ``run.name`` names the run directory under ``output_dir``.""" + + output_dir: Path = Field(default_factory=default_output_dir) + """Directory that groups related runs. Each run writes its artifacts (traces, logs, + checkpoints) to ``output_dir / run.name``. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" + + clean: bool = False + """Delete the run directory (``output_dir / run.name``) before starting. Required to + overwrite a run directory that contains artifacts from a previous run when not resuming.""" + + dry_run: bool = False + """Resolve and write the config, then exit without evaluating.""" + + dashboard: bool = True + """Start (or reuse) the local dashboard daemon and print its URL.""" + + resume: EvalResumeConfig | None = None + """Continue the interrupted run named by ``run.name`` from its trace stream: the + landed episodes rejoin the epoch and only the rollouts still owed run.""" + + log: PeriodicLogConfig = PeriodicLogConfig() + """Logging of the eval process, including its periodic pipeline log.""" + + monitors: MonitorsConfig = MonitorsConfig() + """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).""" + + @property + def run_dir(self) -> Path: + assert self.run.dir is not None # resolved at construction + return self.output_dir / self.run.dir + + @model_validator(mode="after") + def auto_setup_run_identity(self): + """Auto-generate the run name (``----``) when unset and + default the run directory, W&B run name and platform evaluation name to it.""" + if self.run.name is None: + envs = "+".join(dict.fromkeys(source.resolved_name for source in self.source)) + model = self.model.split("/")[-1] + self.run.name = f"{envs}--{model}--{uuid.uuid4().hex[:8]}".lower() + if self.run.dir is None: + self.run.dir = self.run.name + if self.monitors.wandb is not None and self.monitors.wandb.name is None: + self.monitors.wandb.name = self.run.name + if self.monitors.prime is not None and self.monitors.prime.name is None: + self.monitors.prime.name = self.run.name + return self + + def components(self) -> dict[str, ComponentConfig]: + """The env worker pool of every source without ``serve.address``, keyed ``envs/eval/``. The + eval itself runs in the entrypoint process.""" + return { + env_worker_pool_key("eval", source.resolved_name): env_worker_pool_config(source, self.log, self.run_dir) + for source in self.source + if source.serve.address is None + } + + def placement(self) -> dict[str, Placement]: + return {name: Placement() for name in self.components()} diff --git a/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/inference.py b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/inference.py new file mode 100644 index 00000000000..bd0fb2aa4b9 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/inference.py @@ -0,0 +1,283 @@ +from pathlib import Path +from typing import Any, Literal, TypeAlias + +from pydantic import Field, model_validator + +from prime_rl.configs.base import EntrypointConfig, Placement, build_component_config +from prime_rl.configs.blocks.slurm import SlurmConfig +from prime_rl.configs.components.engine import EngineConfig, EngineSection, EngineWeightBroadcastConfig +from prime_rl.configs.components.engine.deployment import ( + DisaggregatedInferenceDeploymentConfig, + InferenceDeploymentConfig, + PDKVTransferConfig, + SingleNodeInferenceDeploymentConfig, + prefill_uses_deepep_high_throughput, +) +from prime_rl.configs.components.engine.kv_cache import KVCacheOffloadConfig +from prime_rl.configs.components.router import RouterBackendConfig, RouterConfig, VllmRouterConfig +from prime_rl.utils.config import default_output_dir, find_package_resource + +PDRole: TypeAlias = Literal["prefill", "decode"] + + +class ServingSection(EngineSection): + """One engine behind a router on one node: the ``[inference]`` block of ``sft``.""" + + router: RouterBackendConfig | None = Field(default_factory=VllmRouterConfig) + """Router fronting the engine(s). Every deployment runs a single global router as the client-facing endpoint on ``server.port``, with the engines listening on ``backend_port``. Set to ``None`` to run a bare engine on ``server.port`` without a router (the SLURM launchers do this for per-rank engine processes; the sbatch script starts the router).""" + + backend_port: int | None = None + """Port for the vLLM engine(s) behind the router. None uses ``server.port + 100``. Multi-node deployments start one engine per local DP rank at ``backend_port + rank``.""" + + @model_validator(mode="after") + def validate_llmd_no_routed_experts(self): + """Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node).""" + if self.router is not None and self.router.type == "llm-d" and self.vllm.enable_return_routed_experts: + raise ValueError( + "The llm-d router backend does not support routed-expert return " + "(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. " + "Use router type 'vllm-router' for routed-expert runs." + ) + return self + + @model_validator(mode="after") + def auto_setup_backend_port(self): + if self.backend_port is None: + self.backend_port = self.server.port + 100 + return self + + def engine_config(self, weight_broadcast: str = "filesystem", **wired: Any) -> EngineConfig: + """The engine process's config. Behind a router, the engine listens on ``backend_port``.""" + config = build_component_config(EngineConfig, self, weight_broadcast={"type": weight_broadcast}, **wired) + if self.router is not None: + config.server.port = self.backend_port + return config + + def router_config(self, local: bool = True) -> RouterConfig | None: + """The router process's config, or None without a vllm-router. A ``local`` router fronts the one engine + on its host. A router for engines on other nodes binds every interface, and its launcher passes the + engine URLs on the command line once it knows the hosts.""" + if not isinstance(self.router, VllmRouterConfig): + return None + host = (self.server.host or "0.0.0.0") if local else "0.0.0.0" + worker_host = "localhost" if host == "0.0.0.0" else host + return RouterConfig( + router=self.router, + host=host, + port=self.server.port, + worker_urls=[f"http://{worker_host}:{self.backend_port}"] if local else [], + intra_node_data_parallel_size=(self.vllm.data_parallel_size_local or self.vllm.data_parallel_size) + if local + else 1, + prometheus_port=self.server.port + 21000, + ) + + +class InferenceSection(ServingSection): + """The ``[inference]`` block of ``rl``: a served model and its deployment.""" + + deployment: InferenceDeploymentConfig = SingleNodeInferenceDeploymentConfig() + """Deployment of the engines: one node, several nodes, or disaggregated prefill and decode.""" + + @model_validator(mode="after") + def validate_bidirectional_kv_transfer(self): + """Bidirectional transfer needs a router that tracks each session's decode blocks, and decode blocks in the + regular paged layout (HiSparse keeps decode's sparse-MLA KV in a host pool that prefill cannot read).""" + if self.deployment.type != "disaggregated" or self.deployment.bidirectional_kv_transfer is None: + return self + if self.router is None or self.router.type != "vllm-router": + raise ValueError("deployment.bidirectional_kv_transfer requires the vllm-router router.") + if self.hisparse is not None: + raise ValueError("deployment.bidirectional_kv_transfer does not support HiSparse decode instances.") + if self.deployment.bidirectional_kv_transfer.spill_to_store is not None: + offloads = self.kv_cache_offload_by_role + if any(offloads[role] is None or offloads[role].type != "mooncake" for role in ("prefill", "decode")): + raise ValueError( + "bidirectional_kv_transfer.spill_to_store needs a Mooncake kv_cache_offload on prefill and " + "decode: it provides the store that expiring turns are written to." + ) + return self + + @model_validator(mode="after") + def validate_router_deployment(self): + """The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines.""" + if self.router is not None and self.router.type == "llm-d" and self.deployment.type == "single_node": + raise ValueError("The llm-d router backend requires a multi-node or disaggregated SLURM deployment.") + if self.router is None and self.deployment.type in ("multi_node", "disaggregated"): + raise ValueError("Multi-node / disaggregated deployments require a router fronting the per-rank engines.") + return self + + @model_validator(mode="after") + def auto_setup_disaggregated(self): + """Auto-configure inference for disaggregated P/D: enable EP and compute DP.""" + if self.deployment.type == "disaggregated": + if "enable_expert_parallel" not in self.vllm.model_fields_set: + self.vllm.enable_expert_parallel = True + if "enable_eplb" not in self.vllm.model_fields_set: + self.vllm.enable_eplb = False + gpus_per_node = self.deployment.gpus_per_node + tp = self.vllm.tensor_parallel_size + dp_per_node = gpus_per_node // tp + if self.vllm.data_parallel_size_local is None: + self.vllm.data_parallel_size_local = dp_per_node + if self.vllm.data_parallel_size == 1: + self.vllm.data_parallel_size = dp_per_node + if self.vllm.api_server_count == 1: + self.vllm.api_server_count = dp_per_node + return self + + @property + def kv_cache_offload_by_role(self) -> dict[str, KVCacheOffloadConfig | None]: + """KV cache offload per P/D role (``prefill``/``decode``), or ``all`` for other deployments.""" + if self.deployment.type != "disaggregated": + return {"all": self.kv_cache_offload} + overrides = { + "prefill": self.deployment.prefill_kv_cache_offload, + "decode": self.deployment.decode_kv_cache_offload, + } + return {role: self.kv_cache_offload if offload == "inherit" else offload for role, offload in overrides.items()} + + @property + def vllm_overrides(self) -> list[dict[str, Any]]: + overrides = super().vllm_overrides + if isinstance(self.deployment, DisaggregatedInferenceDeploymentConfig): + overrides += [self.deployment.prefill_vllm_overrides, self.deployment.decode_vllm_overrides] + return overrides + + def engine_config(self, weight_broadcast: str = "filesystem", role: PDRole | None = None) -> EngineConfig: + """The engine process's config. A disaggregated deployment runs one engine config per ``role``.""" + if not isinstance(self.deployment, DisaggregatedInferenceDeploymentConfig): + if role is not None: + raise ValueError(f"Only a disaggregated deployment has a {role} engine.") + return super().engine_config(weight_broadcast) + if role is None: + raise ValueError("A disaggregated deployment runs a prefill and a decode engine: pass the role.") + deployment = self.deployment + config = super().engine_config( + weight_broadcast, + kv_cache_offload=self.kv_cache_offload_by_role[role], + hisparse=self.hisparse if role == "decode" else None, + ) + config.pd_kv_transfer = PDKVTransferConfig(bidirectional=deployment.bidirectional_kv_transfer) + role_nodes = deployment.prefill_nodes_per_replica if role == "prefill" else deployment.decode_nodes_per_replica + dp_local = config.vllm.data_parallel_size_local or config.vllm.data_parallel_size + config.vllm.data_parallel_size = role_nodes * dp_local + config.vllm.data_parallel_size_local = dp_local + if not config.vllm.enable_lora: + config.vllm.api_server_count = dp_local + if role == "prefill": + config.server.port = deployment.prefill_port + if ( + deployment.bidirectional_kv_transfer is not None + and "kv_load_failure_policy" not in self.model_fields_set + ): + config.kv_load_failure_policy = "recompute" + role_vllm: dict[str, Any] = {"all2all_backend": "deepep_high_throughput"} + role_vllm.update(deployment.prefill_vllm_overrides) + role_env: dict[str, str] = {} + if prefill_uses_deepep_high_throughput(deployment.prefill_vllm_overrides): + role_env["VLLM_USE_BREAKABLE_CUDAGRAPH"] = "0" + role_env.update(deployment.prefill_env_vars) + else: + config.server.port = deployment.decode_port + role_vllm = { + "all2all_backend": "deepep_low_latency", + "compilation_config": {"cudagraph_mode": "FULL_DECODE_ONLY"}, + } + role_vllm.update(deployment.decode_vllm_overrides) + role_env = dict(deployment.decode_env_vars) + for key, value in role_vllm.items(): + setattr(config.vllm, key.replace("-", "_"), value) + config.env_vars = {**config.env_vars, **role_env} + return config + + def engine_configs(self, weight_broadcast: str = "filesystem") -> dict[str, EngineConfig]: + """The engine component configs: ``engine``, or ``engine-prefill`` and ``engine-decode``.""" + if isinstance(self.deployment, DisaggregatedInferenceDeploymentConfig): + return {f"engine-{role}": self.engine_config(weight_broadcast, role) for role in ("prefill", "decode")} + return {"engine": self.engine_config(weight_broadcast)} + + def engine_placement(self, replicas: int, nodes: int, gpus_per_node: int) -> dict[str, Placement]: + """Where the engines of ``engine_configs`` run: ``replicas`` copies of a deployment on ``nodes`` nodes. + Disaggregated roles take their node counts from ``deployment``.""" + deployment = self.deployment + if isinstance(deployment, DisaggregatedInferenceDeploymentConfig): + return { + "engine-prefill": Placement( + replicas=replicas * deployment.num_prefill_replicas, + nodes=deployment.prefill_nodes_per_replica, + gpus_per_node=gpus_per_node, + ), + "engine-decode": Placement( + replicas=replicas * deployment.num_decode_replicas, + nodes=deployment.decode_nodes_per_replica, + gpus_per_node=gpus_per_node, + ), + } + return {"engine": Placement(replicas=replicas, nodes=nodes, gpus_per_node=gpus_per_node)} + + def router_config(self, local: bool | None = None) -> RouterConfig | None: + """The router process's config. The router is ``local`` to a single-node deployment.""" + config = super().router_config(self.deployment.type == "single_node" if local is None else local) + deployment = self.deployment + if config is not None and isinstance(deployment, DisaggregatedInferenceDeploymentConfig): + if deployment.bidirectional_kv_transfer is not None: + config.pd_bidirectional_ttl_s = deployment.bidirectional_kv_transfer.effective_router_ttl_s + return config + + +class InferenceConfig(InferenceSection, EntrypointConfig): + """Serve a model: a router fronting one engine locally, or a multi-node or P/D deployment on SLURM.""" + + weight_broadcast: EngineWeightBroadcastConfig = EngineWeightBroadcastConfig() + """Weight transport the engines accept updates over.""" + + slurm: SlurmConfig | None = None + """SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally.""" + + output_dir: Path = Field(default_factory=default_output_dir) + """Directory for SLURM logs and generated scripts. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" + + dry_run: bool = False + """Only validate and dump resolved configs, then exit early.""" + + @model_validator(mode="after") + def validate_multi_node_requires_slurm(self): + if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None: + raise ValueError("Must use SLURM for multi-node / disaggregated deployment.") + return self + + @model_validator(mode="after") + def auto_setup_slurm_template(self): + if self.slurm is not None and self.slurm.job_name is None: + self.slurm.job_name = "inference" + if self.slurm is not None and self.slurm.template_path is None: + templates_dir = find_package_resource("templates") + if templates_dir is not None: + self.slurm.template_path = templates_dir / "inference.sbatch.j2" + return self + + @model_validator(mode="after") + def validate_components(self): + """Build every component config, so a config that resolves can always launch.""" + self.components() + return self + + def components(self) -> dict[str, Any]: + components: dict[str, Any] = dict(self.engine_configs(self.weight_broadcast.type)) + router = self.router_config() + if router is not None: + components["router"] = router + return components + + def placement(self) -> dict[str, Placement]: + deployment = self.deployment + if deployment.type == "single_node": + vllm = self.vllm + gpus = vllm.tensor_parallel_size * vllm.data_parallel_size * getattr(vllm, "pipeline_parallel_size", 1) + placement = self.engine_placement(1, 1, gpus) + else: + placement = self.engine_placement(1, getattr(deployment, "num_nodes", 1), deployment.gpus_per_node) + if self.router_config() is not None: + placement["router"] = Placement() + return placement diff --git a/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/pretrain.py b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/pretrain.py new file mode 100644 index 00000000000..1b9687c4aaa --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/pretrain.py @@ -0,0 +1,18 @@ +from typing import Literal + +from prime_rl.configs.base import build_component_config +from prime_rl.configs.components.trainer.pretrain import PretrainTrainerConfig, PretrainTrainerSection +from prime_rl.configs.entrypoints._supervised import SupervisedConfig + + +class PretrainConfig(PretrainTrainerSection, SupervisedConfig): + """Pretraining: next-token loss on tokenized shards, with the weights initialized from scratch by default.""" + + mode: Literal["pretrain"] | None = None + """Run kind of this config. ``uv run launch`` picks the entrypoint from it; ``uv run pretrain`` accepts only + "pretrain" (or no mode).""" + + def trainer_config(self) -> PretrainTrainerConfig: + # Inference servers on other nodes connect to the trainer's rendezvous. + host = "0.0.0.0" if self.deployment.type == "multi_node" else "localhost" + return build_component_config(PretrainTrainerConfig, self, weight_broadcast=self.weight_broadcast_config(host)) diff --git a/packages/prime-rl-configs/src/prime_rl/configs/rl.py b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/rl.py similarity index 69% rename from packages/prime-rl-configs/src/prime_rl/configs/rl.py rename to packages/prime-rl-configs/src/prime_rl/configs/entrypoints/rl.py index 1dbe98e60dc..6306f920fe9 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/rl.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/rl.py @@ -5,35 +5,49 @@ from pydantic import Field, model_validator -from prime_rl.configs.inference import InferenceConfig, setup_dummy_load -from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig -from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig -from prime_rl.configs.orchestrator import OrchestratorConfig, SpeculativeDecodingConfig, TrainSamplingConfig -from prime_rl.configs.shared import ( - BaseMultiNodeDeploymentConfig, - BaseSingleNodeDeploymentConfig, - EnvVars, +from prime_rl.configs.base import BaseConfig, ComponentConfig, EntrypointConfig, Placement, build_component_config +from prime_rl.configs.blocks.ckpt import ResumeConfig, ckpt_output_dir +from prime_rl.configs.blocks.deployment import BaseMultiNodeDeploymentConfig, BaseSingleNodeDeploymentConfig +from prime_rl.configs.blocks.model import TokenizerConfig, VLMConfig +from prime_rl.configs.blocks.monitors import MonitorsConfig +from prime_rl.configs.blocks.run import EnvVars, RunConfig +from prime_rl.configs.blocks.slurm import SlurmConfig +from prime_rl.configs.blocks.transport import ZMQTransportConfig +from prime_rl.configs.blocks.weight_broadcast import ( FileSystemWeightBroadcastConfig, - NCCLWeightBroadcastConfig, - ResumeConfig, - RunConfig, - SlurmConfig, - VLMConfig, - WeightBroadcastConfig, - ZMQTransportConfig, + NCCLWeightBroadcastSection, + WeightBroadcastSection, + weight_broadcast_config, ) -from prime_rl.configs.trainer import ( - InitConfig, - NVFP4MoEComputeConfig, - RemoteCheckpointConfig, - TokenizerConfig, - TrainerConfig, +from prime_rl.configs.components.engine import ( + EngineConfig, + reject_explicit_data_parallel_size, + set_max_lora_rank, + setup_dummy_load, ) -from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource +from prime_rl.configs.components.env_worker_pool import ( + ROLLOUT_STORE_DIR, + EnvWorkerPoolConfig, + env_worker_pool_config, + env_worker_pool_key, +) +from prime_rl.configs.components.modelexpress_server import ModelExpressServerConfig, modelexpress_server_config +from prime_rl.configs.components.orchestrator import OrchestratorConfig, OrchestratorSection, SpeculativeDecodingConfig +from prime_rl.configs.components.orchestrator.ckpt import OrchestratorCheckpointConfig +from prime_rl.configs.components.orchestrator.sampling import TrainSamplingConfig +from prime_rl.configs.components.router import RouterConfig +from prime_rl.configs.components.trainer import TrainerConfig, TrainerSection +from prime_rl.configs.components.trainer.ckpt import TrainerCheckpointConfig +from prime_rl.configs.components.trainer.model import InitConfig +from prime_rl.configs.components.trainer.moe import NVFP4MoEComputeConfig +from prime_rl.configs.entrypoints.inference import InferenceSection +from prime_rl.utils.config import default_output_dir, find_package_resource from prime_rl.utils.validation import propagate_shared_fields class SharedLogConfig(BaseConfig): + """The ``rl`` entrypoint's shared log config, propagated to trainer, orchestrator, and inference.""" + level: str | None = None """Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``).""" @@ -41,77 +55,14 @@ class SharedLogConfig(BaseConfig): """Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.). Propagated to trainer, orchestrator, and inference.""" -class SharedWandbConfig(BaseConfig): - project: str | None = "prime-rl" - """W&B project.""" - - entity: str | None = None - """W&B entity.""" - - name: str | None = None - """W&B run name. Inherits ``run.name`` when unset.""" - - group: str | None = None - """W&B group.""" - - tags: list[str] | None = None - """W&B tags attached to the run.""" - - offline: bool | None = False - """Run W&B in offline mode. Incompatible with shared mode, which is always on for the ``rl`` entrypoint.""" - - @model_validator(mode="after") - def validate_not_offline(self): - if self.offline: - raise ValueError( - "W&B shared mode is always on for the rl entrypoint and requires server " - "connectivity; monitors.wandb.offline = true is not supported. Use offline mode " - "via the sub-config wandb blocks (trainer.monitors.wandb.offline, " - "orchestrator.monitors.wandb.offline) if you really need it per-process." - ) - return self - - -class SharedMonitorsConfig(BaseConfig): - """The ``rl`` entrypoint's shared monitor configs, propagated to trainer and orchestrator.""" - - wandb: SharedWandbConfig | None = None - """Shared W&B config. Propagated to trainer and orchestrator.""" - - file: FileMonitorConfig | None = None - """Shared local JSONL metric sink. If set, enables ``/monitors/file/metrics.jsonl`` on both trainer and orchestrator.""" - - prime: PrimeMonitorConfig | None = None - """Shared Prime platform monitor. Propagated to trainer and orchestrator, which log to one Prime run.""" - - -class SharedCheckpointConfig(BaseConfig): - output_dir: Path | None = None - """Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer ``output_dir``.""" - - interval: int | None = None - """Interval at which to save checkpoints.""" - - 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.""" - - keep_interval: int | None = Field(None, ge=1) - """Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping.""" - - rollouts: bool = False - """Also checkpoint the orchestrator's finished but unshipped episodes and its running rollouts, so a resumed run continues them (``orchestrator.ckpt.rollouts``).""" - - rollouts_save_timeout: int = Field(120, ge=1) - """Seconds each running rollout gets to take its memory checkpoint at a rollout checkpoint (``orchestrator.ckpt.rollouts_save_timeout``).""" - - async_save: bool | None = None - """Write trainer checkpoints in the background (see ``trainer.ckpt.async_save``). If None, uses the trainer's default.""" - - remote: RemoteCheckpointConfig | None = None - """Mirror the trainer checkpoints to an object store (see ``trainer.ckpt.remote``).""" +class RLCheckpointConfig(TrainerCheckpointConfig, OrchestratorCheckpointConfig): + """Checkpointing of an ``rl`` run. The trainer and the orchestrator save each step to one directory with one + retention policy, and each takes the fields it reads.""" class SharedModelConfig(BaseConfig): + """The ``rl`` entrypoint's shared model config, propagated to trainer, orchestrator, and inference.""" + name: str = "Qwen/Qwen3-0.6B" """HF model name or local path.""" @@ -122,7 +73,9 @@ class SharedModelConfig(BaseConfig): """Where the trainer's weights start. Propagates to ``trainer.model.init``.""" -class SingleNodeDeploymentConfig(BaseSingleNodeDeploymentConfig): +class RLSingleNodeDeploymentConfig(BaseSingleNodeDeploymentConfig): + """Run the trainer, the orchestrator, and inference on one node.""" + @model_validator(mode="after") def validate_gpu_count(self): total = self.num_train_gpus + self.num_infer_gpus @@ -134,7 +87,9 @@ def validate_gpu_count(self): return self -class MultiNodeDeploymentConfig(BaseMultiNodeDeploymentConfig): +class RLMultiNodeDeploymentConfig(BaseMultiNodeDeploymentConfig): + """Run the trainer and inference on separate nodes as one SLURM job.""" + num_infer_nodes: int | None = Field(None, ge=0) """Inference nodes per replica. If unset, inferred from ``inference.deployment``. Set to 0 to skip inference and orchestrator (requires fake data).""" @@ -153,21 +108,26 @@ def total_infer_nodes(self) -> int: return self.infer_nodes_per_replica * self.num_infer_replicas -DeploymentConfig: TypeAlias = Annotated[ - SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type") +RLDeploymentConfig: TypeAlias = Annotated[ + RLSingleNodeDeploymentConfig | RLMultiNodeDeploymentConfig, Field(discriminator="type") ] -class RLConfig(BaseConfig): +class RLConfig(EntrypointConfig): + """Reinforcement learning: the trainer, the orchestrator, and an optional launcher-managed inference + server.""" + mode: Literal["rl"] | None = None """Run kind of this config. ``uv run launch`` picks the entrypoint from it; ``uv run rl`` accepts only "rl" (or no mode).""" - trainer: TrainerConfig + trainer: TrainerSection + """The trainer: model, optimizer, and loss.""" - orchestrator: OrchestratorConfig + orchestrator: OrchestratorSection + """The orchestrator: envs, sampling, and the rollouts it sends to the trainer.""" - inference: InferenceConfig | None = None + inference: InferenceSection | None = None """Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for manually started servers).""" @model_validator(mode="after") @@ -205,6 +165,134 @@ def run_dir(self) -> Path: assert self.run.dir is not None # resolved at construction return self.output_dir / self.run.dir + @property + def env_worker_pool_replicas(self) -> int | None: + """Multi-node runs start one replica of each env worker pool per inference node.""" + if self.deployment.type == "multi_node" and self.deployment.total_infer_nodes > 0: + return self.deployment.total_infer_nodes + return None + + @property + def inference_world_size(self) -> int: + """Inference GPUs across all engines. Each one is a worker of the in-memory weight transfer.""" + if self.deployment.type == "multi_node": + # The launchers start gpus_per_node / tp servers per node, each sharded over tp GPUs. + return self.deployment.total_infer_nodes * self.deployment.gpus_per_node + if self.inference is None: + return 1 + return self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size + + def _run_fields(self) -> dict[str, Any]: + """The run-level settings that the trainer and the orchestrator both read.""" + return { + "max_steps": self.max_steps, + "resume": self.resume, + "rollout_transport": self.rollout_transport, + "monitors": self.monitors, + } + + def trainer_config(self) -> TrainerConfig: + """The trainer process's config: ``[trainer]`` plus the fields the launcher fills.""" + # Inference servers on other nodes connect to the trainer's rendezvous. + host = "0.0.0.0" if self.deployment.type == "multi_node" else "localhost" + return build_component_config( + TrainerConfig, + self.trainer, + **self._run_fields(), + ckpt=self.ckpt and build_component_config(TrainerCheckpointConfig, self.ckpt), + output_dir=self.run_dir, + weight_broadcast=weight_broadcast_config(self.weight_broadcast, self.inference_world_size, host), + ) + + def orchestrator_config(self) -> OrchestratorConfig: + """The orchestrator process's config: ``[orchestrator]`` plus the fields the launcher fills.""" + return build_component_config( + OrchestratorConfig, + self.orchestrator, + **self._run_fields(), + ckpt=self.ckpt and build_component_config(OrchestratorCheckpointConfig, self.ckpt), + output_dir=self.run_dir, + weight_broadcast=weight_broadcast_config(self.weight_broadcast, self.inference_world_size), + env_worker_pool_replicas=self.env_worker_pool_replicas, + ) + + def engine_configs(self) -> dict[str, EngineConfig]: + """The engine process configs, keyed like ``components()``: ``[inference]`` plus the weight transport.""" + if self.inference is None: + return {} + engines = self.inference.engine_configs(self.weight_broadcast.type) + for engine in engines.values(): + # The launcher gives every engine the run's admin token, so none may serve its admin routes open. + engine.server.require_admin_token = True + return engines + + def router_config(self) -> RouterConfig | None: + """The router process's config. A multi-node launcher passes the engine URLs at start.""" + if self.inference is None: + return None + return self.inference.router_config(local=self.deployment.type == "single_node") + + def env_worker_pool_configs(self) -> dict[str, EnvWorkerPoolConfig]: + """The config of every env worker pool the run starts, keyed ``envs//``.""" + retain = self.rollout_transport.retain + save_dir = ckpt_output_dir(self.run_dir, self.ckpt) + return { + env_worker_pool_key(split, source.resolved_name): env_worker_pool_config( + source, + self.orchestrator.log, + save_dir, + store_dir=ROLLOUT_STORE_DIR if retain and split == "train" else None, + ) + for split, source in self.orchestrator.managed_env_sources + } + + def modelexpress_server_config(self) -> ModelExpressServerConfig | None: + """The config of the ModelExpress server that the run starts, or None if it starts none.""" + if self.slurm is not None and not self.slurm.launch_modelexpress: + return None + return modelexpress_server_config(self.weight_broadcast, self.run_dir / "logs") + + def components(self) -> dict[str, ComponentConfig]: + components: dict[str, ComponentConfig] = {"trainer": self.trainer_config()} + modelexpress = self.modelexpress_server_config() + if modelexpress is not None: + components["modelexpress-server"] = modelexpress + if self.deployment.type == "multi_node" and self.deployment.infer_nodes_per_replica == 0: + return components + components["orchestrator"] = self.orchestrator_config() + components.update(self.engine_configs()) + router = self.router_config() + if router is not None: + components["router"] = router + components.update(self.env_worker_pool_configs()) + return components + + def placement(self) -> dict[str, Placement]: + deployment = self.deployment + if deployment.type == "single_node": + placement = {"trainer": Placement(gpus_per_node=deployment.num_train_gpus)} + else: + placement = {"trainer": Placement(nodes=deployment.num_train_nodes, gpus_per_node=deployment.gpus_per_node)} + if self.modelexpress_server_config() is not None: + placement["modelexpress-server"] = Placement() + if deployment.type == "multi_node" and deployment.infer_nodes_per_replica == 0: + return placement + if self.inference is None: + engines = {} + elif deployment.type == "single_node": + engines = self.inference.engine_placement(1, 1, deployment.num_infer_gpus) + else: + engines = self.inference.engine_placement( + deployment.num_infer_replicas, deployment.infer_nodes_per_replica, deployment.gpus_per_node + ) + placement["orchestrator"] = Placement() + placement.update(engines) + if self.router_config() is not None: + placement["router"] = Placement() + for name in self.env_worker_pool_configs(): + placement[name] = Placement(replicas=self.env_worker_pool_replicas or 1) + return placement + def _resolve_run_name(self) -> None: """Fill the auto-generated run name and directory (idempotent — called by every validator that reads them, so it does not depend on validator ordering).""" @@ -218,16 +306,16 @@ def _resolve_run_name(self) -> None: ### Shared configurations log: SharedLogConfig = SharedLogConfig() - """Shared log config. Propagated to trainer and orchestrator.""" + """Shared log config. Propagated to trainer, orchestrator, and inference.""" - ckpt: SharedCheckpointConfig | None = None - """Shared checkpoint config. If None, falls back to the sub-config checkpoint settings.""" + ckpt: RLCheckpointConfig | None = None + """Checkpointing of the trainer and the orchestrator. If None, the run saves no checkpoints.""" resume: ResumeConfig | None = None """Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. If None, does not resume.""" - monitors: SharedMonitorsConfig = SharedMonitorsConfig() - """Shared monitor configs (``monitors.wandb``, ``monitors.file``, ``monitors.prime``). Propagated to trainer and orchestrator.""" + monitors: MonitorsConfig = MonitorsConfig() + """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``). The trainer and the orchestrator log to one run per monitor.""" model: SharedModelConfig | None = None """Shared model config. If None, falls back to the sub-config model settings.""" @@ -236,16 +324,20 @@ def _resolve_run_name(self) -> None: """Shared tokenizer config. Propagated to trainer, orchestrator, and inference. If None, each component uses its own tokenizer config (defaulting to model name).""" max_steps: int | None = None - """Shared maximum training steps. If None, falls back to the sub-config ``max_steps``.""" + """Maximum training steps of the trainer and the orchestrator. If None, the run does not stop on its own.""" seq_len: int | None = None - """Shared sequence length. Propagates to ``trainer.model.seq_len`` and ``orchestrator.seq_len`` only when those values were not explicitly set; explicit per-component values always win.""" + """Shared sequence length. Propagates to ``trainer.model.seq_len`` and ``orchestrator.seq_len``; a component value that differs is an error. Leave it unset to set the two separately.""" - weight_broadcast: WeightBroadcastConfig | None = None + weight_broadcast: WeightBroadcastSection | None = None + """How the trainer sends weights to inference. Copied to the trainer, the orchestrator, and inference. If None, + uses NCCL with launcher-managed inference, else the filesystem.""" - rollout_transport: ZMQTransportConfig | None = None + rollout_transport: ZMQTransportConfig = ZMQTransportConfig() + """How the orchestrator sends rollouts to the trainer.""" - deployment: DeploymentConfig = SingleNodeDeploymentConfig() + deployment: RLDeploymentConfig = RLSingleNodeDeploymentConfig() + """GPU and node placement of the trainer and inference.""" slurm: SlurmConfig | None = None """SLURM configuration. If None, runs locally.""" @@ -318,42 +410,31 @@ def auto_setup_shared_configs(cls, data: Any) -> Any: return propagate_shared_fields(data) @model_validator(mode="after") - def auto_setup_run_dir(self): - """Point trainer and orchestrator at the run directory (``output_dir / run.name``). - - The sub-configs' ``output_dir`` is fully derived here: sub-processes spawned by - the launcher receive the resolved run directory and never re-derive it. - """ + def auto_setup_run_name(self): self._resolve_run_name() - run_dir = self.run_dir - for sub in (self.trainer, self.orchestrator): - if "output_dir" in sub.model_fields_set and sub.output_dir != run_dir: - raise ValueError( - f"{type(sub).__name__}.output_dir ({sub.output_dir}) conflicts with the run directory " - f"({run_dir}). Under the rl entrypoint, sub-config output directories are derived from " - "output_dir / run.name — set those instead." - ) - self.trainer.output_dir = run_dir - self.orchestrator = self.orchestrator.model_copy(update={"output_dir": run_dir}) + return self + + @model_validator(mode="after") + def validate_wandb_online(self): + """The trainer and the orchestrator log to one shared W&B run, which needs the W&B server.""" + if self.monitors.wandb is not None and self.monitors.wandb.offline: + raise ValueError("rl logs to one shared W&B run, which cannot run offline: unset monitors.wandb.offline.") return self @model_validator(mode="after") def auto_setup_run_identity(self): """Default the W&B and Prime platform run names to ``run.name``. - Explicit names always win: only unset names inherit. Runs after the - orchestrator's own ``auto_setup_prime_monitor_name``, so an explicitly - set W&B name still takes precedence for the platform run name. The run - identity itself is runtime-only ($PRL_RUN_ID / $PRL_RUN_NAME, set by the - ``rl`` entrypoint), never sub-config. + Explicit names always win: only unset names inherit, and an explicit W&B + name also names the platform run. The run identity itself is runtime-only + ($PRL_RUN_ID / $PRL_RUN_NAME, set by the ``rl`` entrypoint), never sub-config. """ self._resolve_run_name() - for wandb in (self.monitors.wandb, self.trainer.monitors.wandb, self.orchestrator.monitors.wandb): - if wandb is not None and wandb.name is None: - wandb.name = self.run.name - for prime in (self.monitors.prime, self.trainer.monitors.prime, self.orchestrator.monitors.prime): - if prime is not None and prime.name is None: - prime.name = self.run.name + wandb, prime = self.monitors.wandb, self.monitors.prime + if prime is not None and prime.name is None: + prime.name = (wandb.name if wandb is not None else None) or self.run.name + if wandb is not None and wandb.name is None: + wandb.name = self.run.name return self ### Validate shared configs (after sub-config construction) @@ -369,18 +450,6 @@ def require_equal(name: str, values: dict[str, Any]) -> None: found = ", ".join(f"{path}={value!r}" for path, value in values.items()) raise ValueError(f"{name} must match across components ({found}). Set the shared [{name}] instead.") - # The orchestrator queries the inference server it is paired with; without one, it - # must match the trainer whose weights the external server receives. - # The components log to one run per monitor, so a monitor is on in all or none. - for name in ("wandb", "file", "prime"): - require_equal( - f"monitors.{name}", - { - f"{component}.monitors.{name}": getattr(config.monitors, name) is not None - for component, config in (("trainer", trainer), ("orchestrator", orchestrator)) - }, - ) - if inference is not None: require_equal( "deployment.gpus_per_node", @@ -389,6 +458,8 @@ def require_equal(name: str, values: dict[str, Any]) -> None: "inference.deployment.gpus_per_node": inference.deployment.gpus_per_node, }, ) + # The orchestrator queries the inference server it is paired with; without one, it + # must match the trainer whose weights the external server receives. require_equal( "model.name", {"inference.vllm.model": inference.vllm.model, "orchestrator.model.name": orchestrator.model.name}, @@ -406,43 +477,11 @@ def require_equal(name: str, values: dict[str, Any]) -> None: if inference is not None: chat_templates["inference.vllm.chat_template"] = inference.vllm.chat_template require_equal("tokenizer.chat_template", chat_templates) - require_equal( - "max_steps", {"trainer.max_steps": trainer.max_steps, "orchestrator.max_steps": orchestrator.max_steps} - ) - require_equal("resume", {"trainer.resume": trainer.resume, "orchestrator.resume": orchestrator.resume}) if trainer.model.seq_len < orchestrator.seq_len: raise ValueError( f"trainer.model.seq_len ({trainer.model.seq_len}) must be >= orchestrator.seq_len " f"({orchestrator.seq_len}) so the trainer can handle every sequence the orchestrator produces." ) - if (trainer.ckpt is None) != (orchestrator.ckpt is None): - raise ValueError( - "Checkpointing must be configured on both trainer and orchestrator. Use the shared [ckpt]." - ) - if trainer.ckpt and orchestrator.ckpt: - # Both halves of a step share one directory and one retention policy. - for leaf in ("output_dir", "interval", "keep_last", "keep_interval"): - require_equal( - f"ckpt.{leaf}", - { - f"trainer.ckpt.{leaf}": getattr(trainer.ckpt, leaf), - f"orchestrator.ckpt.{leaf}": getattr(orchestrator.ckpt, leaf), - }, - ) - trainer_wandb, orchestrator_wandb = trainer.monitors.wandb, orchestrator.monitors.wandb - if (trainer_wandb is None) != (orchestrator_wandb is None): - raise ValueError( - "W&B must be configured on both trainer and orchestrator, otherwise only one side's " - "metrics are logged. Use the shared [monitors.wandb]." - ) - if trainer_wandb and orchestrator_wandb: - require_equal( - "monitors.wandb.project", - { - "trainer.monitors.wandb.project": trainer_wandb.project, - "orchestrator.monitors.wandb.project": orchestrator_wandb.project, - }, - ) return self @model_validator(mode="after") @@ -462,12 +501,12 @@ def auto_setup_weight_broadcast(self): inference server is configured, or with ``rollout_transport.retain`` (a restarted trainer cannot rejoin an in-memory transfer group). """ - retain = self.trainer.rollout_transport.retain + retain = self.rollout_transport.retain if self.weight_broadcast is None: if self.trainer.model.lora is not None or self.inference is None or retain: self.weight_broadcast = FileSystemWeightBroadcastConfig() else: - self.weight_broadcast = NCCLWeightBroadcastConfig() + self.weight_broadcast = NCCLWeightBroadcastSection() if self.weight_broadcast.type != "filesystem" and self.trainer.model.lora is not None: raise ValueError( "LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a " @@ -480,22 +519,6 @@ def auto_setup_weight_broadcast(self): f"'{self.weight_broadcast.type}': a restarted trainer cannot rejoin its transfer group. " "Use weight_broadcast.type = 'filesystem'." ) - # host and inference_world_size are filled in per deployment after this copy. - launcher_set = {"host", "inference_world_size"} - for name, sub in (("trainer", self.trainer), ("orchestrator", self.orchestrator)): - if "weight_broadcast" in sub.model_fields_set and sub.weight_broadcast.model_dump( - exclude=launcher_set - ) != self.weight_broadcast.model_dump(exclude=launcher_set): - raise ValueError( - f"{name}.weight_broadcast conflicts with the shared weight_broadcast. Under the rl " - "entrypoint it is copied from [weight_broadcast]; set that instead." - ) - self.trainer.weight_broadcast = self.weight_broadcast.model_copy() - self.orchestrator = self.orchestrator.model_copy( - update={"weight_broadcast": self.weight_broadcast.model_copy()} - ) - if self.inference is not None: - self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type) return self @model_validator(mode="after") @@ -508,26 +531,6 @@ def validate_enough_devices_for_nccl(self): ) return self - @model_validator(mode="after") - def auto_setup_rollout_transport(self): - """Resolve the shared ``rollout_transport`` from the sub-configs so the launcher can - read ``retain`` from it (mirrors ``auto_setup_weight_broadcast``). - - ``rollout_transport`` may be set either as the shared block (propagated down to both - sub-configs by ``propagate_shared_fields``) or directly on - ``trainer.rollout_transport`` / ``orchestrator.rollout_transport`` (the documented - fallback). Either way the shared field must reflect the resolved per-component - transport. - """ - if self.trainer.rollout_transport.retain != self.orchestrator.rollout_transport.retain: - raise ValueError( - "trainer.rollout_transport.retain != orchestrator.rollout_transport.retain; set the " - "shared [rollout_transport] instead." - ) - if self.rollout_transport is None: - self.rollout_transport = self.trainer.rollout_transport - return self - @model_validator(mode="after") def validate_eplb(self): if self.inference is not None and self.inference.vllm.enable_eplb: @@ -539,7 +542,7 @@ def auto_setup_lora(self): if self.trainer.model.lora is not None: if self.inference is not None: self.inference.vllm.enable_lora = True - self.inference.vllm.max_lora_rank = self.trainer.model.lora.rank + set_max_lora_rank(self.inference.vllm, self.trainer.model.lora.rank) else: warnings.warn( "LoRA is enabled, but inference is not configured. When manually starting the inference server, " @@ -616,7 +619,7 @@ def validate_llmd_no_routed_experts(self): Runs after ``auto_setup_router_replay`` so it also catches the ``trainer.enable_router_replay`` path, which sets the inference flag here - (after InferenceConfig's own validators, which therefore miss it). + (after InferenceSection's own validators, which therefore miss it). """ if self.inference is not None and self.inference.vllm.enable_return_routed_experts: router = self.inference.router @@ -710,12 +713,12 @@ def validate_mooncake_offload_requires_slurm(self): @model_validator(mode="after") def auto_setup_deployment(self): - env_worker_pool_replicas = self.orchestrator.env_worker_pool_replicas if self.deployment.type == "single_node": # single-node # fill up inference capacity with dp ranks if self.inference is not None: num_infer_gpus = self.deployment.num_infer_gpus if num_infer_gpus != self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size: + reject_explicit_data_parallel_size(self.inference.vllm, num_infer_gpus) assert num_infer_gpus % self.inference.vllm.tensor_parallel_size == 0, ( "Number of inference GPUs must be divisible by the tensor parallel size" ) @@ -726,16 +729,8 @@ def auto_setup_deployment(self): dp = self.inference.vllm.data_parallel_size if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora: self.inference.vllm.api_server_count = dp - if self.weight_broadcast.type != "filesystem": - # Every inference GPU joins the in-memory transfer group, so size it after the DP fill. - world_size = dp * self.inference.vllm.tensor_parallel_size - self.trainer.weight_broadcast.inference_world_size = world_size - self.orchestrator.weight_broadcast.inference_world_size = world_size elif self.deployment.type == "multi_node": # multi-node - if self.deployment.total_infer_nodes > 0: - env_worker_pool_replicas = self.deployment.total_infer_nodes - if ( self.inference is not None and self.inference.vllm.enable_expert_parallel @@ -788,23 +783,6 @@ def auto_setup_deployment(self): if self.inference.vllm.api_server_count == 1 and dp_per_node > 1: self.inference.vllm.api_server_count = dp_per_node - if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "modelexpress"): - # Every allocated inference GPU is an in-memory transfer worker. - # The external-LB launcher starts dp_per_node (= gpus_per_node / tp) - # TP-sharded servers per node, i.e. gpus_per_node workers per node, so use - # the GPU count directly. Deriving it from api_server_count double-counts: - # api_server_count can resolve to the *global* DP size, making the node - # factor count twice and wait for ranks that never connect. Matches - # the disaggregated path below. - total_infer_workers = self.deployment.total_infer_nodes * self.deployment.gpus_per_node - assert self.trainer.weight_broadcast.type in ("nccl", "modelexpress") - if self.trainer.weight_broadcast.type == "nccl": - self.trainer.weight_broadcast.host = "0.0.0.0" - self.trainer.weight_broadcast.inference_world_size = total_infer_workers - assert self.orchestrator.weight_broadcast.type in ("nccl", "modelexpress") - self.orchestrator.weight_broadcast.inference_world_size = total_infer_workers - - self.orchestrator = self.orchestrator.model_copy(update={"env_worker_pool_replicas": env_worker_pool_replicas}) return self @model_validator(mode="after") @@ -823,7 +801,6 @@ def auto_setup_disaggregated_inference(self): f"disaggregated inference nodes per replica ({expected_infer_nodes})." ) - total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node if "inference_metrics_roles" not in self.orchestrator.model_fields_set: # External-LB: one admin client per DP rank, so roles expand per rank # (stride = dp_local = gpus_per_node / tp). ADMIN_URLS lists all prefill @@ -835,12 +812,6 @@ def auto_setup_disaggregated_inference(self): self.orchestrator = self.orchestrator.model_copy( update={"inference_metrics_roles": role_order * self.deployment.num_infer_replicas} ) - if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "modelexpress"): - assert self.trainer.weight_broadcast.type in ("nccl", "modelexpress") - self.trainer.weight_broadcast.inference_world_size = total_infer_gpus - assert self.orchestrator.weight_broadcast.type in ("nccl", "modelexpress") - self.orchestrator.weight_broadcast.inference_world_size = total_infer_gpus - return self @model_validator(mode="after") @@ -884,4 +855,10 @@ def auto_setup_slurm_template(self): self.slurm.template_path = templates_dir / "multi_node_rl.sbatch.j2" return self + @model_validator(mode="after") + def validate_components(self): + """Build every component config, so a config that resolves can always launch.""" + self.components() + return self + ### Warnings diff --git a/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/sft.py b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/sft.py new file mode 100644 index 00000000000..ce95e9ee705 --- /dev/null +++ b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/sft.py @@ -0,0 +1,18 @@ +from typing import Literal + +from prime_rl.configs.base import build_component_config +from prime_rl.configs.components.trainer.sft import SFTTrainerConfig, SFTTrainerSection +from prime_rl.configs.entrypoints._supervised import SupervisedConfig + + +class SFTConfig(SFTTrainerSection, SupervisedConfig): + """Supervised fine-tuning, with optional online evals against a launcher-managed inference server.""" + + mode: Literal["sft"] | None = None + """Run kind of this config. ``uv run launch`` picks the entrypoint from it; ``uv run sft`` accepts only + "sft" (or no mode).""" + + def trainer_config(self) -> SFTTrainerConfig: + # Inference servers on other nodes connect to the trainer's rendezvous. + host = "0.0.0.0" if self.deployment.type == "multi_node" else "localhost" + return build_component_config(SFTTrainerConfig, self, weight_broadcast=self.weight_broadcast_config(host)) diff --git a/packages/prime-rl-configs/src/prime_rl/configs/eval.py b/packages/prime-rl-configs/src/prime_rl/configs/eval.py deleted file mode 100644 index c29299da568..00000000000 --- a/packages/prime-rl-configs/src/prime_rl/configs/eval.py +++ /dev/null @@ -1,206 +0,0 @@ -import uuid -from pathlib import Path -from typing import Literal - -import verifiers.v1 as vf -from pydantic import AliasChoices, Field, model_validator - -from prime_rl.configs.monitors import MonitorsConfig -from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig -from prime_rl.configs.shared import ( - ClientConfig, - ControlConfig, - HeartbeatConfig, - LogConfig, - RunConfig, - VLLMClientConfig, - WeightBroadcastConfig, -) -from prime_rl.utils.config import BaseConfig, default_output_dir, resolve_client_roles - - -class ServedEvalConfig(EvalSourcesConfig): - """Eval sources run against a live inference server: the server's client and the - adaptive concurrency band.""" - - client: VLLMClientConfig = Field(default_factory=VLLMClientConfig) - """Client of the inference server evals run against.""" - - concurrency: ConcurrencyConfig = ConcurrencyConfig() - """Adaptive in-flight episode concurrency, sized by the same controller as - ``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it.""" - - inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None - """P/D role of each ``client.admin_base_url`` entry, in the same order: labels inference - metrics and lets the concurrency controller read prefill and decode engines apart.""" - - dispatch_per_minute: int | None = Field(None, ge=1) - """Rate limit on episode dispatch: at most this many episodes start per minute. Each - episode counts once, so a group of ``group_size`` episodes counts ``group_size`` - times. Use it for sandbox-backed environments to pace provisioning during - autoscaling. None disables it.""" - - control: ControlConfig | None = None - """Serve the eval's control API, which reads and sets its concurrency while it runs - (``GET``/``PUT /v1/concurrency``). If None, it takes no control requests.""" - - heartbeat: HeartbeatConfig | None = None - """BetterStack heartbeat for the run: pinged by landed episodes — the first - landed episode is the first beat, so the run's boot never shows up as a - stale-prone silence. Pings are throttled to at most one every - ``heartbeat.min_interval`` seconds. When episodes stop landing, the pings stop - and the heartbeat goes stale on Better Stack after its grace period. Size that - period + grace above the longest legitimate gap between episodes.""" - - @model_validator(mode="after") - def validate_inference_metrics_roles(self): - if self.inference_metrics_roles is not None: - admin_urls = self.client.admin_base_url or [] - try: - resolve_client_roles(len(admin_urls), self.inference_metrics_roles) - except ValueError as err: - raise ValueError( - f"inference_metrics_roles has {len(self.inference_metrics_roles)} role(s) but " - f"client.admin_base_url has {len(admin_urls)} URL(s): give one role per admin URL " - "(or one uniform block per pod under internal DP)" - ) from err - return self - - @property - def env_addresses(self) -> dict[tuple[str, str], str | None]: - """Where each eval source's env worker pool lives, keyed by ``("eval", resolved_name)``. - Same contract as ``OrchestratorConfig.env_addresses``: an explicit ``serve.address`` - is an externally managed server; None means the launcher spawns the server and the - eval learns its address from the file it publishes.""" - return {("eval", source.resolved_name): source.serve.address for source in self.source} - - -class EvalResumeConfig(BaseConfig): - skip_checks: bool = False - """Reuse saved episodes even when resolved configs differ or snapshots are missing.""" - - -class EvalConfig(ServedEvalConfig): - """``uv run eval``: evaluate the configured sources once against a live inference - pool, then exit. Every source's env worker pool is spawned by the eval process unless - the source sets ``serve.address``. Defaults to Prime Inference (``PRIME_API_KEY`` or - ``prime login``) with the concurrency pinned at 128.""" - - mode: Literal["eval"] | None = None - """Run kind of this config. ``uv run launch`` picks the entrypoint from it; ``uv run eval`` accepts only - "eval" (or no mode).""" - - model: str = Field("deepseek/deepseek-v4.1-flash-1017", validation_alias=AliasChoices("model", "m")) - """Model id — the ``model`` field of every eval request and the startup model check.""" - - client: ClientConfig = Field(default_factory=ClientConfig) - """Client of the inference server. Defaults to Prime Inference.""" - - select: vf.SelectCLIConfig = vf.SelectCLIConfig() - """Task selection that every source inherits (``-n`` sets ``limit``, ``-s`` sets - ``shuffle``). Each field a source sets on its own ``select`` wins over this one.""" - - concurrency: ConcurrencyConfig = ConcurrencyConfig(min_inflight=128, max_inflight=128) - """In-flight episodes, pinned at 128 (``-c N`` repins). External APIs expose no vLLM - ``/metrics`` to adapt to; against a vLLM server set ``min_inflight < max_inflight`` to - let the band adapt to the engines' load like the orchestrator's.""" - - group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "r")) - """Default rollouts per example. Can be overridden per env.""" - - run: RunConfig = Field(default_factory=RunConfig) - """Run metadata. ``run.name`` names the run directory under ``output_dir``.""" - - output_dir: Path = Field(default_factory=default_output_dir) - """Directory that groups related runs. Each run writes its artifacts (traces, logs, - checkpoints) to ``output_dir / run.name``. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" - - clean: bool = False - """Delete the run directory (``output_dir / run.name``) before starting. Required to - overwrite a run directory that contains artifacts from a previous run when not resuming.""" - - dry_run: bool = False - """Resolve and write the config, then exit without evaluating.""" - - dashboard: bool = True - """Start (or reuse) the local dashboard daemon and print its URL.""" - - resume: EvalResumeConfig | None = None - """Continue the interrupted run named by ``run.name`` from its trace stream: the - landed episodes rejoin the epoch and only the rollouts still owed run.""" - - log: LogConfig = LogConfig() - - monitors: MonitorsConfig = MonitorsConfig() - """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).""" - - @property - def run_dir(self) -> Path: - assert self.run.dir is not None # resolved at construction - return self.output_dir / self.run.dir - - @model_validator(mode="after") - def auto_setup_run_identity(self): - """Auto-generate the run name (``----``) when unset and - default the run directory, W&B run name and platform evaluation name to it.""" - if self.run.name is None: - envs = "+".join(dict.fromkeys(source.resolved_name for source in self.source)) - model = self.model.split("/")[-1] - self.run.name = f"{envs}--{model}--{uuid.uuid4().hex[:8]}".lower() - if self.run.dir is None: - self.run.dir = self.run.name - if self.monitors.wandb is not None and self.monitors.wandb.name is None: - self.monitors.wandb.name = self.run.name - if self.monitors.prime is not None and self.monitors.prime.name is None: - self.monitors.prime.name = self.run.name - return self - - -class SFTOnlineEvalConfig(ScheduledEvalConfig, ServedEvalConfig): - """The ``[eval]`` block of the ``sft`` entrypoint, and the config of the online-eval - process the launcher spawns from it: interval-driven eval sources against the inference - server that receives the trainer's weight broadcasts. The process watches the - broadcasts directory, moves the inference server onto each broadcast, and runs the - due sources against the updated weights. The launcher fills the run-level fields - (``model``, ``weight_broadcast``, ``broadcasts_dir``, ``max_steps``, ``resume_step``, - ``output_dir``, ``log``, ``monitors``) from the resolved SFT config.""" - - cancel_on_new_checkpoint: bool = True - """Cancel unfinished episodes when a newer trainer checkpoint is ready. Disable to - finish every triggered eval epoch before loading later weights. The trainer can idle - while it waits for slow evals.""" - - model: str | None = None - """Name the inference server serves the model under. The name stays fixed across - weight updates (weights are swapped in place), so per-step results are told apart by - ``eval/{env}/policy_version``.""" - - weight_broadcast: WeightBroadcastConfig | None = None - """Weight transport. None reloads weights from the filesystem broadcasts.""" - - broadcasts_dir: Path | None = None - """Directory to watch for ``step_{n}`` weight broadcasts. Defaults to - ``/broadcasts``.""" - - max_steps: int | None = None - """Trainer step at which the run ends. The final checkpoint always fires every eval - env, and the process exits after processing it. If None, runs until terminated.""" - - resume_step: int | None = None - """Trainer step the run resumed from. When set, the startup (base-model) eval is - skipped; set ``retrigger_on_resume`` to re-fire interval-aligned evals at this step.""" - - output_dir: Path = Field(default_factory=default_output_dir) - """The run directory, shared with the trainer. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" - - log: LogConfig = LogConfig() - - monitors: MonitorsConfig = MonitorsConfig() - """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``): the - trainer's, so the process logs to the trainer's W&B and Prime runs.""" - - @model_validator(mode="after") - def auto_setup_broadcasts_dir(self): - if self.broadcasts_dir is None: - self.broadcasts_dir = self.output_dir / "broadcasts" - return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/inference.py b/packages/prime-rl-configs/src/prime_rl/configs/inference.py deleted file mode 100644 index ad31881f6df..00000000000 --- a/packages/prime-rl-configs/src/prime_rl/configs/inference.py +++ /dev/null @@ -1,953 +0,0 @@ -import json -import os -import re -import warnings -from argparse import Namespace -from pathlib import Path -from typing import Annotated, Any, Literal, TypeAlias - -from pydantic import ConfigDict, Field, model_validator -from pydantic_config import BaseConfig - -from prime_rl.configs.shared import EnvVars, LogConfig, SlurmConfig -from prime_rl.utils.config import default_output_dir, find_package_resource -from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser - -# TODO: Set thinking/ solution budget - - -class ServerConfig(BaseConfig): - host: str | None = None - """Host to bind to.""" - - port: int = 8000 - """Port to bind to.""" - - liveness_timeout_seconds: float = Field(30.0, gt=0) - """Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. Health checks polling this endpoint should use a timeout at least this high.""" - - admin_token_var: str = "PRIME_RL_ADMIN_TOKEN" - """Name of the environment variable holding the admin token. When it, or ``_SHA256`` holding the token's SHA-256 digest, is set, the admin routes (weight updates, pause/resume, broadcaster setup, LoRA loading) reject requests whose ``X-Prime-Admin-Token`` header does not match it.""" - - require_admin_token: bool = False - """Refuse to start when neither ``admin_token_var`` nor its ``_SHA256`` digest variable is set, instead of serving the admin routes without authentication.""" - - -# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so -# tiny adapters round up to 8. Hardcoded rather than imported: prime-rl-configs does -# not depend on vLLM, and importing it costs seconds in every config-parsing process. -VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512) - -QuantizationType = Literal["fp8_per_block", "mxfp8", "online"] - - -class VllmConfig(BaseConfig): - """Arguments forwarded to the vLLM server, under vLLM's own argument names - (https://docs.vllm.ai/en/latest/configuration/engine_args.html). - - The fields below are the arguments prime-rl types, defaults, or reads back; - any other vLLM argument can be set as well (``[inference.vllm] max_num_seqs = 256`` - or ``--vllm.max-num-seqs 256``) and passes through to the server verbatim. - - Parser fields (``tool_call_parser``, ``reasoning_parser``) default to ``"auto"``, - which resolves to a concrete parser name at validation time from the tokenizer name, then the model name. - Set to ``None`` to disable. - """ - - model_config = ConfigDict(extra="allow") - - model: str = "Qwen/Qwen3-0.6B" - """HF model name or local path.""" - - max_model_len: int | None = None - """Maximum model context length. If None, uses the model config's value.""" - - chat_template: str | None = None - """Chat template — a Jinja2 template string or path to a template file. If None, uses the model's default.""" - - tool_call_parser: str | None = "auto" - """Tool-call parser. Set to ``"auto"`` (default) to detect from the tokenizer name, then the model name, or ``None`` to disable.""" - - reasoning_parser: str | None = "auto" - """Parser for extracting reasoning content from model outputs. Set to ``"auto"`` (default) to detect from the tokenizer name, then the model name, or ``None`` to disable.""" - - rope_scaling: dict[str, Any] | str | None = None - """RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``).""" - - tensor_parallel_size: int = 1 - """Tensor parallel size.""" - - data_parallel_size: int = Field(1, ge=1) - """Data parallel size.""" - - data_parallel_size_local: int | None = Field(None, ge=1) - """Data parallel replicas to run on this node.""" - - data_parallel_rpc_port: int = Field(13345, ge=1, le=65535) - """RPC port for data parallel communication.""" - - api_server_count: int = Field(1, ge=0) - """API servers to run. Set to 0 for headless mode.""" - - gpu_memory_utilization: float = 0.9 - """GPU memory utilization.""" - - enable_prefix_caching: bool | None = None - """Enable prefix caching.""" - - quantization: QuantizationType | None = None - """Online inference quantization method. If None, vLLM infers it from the checkpoint. ``"online"`` takes the - per-layer-kind schemes from ``quantization_config``, e.g. ``{linear = "mxfp8", moe = "nvfp4_per_token"}``.""" - - enable_lora: bool = False - """Enable LoRA.""" - - max_lora_rank: int | None = None - """Maximum LoRA rank. Rounded up to the nearest value vLLM accepts.""" - - lora_target_modules: list[str] | None = None - """LoRA target modules.""" - - enable_expert_parallel: bool = False - """Enable expert parallelism for MoE models.""" - - enable_eplb: bool = False - """Enable expert parallel load balancer (EPLB).""" - - enable_ep_weight_filter: bool = True - """Skip non-local expert weights at load time under expert parallelism, so each - rank reads only its own expert shard from disk. No-op for non-MoE models, when - expert parallelism is disabled, or under EPLB (redundant expert slots need all - logical expert weights).""" - - enable_return_routed_experts: bool = False - """Return routed experts in responses.""" - - @model_validator(mode="before") - @classmethod - def parse_extra_values(cls, data: dict) -> dict: - """Normalize pass-through (untyped) entries: kebab-case keys become snake_case, - and string values — which is how CLI overrides arrive — are JSON-parsed so - ``--vllm.max-num-seqs 256`` lands as an int and ``--vllm.compilation-config - '{"cudagraph_mode": "NONE"}'`` as a dict. Non-JSON strings stay strings.""" - if not isinstance(data, dict): - return data - for key in [k for k in data if k not in cls.model_fields]: - value = data.pop(key) - if isinstance(value, str): - try: - value = json.loads(value) - except json.JSONDecodeError: - pass - data[key.replace("-", "_")] = value - return data - - @model_validator(mode="after") - def auto_resolve_parsers(self): - """Resolve ``"auto"`` parser values to concrete parser names from the tokenizer name, then the model name. - - Runs after ``RLConfig.auto_setup_shared_configs`` (mode=before) has - propagated the shared ``[model] name`` and ``[tokenizer] name`` into ``inference.vllm``, so the - names are set even when only the shared blocks specify them. - """ - tokenizer = (self.model_extra or {}).get("tokenizer") - names = [name for name in (tokenizer, self.model) if name] - unresolved = [] - for field, resolve in ( - ("tool_call_parser", resolve_tool_call_parser), - ("reasoning_parser", resolve_reasoning_parser), - ): - if getattr(self, field) == "auto": - parser = next((parser for name in names if (parser := resolve(name))), None) - setattr(self, field, parser) - if parser is None: - unresolved.append(field) - if unresolved and tokenizer is None and not re.fullmatch(r"[\w.-]+/[\w.-]+", self.model): - warnings.warn( - f"No {' or '.join(unresolved)} matches the local model {self.model}: set tokenizer.name to the HF " - "model name to pick them", - stacklevel=2, - ) - return self - - @model_validator(mode="after") - def auto_setup_max_lora_rank(self): - """Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value. - - vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512). - This validator ensures that any configured rank is rounded up to the minimum valid value - that can serve adapters of the requested rank. - """ - if self.max_lora_rank is not None: - original_rank = self.max_lora_rank - for valid_rank in VALID_VLLM_LORA_RANKS: - if valid_rank >= self.max_lora_rank: - self.max_lora_rank = valid_rank - break - else: - raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}") - return self - - @model_validator(mode="after") - def auto_setup_api_server_count(self): - """ - Ensures that we have at least as many API servers as data parallel - size. Unless LoRA is enabled, in which case only one API server is - supported (vLLM limitation). - """ - if self.model_extra and self.model_extra.get("headless", False): - self.api_server_count = 0 - return self - - if "api_server_count" not in self.model_fields_set: - min_api_server_count = self.data_parallel_size_local or self.data_parallel_size - if self.api_server_count < min_api_server_count: - self.api_server_count = min_api_server_count - - if self.enable_lora: - self.api_server_count = 1 # LoRA requires only one API server - return self - - -class WeightBroadcastConfig(BaseConfig): - type: Literal["nccl", "filesystem", "modelexpress"] = "filesystem" - """Weight broadcast transport.""" - - -class CPUOffloadTier(BaseConfig): - num_bytes: int = Field(..., ge=0) - """CPU/DRAM offload capacity. For the ``native`` backend this is vLLM's aggregate ``cpu_bytes_to_use`` (scaled across workers internally; must be positive). For the ``mooncake`` backend this is the per-node store client's DRAM segment (``-global_segment_size``); 0 connects the node to the shared pool without contributing storage.""" - - -class DiskOffloadTier(BaseConfig): - path: Path - """Filesystem root for the disk tier. For ``native`` this is the ``fs`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota).""" - - -class BaseKVCacheOffloadConfig(BaseConfig): - cpu: CPUOffloadTier | None = None - """CPU/DRAM offload tier. Always required — disk-only offload is not supported.""" - - disk: DiskOffloadTier | None = None - """Optional disk tier, layered behind the CPU tier (GPU → DRAM → disk).""" - - @model_validator(mode="after") - def valid_tiers(self): - # Both backends support only two shapes: cpu-only or cpu+disk. Native disk - # tiering needs a CPU primary tier; Mooncake standalone-store needs a DRAM - # staging tier. Disk-only is rejected for both. - if self.cpu is None: - raise ValueError("inference.kv_cache_offload requires a cpu tier (disk-only offload is not supported).") - return self - - -class NativeKVCacheOffloadConfig(BaseKVCacheOffloadConfig): - type: Literal["native"] = "native" - """vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs`` disk secondary). Fully self-contained — no external processes.""" - - @model_validator(mode="after") - def positive_cpu_capacity(self): - if self.cpu is not None and self.cpu.num_bytes == 0: - raise ValueError("Native KV cache offload requires a positive cpu.num_bytes.") - return self - - def to_connector_dict(self) -> dict[str, Any]: - assert self.cpu is not None - extra: dict[str, Any] = {"cpu_bytes_to_use": int(self.cpu.num_bytes)} - if self.disk is not None: - extra["spec_name"] = "TieringOffloadingSpec" - extra["secondary_tiers"] = [{"type": "fs", "root_dir": str(self.disk.path)}] - return { - "kv_connector": "OffloadingConnector", - "kv_role": "kv_both", - "kv_connector_extra_config": extra, - } - - -class MooncakeKVCacheOffloadConfig(BaseKVCacheOffloadConfig): - type: Literal["mooncake"] = "mooncake" - """Mooncake distributed store offloading (SLURM only). One ``mooncake_master`` + metadata server runs on the head inference node; every node runs a ``mooncake_client`` contributing its segment to the single shared pool, so prefixes cached on any node are reusable by all. The cpu tier sizes each node's DRAM segment; the optional disk tier adds an SSD tier.""" - - device_name: str = "" - """RDMA device name(s) for the store (empty = auto-detect).""" - - lease_ttl_s: float = Field(30.0, gt=0) - """How long the master protects a newly written or read KV object from eviction (``-default_kv_lease_ttl``). - Leased objects are skipped by eviction, so a lease close to the time the pool takes to turn over leaves only - fresh, not yet reused prefixes to evict, and one longer than the time it takes to fill blocks eviction: puts - then fail and the store stops caching. The P/D prefill-to-decode handoff goes over NIXL and is governed by its - own ``kv_lease_duration``, not this lease. Under P/D the larger of the two roles' values applies, since one - master serves both.""" - - lookup_async: bool = True - """Look up a request's prefix in the store on a background thread (``lookup_async``), starting when the request - arrives. A synchronous lookup blocks the scheduler for its whole duration (tens of ms for a long prompt, one key - per KV block and group), and with data parallelism the ranks of a node step together, so one rank's lookup - stalls them all.""" - - def to_connector_dict(self) -> dict[str, Any]: - # Addresses/sizes/tiers are realized by the per-node store launch in the sbatch - # template (MOONCAKE_CONFIG_PATH JSON); blocks are keyed by model + parallel rank + - # content hash (no instance id), so the shared pool is reused across nodes/replicas. - return { - "kv_connector": "MooncakeStoreConnector", - "kv_role": "kv_both", - "kv_connector_extra_config": {"lookup_async": self.lookup_async}, - } - - -KVCacheOffloadConfig: TypeAlias = Annotated[ - NativeKVCacheOffloadConfig | MooncakeKVCacheOffloadConfig, Field(discriminator="type") -] - - -class HiSparseConfig(BaseConfig): - """vLLM HiSparse for DSA sparse-MLA models (e.g. GLM-5.x): the sparse-MLA KV lives in a pinned host pool and decode attention reads per-request GPU buffers of the indexer top-k rows.""" - - host_pool_gib: float = Field(..., gt=0) - """Pinned host pool per GPU worker, in GiB (``HiSparseConnector`` ``host_pool_gib``). Budget ``GPUs per node × host_pool_gib`` against node RAM.""" - - -# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos). -KNOWN_SCORERS = frozenset( - { - "prefix-cache-scorer", - "precise-prefix-cache-scorer", - "queue-scorer", - "kv-cache-utilization-scorer", - "active-request-scorer", - "load-aware-scorer", - "running-requests-size-scorer", - "token-load-scorer", - "latency-scorer", - "session-affinity-scorer", - "lora-affinity-scorer", - } -) - - -class VllmRouterConfig(BaseConfig): - """PrimeIntellect vllm-router.""" - - type: Literal["vllm-router"] = "vllm-router" - - request_timeout_secs: int = Field(14400, ge=1) - """Maximum lifetime of a routed request, including streamed completions.""" - - policy: str = "sticky_least_loaded" - """Routing policy. Defaults to session-affine least-loaded routing; alternatives include ``consistent_hash`` and ``round_robin``.""" - - pd_turn_retries: int = Field(2, ge=0) - """Disaggregated P/D only: how often the router reruns a turn whose prefill or decode request failed with a connection error (``--pd-turn-retries``). A retry runs a fresh prefill and then decode, without the previous turn's decode KV. 0 returns the first error to the client.""" - - -class LlmdRouterConfig(BaseConfig): - """llm-d router backend (EPP + Envoy).""" - - type: Literal["llm-d"] = "llm-d" - - scorers: dict[str, float] = { - "prefix-cache-scorer": 3.0, - "active-request-scorer": 2.0, - } - """EPP scorer name → weight, applied to every routing profile (before the per-profile P/D overrides). Defaults to prefix-cache affinity plus in-flight (active-request) load balancing. Unknown scorer names are rejected.""" - - prefill_scorer_overrides: dict[str, float] = { - "queue-scorer": 2.0, - "kv-cache-utilization-scorer": 2.0, - } - """P/D only: scorer → weight merged onto ``scorers`` for the prefill profile (a per-profile weight overrides the base).""" - - decode_scorer_overrides: dict[str, float] = {} - """P/D only: scorer → weight merged onto ``scorers`` for the decode profile (a per-profile weight overrides the base); empty by default.""" - - non_cached_tokens: int = 16 - """P/D only: requests with fewer than this many non-cached prompt tokens skip remote prefill and run decode-only.""" - - decode_sidecar_port: int = 8300 - """P/D only: port the decode-side llm-d sidecar listens on.""" - - @property - def prefill_scorers(self) -> dict[str, float]: - """Effective prefill-profile scorers: ``scorers`` merged with ``prefill_scorer_overrides``.""" - return {**self.scorers, **self.prefill_scorer_overrides} - - @property - def decode_scorers(self) -> dict[str, float]: - """Effective decode-profile scorers: ``scorers`` merged with ``decode_scorer_overrides``.""" - return {**self.scorers, **self.decode_scorer_overrides} - - @model_validator(mode="after") - def validate_scorers(self): - unknown = ( - set(self.scorers) | set(self.prefill_scorer_overrides) | set(self.decode_scorer_overrides) - ) - KNOWN_SCORERS - if unknown: - raise ValueError(f"Unknown llm-d scorer(s): {sorted(unknown)}. Known scorers: {sorted(KNOWN_SCORERS)}.") - return self - - -# Discriminated on ``type`` so the launch path can pick the router backend. -RouterConfig: TypeAlias = Annotated[VllmRouterConfig | LlmdRouterConfig, Field(discriminator="type")] - - -class SpillToStoreConfig(BaseConfig): - """Write a finished turn's KV from decode to the Mooncake store shortly before its lease ends unread, and let a - turn that returns later fetch it from there (``prime_rl.inference.kv_spill``). - - Without it, decode pins every idle session's KV for the whole ``decode_blocks_ttl_s``, and a turn that returns - after the lease is recomputed in full. With it the lease can be a few tens of seconds: decode's KV cache then - holds mostly running requests, and late turns cost one store read. Both roles need a Mooncake - ``kv_cache_offload``; it only provides the store, vLLM's own store lookups, loads and saves stay off.""" - - start_before_expiry_s: float = Field(10.0, gt=5) - """How long before the lease ends the put starts. Prefill stops reading from decode 5 s before the lease ends, - so the put must be done by then.""" - - fetch_wait_s: float = Field(6.0, ge=0) - """How long a fetch waits for the objects of a put that is still in flight before it gives up and the turn is - recomputed.""" - - fetchable_for_s: int = Field(3600, ge=1) - """How long the router keeps a session's handle, and so how long after a turn its KV can still be fetched from - the store (if the store has not evicted it).""" - - -class BidirectionalKVTransferConfig(BaseConfig): - """Bidirectional NIXL KV transfer for multi-turn P/D (vLLM ``bidirectional_kv_xfer``). - - After a turn, decode keeps the turn's KV blocks (prompt and completion) for ``decode_blocks_ttl_s``. The router - remembers them per session (``x-session-id``) and hands them to the next turn's prefill, which reads them from - decode over NIXL and computes only the new tokens, instead of recomputing the conversation. Each handle is used at - most once: decode frees the blocks after the first read, so a retried turn falls back to a plain prefill.""" - - decode_blocks_ttl_s: int = Field(480, ge=1) - """How long decode keeps a finished turn's blocks for the next turn (``decoder_kv_blocks_ttl``). Retained blocks - occupy decode's KV cache until read or expired, so a long TTL with many idle sessions costs decode capacity.""" - - router_ttl_s: int | None = Field(None, ge=1) - """How long the router keeps a session's decode handle. Must be shorter than ``decode_blocks_ttl_s`` so the router - never hands out blocks decode has already released. Defaults to ``decode_blocks_ttl_s`` minus 30 s.""" - - spill_to_store: SpillToStoreConfig | None = None - """Spill expiring turns to the Mooncake store. The router then keeps handles for - ``spill_to_store.fetchable_for_s``, past the lease: prefill finds such a handle expired and reads the store.""" - - @property - def effective_router_ttl_s(self) -> int: - if self.router_ttl_s is not None: - return self.router_ttl_s - if self.spill_to_store is not None: - return self.spill_to_store.fetchable_for_s - return max(1, self.decode_blocks_ttl_s - 30) - - @model_validator(mode="after") - def router_ttl_below_decode_ttl(self): - if self.spill_to_store is not None: - if self.decode_blocks_ttl_s <= self.spill_to_store.start_before_expiry_s: - raise ValueError( - "bidirectional_kv_transfer.decode_blocks_ttl_s must be longer than " - "spill_to_store.start_before_expiry_s: the spill would otherwise start as the turn finishes." - ) - return self - if self.effective_router_ttl_s >= self.decode_blocks_ttl_s: - raise ValueError( - "bidirectional_kv_transfer.router_ttl_s must be shorter than decode_blocks_ttl_s: the router would " - "otherwise hand out decode blocks that are already released." - ) - return self - - -class BaseInferenceDeploymentConfig(BaseConfig): - gpus_per_node: int = 8 - """GPUs per node.""" - - -class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig): - type: Literal["single_node"] = "single_node" - - -# Multi-node inference: each node runs an independent vLLM replica. -class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig): - type: Literal["multi_node"] = "multi_node" - - num_nodes: int = Field(2, ge=1) - """Inference nodes.""" - - -# Disaggregated prefill/decode inference. Each replica is split into separate -# prefill and decode node groups. Requires NIXL for KV transfer and a router for -# request routing. -class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig): - type: Literal["disaggregated"] = "disaggregated" - - prefill_nodes_per_replica: int = Field(1, ge=1) - """Nodes in each prefill vLLM instance.""" - - decode_nodes_per_replica: int = Field(1, ge=1) - """Nodes in each decode vLLM instance.""" - - num_prefill_replicas: int = Field(1, ge=1) - """Independent prefill vLLM instances.""" - - num_decode_replicas: int = Field(1, ge=1) - """Independent decode vLLM instances.""" - - prefill_port: int = 8100 - """Port for prefill vLLM instances.""" - - decode_port: int = 8200 - """Port for decode vLLM instances.""" - - prefill_env_vars: EnvVars = {} - """Extra environment variables exported only on prefill nodes.""" - - decode_env_vars: EnvVars = {} - """Extra environment variables exported only on decode nodes.""" - - prefill_vllm_overrides: dict[str, Any] = {} - """Extra vLLM config options merged into --vllm-extra only for prefill ranks (SLURM only).""" - - decode_vllm_overrides: dict[str, Any] = {} - """Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only).""" - - prefill_kv_cache_offload: KVCacheOffloadConfig | Literal["inherit"] | None = "inherit" - """KV cache offload on prefill instances. ``inherit`` uses ``inference.kv_cache_offload``; None disables it.""" - - decode_kv_cache_offload: KVCacheOffloadConfig | Literal["inherit"] | None = "inherit" - """KV cache offload on decode instances. ``inherit`` uses ``inference.kv_cache_offload``; None disables it.""" - - bidirectional_kv_transfer: BidirectionalKVTransferConfig | None = None - """Bidirectional KV transfer: the next turn's prefill reads the previous turn's KV back from decode. Requires the - ``vllm-router`` router. None (default) keeps one-way prefill-to-decode transfer.""" - - nixl_nic_affinity: bool = True - """Pin each single-GPU engine's NIXL/UCX traffic to the RDMA port nearest its GPU, on one rail - (``UCX_NET_DEVICES``, ``UCX_MAX_RMA_RAILS=1``). Spreading GPUDirect RDMA over every NIC sends traffic across - CPU sockets, which can stall the GPU under sustained P/D transfer load. Engines spanning several GPUs keep all - ports.""" - - @property - def num_prefill_nodes(self) -> int: - return self.prefill_nodes_per_replica * self.num_prefill_replicas - - @property - def num_decode_nodes(self) -> int: - return self.decode_nodes_per_replica * self.num_decode_replicas - - @property - def num_nodes(self) -> int: - return self.num_prefill_nodes + self.num_decode_nodes - - -InferenceDeploymentConfig: TypeAlias = Annotated[ - SingleNodeInferenceDeploymentConfig | MultiNodeInferenceDeploymentConfig | DisaggregatedInferenceDeploymentConfig, - Field(discriminator="type"), -] - - -class InferenceConfig(BaseConfig): - server: ServerConfig = ServerConfig() - - router: RouterConfig | None = Field(default_factory=VllmRouterConfig) - """Router fronting the engine(s). Every deployment runs a single global router as the client-facing endpoint on ``server.port``, with the engines listening on ``backend_port``. Set to ``None`` to run a bare engine on ``server.port`` without a router (the SLURM launchers do this for per-rank engine processes; the sbatch script starts the router).""" - - backend_port: int = 8100 - """Port for the vLLM engine(s) behind the router. Defaults to ``server.port + 100``. Multi-node deployments start one engine per local DP rank at ``backend_port + rank``.""" - - vllm: VllmConfig = Field(default_factory=VllmConfig) - """vLLM server arguments, under vLLM's own argument names. Unknown fields pass through verbatim.""" - - log: LogConfig = LogConfig() - """Logging configuration.""" - - env_vars: EnvVars = {} - """Extra environment variables for the inference server process(es). Merged on top of the launcher defaults.""" - - use_deep_gemm: bool = False - """Enable vLLM DeepGEMM FP8 kernels ``VLLM_USE_DEEP_GEMM=1``. Only works with block-wise FP8 quantization (e.g. GLM-5-FP8).""" - - weight_broadcast: WeightBroadcastConfig = WeightBroadcastConfig() - - kv_cache_offload: KVCacheOffloadConfig | None = None - """KV cache offload for inference workers, as composable CPU/disk tiers. Discriminated on ``type``: ``native`` (vLLM ``OffloadingConnector``/``TieringOffloadingSpec``, self-contained) or ``mooncake`` (per-node Mooncake distributed store). Disaggregated P/D combines the chosen connector with NIXL through ``MultiConnector``.""" - - hisparse: HiSparseConfig | None = None - """Enable vLLM HiSparse (experimental). Under disaggregated P/D it applies to decode instances only, and decode must not offload KV (``deployment.decode_kv_cache_offload = None``). vLLM checks its requirements at startup (a DSA model, no pipeline or decode context parallelism).""" - - use_pd_kv_transfer: bool = False - """Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand.""" - - pd_decode_blocks_ttl_s: int | None = None - """Auto-set from ``deployment.bidirectional_kv_transfer``: enables bidirectional NIXL transfer with this decode block TTL. Persisted into the per-node config like ``use_pd_kv_transfer``. Not meant to be set by hand.""" - pd_spill_to_store: SpillToStoreConfig | None = None - """Auto-set from ``deployment.bidirectional_kv_transfer.spill_to_store``. Persisted into the per-node config like - ``pd_decode_blocks_ttl_s``. Not meant to be set by hand.""" - - kv_load_failure_policy: Literal["recompute", "fail"] | None = None - """What vLLM does when a KV load from another instance fails or is declined (``kv_transfer_config.kv_load_failure_policy``): ``recompute`` computes the missing tokens locally, ``fail`` ends the request with an error. None keeps vLLM's default (``fail``). Under bidirectional P/D, prefill defaults to ``recompute``: it declines reading decode blocks that are about to expire, and that turn should then prefill locally instead of failing.""" - - enable_return_sampling_mask: bool = False - """Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling and for recorded sampler logprobs (``sampling.logprobs``, set by score centering), which are captured next to the mask. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs. Requests opt in with ``extra_args.prl_replay = true``; only these requests require positive temperature. Their supports are captured whole, so top-p alone needs no top-k. Evaluation requests need not opt in. Under speculative decoding each accepted position carries its own support, and sampler logprobs need truncated (replayed) sampling.""" - - sampling_support_capacity: int = Field(16 * 2**20, ge=1) - """Entries (8 bytes each) in the per-step device buffer that holds captured sampling supports: the kept ids of every replayed request in one sampling step, plus sampler rows. Requests whose supports do not fit fail with an explicit error instead of being truncated; the server logs the maximum per-step total every minute.""" - - enable_fp32_lm_head: bool = True - """Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented natively by vLLM's LogitsProcessor, which reads ``head_dtype`` off the HF config, so this flag injects ``hf_overrides = {"head_dtype": "float32"}``.""" - - enable_fp32_router_logits: bool = True - """Request FP32 MoE router logits via ``hf_overrides = {"moe_router_dtype": "float32"}``. Operand and weight precision depend on the serving model implementation; FP32 logits do not imply FP32 gate weights. Trainer routers use BF16 operands with FP32 logits; configure serving gate precision explicitly to match.""" - - # Launcher-only fields - - deployment: InferenceDeploymentConfig = SingleNodeInferenceDeploymentConfig() - - slurm: SlurmConfig | None = None - """SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally.""" - - output_dir: Path = Field(default_factory=default_output_dir) - """Directory for SLURM logs and generated scripts. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" - - dry_run: bool = False - """Only validate and dump resolved configs, then exit early.""" - - @model_validator(mode="after") - def validate_multi_node_requires_slurm(self): - if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None: - raise ValueError("Must use SLURM for multi-node / disaggregated deployment.") - return self - - @model_validator(mode="after") - def validate_llmd_no_routed_experts(self): - """Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node).""" - if self.router is not None and self.router.type == "llm-d" and self.vllm.enable_return_routed_experts: - raise ValueError( - "The llm-d router backend does not support routed-expert return " - "(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. " - "Use router type 'vllm-router' for routed-expert runs." - ) - return self - - @model_validator(mode="after") - def validate_hisparse_decode_offload(self): - """A HiSparse decode instance keeps its sparse-MLA KV in a host-resident layout: native offload rejects it, and Mooncake stores it under the same keys as prefill's regular layout, so prefill fails to load it.""" - if self.hisparse is None: - return self - if self.kv_cache_offload_by_role.get("decode") is not None: - raise ValueError( - "HiSparse runs on decode, which cannot also offload KV: set " - "inference.deployment.decode_kv_cache_offload = None (prefill offload is supported)." - ) - if isinstance(self.kv_cache_offload_by_role.get("all"), NativeKVCacheOffloadConfig): - raise ValueError("HiSparse does not work with native KV cache offload: use Mooncake or no offload.") - return self - - @model_validator(mode="after") - def validate_bidirectional_kv_transfer(self): - """Bidirectional transfer needs a router that tracks each session's decode blocks, and decode blocks in the - regular paged layout (HiSparse keeps decode's sparse-MLA KV in a host pool that prefill cannot read).""" - if self.deployment.type != "disaggregated" or self.deployment.bidirectional_kv_transfer is None: - return self - if self.router is None or self.router.type != "vllm-router": - raise ValueError("deployment.bidirectional_kv_transfer requires the vllm-router router.") - if self.hisparse is not None: - raise ValueError("deployment.bidirectional_kv_transfer does not support HiSparse decode instances.") - if self.deployment.bidirectional_kv_transfer.spill_to_store is not None: - offloads = self.kv_cache_offload_by_role - if any(offloads[role] is None or offloads[role].type != "mooncake" for role in ("prefill", "decode")): - raise ValueError( - "bidirectional_kv_transfer.spill_to_store needs a Mooncake kv_cache_offload on prefill and " - "decode: it provides the store that expiring turns are written to." - ) - return self - - @model_validator(mode="after") - def validate_router_deployment(self): - """The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines.""" - if self.router is not None and self.router.type == "llm-d" and self.deployment.type == "single_node": - raise ValueError("The llm-d router backend requires a multi-node or disaggregated SLURM deployment.") - if self.router is None and self.deployment.type in ("multi_node", "disaggregated"): - raise ValueError("Multi-node / disaggregated deployments require a router fronting the per-rank engines.") - return self - - @model_validator(mode="after") - def auto_setup_backend_port(self): - if self.router is not None and "backend_port" not in self.model_fields_set: - self.backend_port = self.server.port + 100 - return self - - @model_validator(mode="after") - def auto_setup_kv_cache_offload(self): - offloads = [offload for offload in self.kv_cache_offload_by_role.values() if offload is not None] - if len({offload.disk.path for offload in offloads if offload.type == "mooncake" and offload.disk}) > 1: - raise ValueError("Mooncake roles share one store master, so their disk tiers must use the same path.") - if offloads: - if self.vllm.enable_prefix_caching is False: - raise ValueError("KV cache offloading requires inference.vllm.enable_prefix_caching to be true.") - if "enable_prefix_caching" not in self.vllm.model_fields_set: - self.vllm.enable_prefix_caching = True - - return self - - @model_validator(mode="after") - def auto_setup_disaggregated(self): - """Auto-configure inference for disaggregated P/D: enable EP and compute DP.""" - if self.deployment.type == "disaggregated": - self.use_pd_kv_transfer = True - if self.deployment.bidirectional_kv_transfer is not None: - self.pd_decode_blocks_ttl_s = self.deployment.bidirectional_kv_transfer.decode_blocks_ttl_s - self.pd_spill_to_store = self.deployment.bidirectional_kv_transfer.spill_to_store - if "enable_expert_parallel" not in self.vllm.model_fields_set: - self.vllm.enable_expert_parallel = True - if "enable_eplb" not in self.vllm.model_fields_set: - self.vllm.enable_eplb = False - gpus_per_node = self.deployment.gpus_per_node - tp = self.vllm.tensor_parallel_size - dp_per_node = gpus_per_node // tp - if self.vllm.data_parallel_size_local is None: - self.vllm.data_parallel_size_local = dp_per_node - if self.vllm.data_parallel_size == 1: - self.vllm.data_parallel_size = dp_per_node - if self.vllm.api_server_count == 1: - self.vllm.api_server_count = dp_per_node - return self - - @model_validator(mode="after") - def auto_setup_slurm_template(self): - if self.slurm is not None and self.slurm.job_name is None: - self.slurm.job_name = "inference" - if self.slurm is not None and self.slurm.template_path is None: - templates_dir = find_package_resource("templates") - if templates_dir is not None: - self.slurm.template_path = templates_dir / "inference.sbatch.j2" - return self - - @property - def kv_cache_offload_by_role(self) -> dict[str, KVCacheOffloadConfig | None]: - """KV cache offload per P/D role (``prefill``/``decode``), or ``all`` for other deployments.""" - if self.deployment.type != "disaggregated": - return {"all": self.kv_cache_offload} - overrides = { - "prefill": self.deployment.prefill_kv_cache_offload, - "decode": self.deployment.decode_kv_cache_offload, - } - return {role: self.kv_cache_offload if offload == "inherit" else offload for role, offload in overrides.items()} - - def for_pd_role(self, role: Literal["prefill", "decode"]) -> "InferenceConfig": - """Self-contained engine config for one disaggregated role.""" - assert isinstance(self.deployment, DisaggregatedInferenceDeploymentConfig) - config = self.model_copy(deep=True) - config.kv_cache_offload = self.kv_cache_offload_by_role[role] - role_nodes = ( - self.deployment.prefill_nodes_per_replica if role == "prefill" else self.deployment.decode_nodes_per_replica - ) - dp_local = config.vllm.data_parallel_size_local or config.vllm.data_parallel_size - config.vllm.data_parallel_size = role_nodes * dp_local - config.vllm.data_parallel_size_local = dp_local - if not config.vllm.enable_lora: - config.vllm.api_server_count = dp_local - if role == "prefill": - config.server.port = self.deployment.prefill_port - config.hisparse = None - if self.pd_decode_blocks_ttl_s is not None and "kv_load_failure_policy" not in self.model_fields_set: - config.kv_load_failure_policy = "recompute" - role_vllm: dict[str, Any] = {"all2all_backend": "deepep_high_throughput"} - role_vllm.update(self.deployment.prefill_vllm_overrides) - role_env: dict[str, str] = {} - if prefill_uses_deepep_high_throughput(self.deployment.prefill_vllm_overrides): - role_env["VLLM_USE_BREAKABLE_CUDAGRAPH"] = "0" - role_env.update(self.deployment.prefill_env_vars) - else: - config.server.port = self.deployment.decode_port - role_vllm = { - "all2all_backend": "deepep_low_latency", - "compilation_config": {"cudagraph_mode": "FULL_DECODE_ONLY"}, - } - role_vllm.update(self.deployment.decode_vllm_overrides) - role_env = dict(self.deployment.decode_env_vars) - - for key, value in role_vllm.items(): - setattr(config.vllm, key.replace("-", "_"), value) - config.env_vars = {**config.env_vars, **role_env} - return config - - def build_kv_transfer_config(self) -> dict[str, Any] | None: - """Build the single vLLM ``kv_transfer_config`` from the transfer, offload and HiSparse connectors. - - Disaggregated P/D always uses NIXL for prefill→decode transfer. KV cache offload and - HiSparse (if configured) contribute their own connectors. Several connectors are composed - via ``MultiConnector``. Returns None when none applies. - """ - connectors: list[dict[str, Any]] = [] - bidirectional = self.use_pd_kv_transfer and self.pd_decode_blocks_ttl_s is not None - spill = self.pd_spill_to_store if bidirectional else None - if self.use_pd_kv_transfer: - nixl_extra: dict[str, Any] = {"num_threads": 1} - if bidirectional: - nixl_extra |= {"bidirectional_kv_xfer": True, "decoder_kv_blocks_ttl": self.pd_decode_blocks_ttl_s} - if spill is not None: - nixl_extra |= { - "prime_rl_spill_lead_s": spill.start_before_expiry_s, - "prime_rl_spill_fetch_wait_s": spill.fetch_wait_s, - } - connectors.append( - {"kv_connector": "NixlConnector", "kv_role": "kv_both", "kv_connector_extra_config": nixl_extra} - ) - if self.kv_cache_offload is not None: - connector = self.kv_cache_offload.to_connector_dict() - if spill is not None and connector["kv_connector"] == "MooncakeStoreConnector": - # Capacity-only: the connector mounts the store client for the spill and does no lookups, loads or - # saves of its own. - connector["kv_role"] = "kv_consumer" - connector["kv_connector_extra_config"]["enable_lookup"] = False - elif self.use_pd_kv_transfer and connector["kv_connector"] == "MooncakeStoreConnector": - # Decode instances also store the KV they generate, so the next turn's prefill can load it. - connector["kv_connector_extra_config"]["save_decode_cache"] = True - connectors.append(connector) - if self.hisparse is not None: - connectors.append( - { - "kv_connector": "HiSparseConnector", - "kv_role": "kv_both", - "kv_connector_extra_config": {"host_pool_gib": self.hisparse.host_pool_gib}, - } - ) - - if not connectors: - return None - if len(connectors) == 1: - config = connectors[0] - else: - config = { - "kv_connector": "MultiConnector", - "kv_role": "kv_both", - "kv_connector_extra_config": {"connectors": connectors}, - } - if self.kv_load_failure_policy is not None: - # The scheduler reads the policy from the top-level config only, also under MultiConnector. - config["kv_load_failure_policy"] = self.kv_load_failure_policy - return config - - # Fields vLLM rejects as None — omitted from the namespace so vLLM applies its - # own default (e.g. quantization is inferred from the checkpoint). - _OMIT_IF_NONE = frozenset( - {"chat_template", "tool_call_parser", "reasoning_parser", "lora_target_modules", "quantization", "rope_scaling"} - ) - - def to_namespace(self) -> Namespace: - """Dump the server + vllm sections into a vLLM-compatible Namespace.""" - namespace = Namespace( - host=self.server.host, - port=self.server.port, - liveness_timeout_seconds=self.server.liveness_timeout_seconds, - admin_token_var=self.server.admin_token_var, - ) - - extra_fields = self.vllm.model_extra or {} - for key in (*type(self.vllm).model_fields, *extra_fields): - value = getattr(self.vllm, key) - # None extras are dropped too: `--vllm.foo None` means "use vLLM's default". - if value is None and (key in self._OMIT_IF_NONE or key in extra_fields): - continue - setattr(namespace, key, value) - - # Auto tool choice is gated on a tool-call parser being resolved, unless - # explicitly overridden. - if "enable_auto_tool_choice" not in extra_fields: - namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser") - - # Default `logprobs_mode` to `processed_logprobs` - if not hasattr(namespace, "logprobs_mode"): - namespace.logprobs_mode = "processed_logprobs" - - # Always surface cached prompt tokens in `usage` — the router's - # cache-discount billing counters parse them off /inference/v1/generate. - if "enable_prompt_tokens_details" not in extra_fields: - namespace.enable_prompt_tokens_details = True - - # The orchestrator generates through /inference/v1/generate, a scale-out - # endpoint that vLLM registers only with `--enable-scale-out`. - if "enable_scale_out" not in extra_fields: - namespace.enable_scale_out = True - - # vLLM's DeepseekV2-family (and transformers-backend MoE) gates read - # `moe_router_dtype` off the HF config to pick the router logits dtype. - if self.enable_fp32_router_logits: - hf_overrides = getattr(namespace, "hf_overrides", None) or {} - hf_overrides.setdefault("moe_router_dtype", "float32") - namespace.hf_overrides = hf_overrides - - # vLLM's LogitsProcessor reads `head_dtype` off the HF config to pick the - # lm_head projection dtype (fp32 runs as a native bf16xbf16 -> fp32 GEMM). - if self.enable_fp32_lm_head: - hf_overrides = getattr(namespace, "hf_overrides", None) or {} - hf_overrides.setdefault("head_dtype", "float32") - namespace.hf_overrides = hf_overrides - - if self.enable_return_sampling_mask: - namespace.return_sampling_mask = True - - # The LoRA adapter is registered under the model name clients send, and vLLM rejects - # an adapter named like a served base model, so serve the base under another name. - if self.vllm.enable_lora and "served_model_name" not in extra_fields: - namespace.served_model_name = [f"{self.vllm.model}-base"] - - kv_transfer_config = self.build_kv_transfer_config() - if kv_transfer_config is not None: - namespace.kv_transfer_config = kv_transfer_config - - default_moe_backend = os.environ.get("PRL_DEFAULT_MOE_BACKEND") - if default_moe_backend and getattr(namespace, "moe_backend", None) is None: - namespace.moe_backend = default_moe_backend - - return namespace - - -def prefill_uses_deepep_high_throughput(overrides: dict[str, Any]) -> bool: - """vLLM cannot capture DeepEP high-throughput dispatch in a breakable CUDA graph.""" - return overrides.get("all2all_backend", "deepep_high_throughput") == "deepep_high_throughput" - - -MODEL_NAME_DRAFT_METHODS = ("mtp", "dspark") - - -def setup_dummy_load(inference: InferenceConfig, dummy: bool) -> None: - """With ``dummy``, the server starts with placeholder weights (``load_format = "dummy"``), which the trainer's - startup broadcast replaces, unless ``load_format`` is set explicitly. That is the case when the trainer's weights - are not HF weights stored at ``model.name``: a ``scratch`` init, known from the config, or a checkpoint step - directory as ``model.name``, which the inference server detects since only it is sure to see the path. HF weights - still load from disk: vLLM checks that a load from disk writes every weight, but no weight transfer checks that the - trainer's update does, so a weight the update misses keeps its pretrained value instead of a placeholder. - - Under a dummy-loaded target, a speculative draft with its own ``model`` still loads it from disk, except a - ``draft_model`` draft, which vLLM loads with the target's load format. A draft that reads its weights from - ``model.name`` (MTP, DSpark without a ``model``) gets none.""" - if dummy and "load_format" not in (inference.vllm.model_extra or {}): - inference.vllm.load_format = "dummy" - if getattr(inference.vllm, "load_format", None) != "dummy": - return - overrides = [inference.vllm.model_extra or {}] - if isinstance(inference.deployment, DisaggregatedInferenceDeploymentConfig): - overrides += [inference.deployment.prefill_vllm_overrides, inference.deployment.decode_vllm_overrides] - for override in overrides: - draft = next((value for key, value in override.items() if key.replace("-", "_") == "speculative_config"), None) - if not draft: - continue - draft_keys = {key.replace("-", "_") for key in draft} - # vLLM treats a draft with a model but no method as a draft_model draft - method = str(draft.get("method") or ("draft_model" if "model" in draft_keys else None)) - if method == "draft_model": - raise ValueError( - 'vLLM loads a speculative_config method "draft_model" draft with the target\'s load format, here ' - 'dummy: use a method such as "eagle3", or load the target from disk (HF weights at model.name with model.init.type = "pretrained", or an explicit inference.vllm.load_format)' - ) - if "model" in draft_keys: - if "draft_load_config" not in draft_keys: - draft["draft_load_config"] = {"load_format": "auto"} - continue - if method in MODEL_NAME_DRAFT_METHODS or method.endswith("_mtp"): - raise ValueError( - f'speculative_config method "{method}" reads its draft weights from model.name, which a dummy-loaded ' - 'server does not load: set speculative_config.model to a draft checkpoint, or load the target from disk (HF weights at model.name with model.init.type = "pretrained", or an explicit inference.vllm.load_format)' - ) diff --git a/packages/prime-rl-configs/src/prime_rl/configs/modelexpress_server.py b/packages/prime-rl-configs/src/prime_rl/configs/modelexpress_server.py deleted file mode 100644 index 0ac04b99814..00000000000 --- a/packages/prime-rl-configs/src/prime_rl/configs/modelexpress_server.py +++ /dev/null @@ -1,26 +0,0 @@ -from pathlib import Path - -from pydantic import ConfigDict, Field - -from prime_rl.configs.shared import ( - FileSystemWeightBroadcastConfig, - ModelExpressWeightBroadcastConfig, - WeightBroadcastConfig, -) -from prime_rl.utils.config import BaseConfig - - -class ModelExpressServerConfig(BaseConfig): - model_config = ConfigDict(extra="ignore") - - weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig() - port: int | None = Field(default=None, ge=1, le=65535) - log_dir: Path = Path("/tmp") - - @property - def resolved_port(self) -> int: - if self.port is not None: - return self.port - if isinstance(self.weight_broadcast, ModelExpressWeightBroadcastConfig): - return self.weight_broadcast.port - return ModelExpressWeightBroadcastConfig().port diff --git a/packages/prime-rl-configs/src/prime_rl/configs/orchestrator.py b/packages/prime-rl-configs/src/prime_rl/configs/orchestrator.py deleted file mode 100644 index 144fab7d523..00000000000 --- a/packages/prime-rl-configs/src/prime_rl/configs/orchestrator.py +++ /dev/null @@ -1,810 +0,0 @@ -import warnings -from collections.abc import Callable -from pathlib import Path -from typing import Annotated, Any, Literal, TypeAlias, get_args - -import verifiers.v1 as vf -from pydantic import AliasChoices, BaseModel, Field, SerializeAsAny, TypeAdapter, ValidationError, model_validator -from pydantic.fields import FieldInfo -from renderers import AutoRendererConfig, RendererConfig -from verifiers.v1.configs.agent import agent_config_fields - -from prime_rl.configs.algorithm import ( - AlgoConfig, - GRPOAlgoConfig, -) -from prime_rl.configs.diff import Frozen, Live -from prime_rl.configs.env_worker_pool import ServeConfig -from prime_rl.configs.monitors import MonitorsConfig -from prime_rl.configs.shared import ( - BaseCheckpointConfig, - BaseModelConfig, - ControlConfig, - EnvVars, - FileSystemWeightBroadcastConfig, - GCConfig, - HeartbeatConfig, - LogConfig, - PolicyClientConfig, - ResumeConfig, - WeightBroadcastConfig, - ZMQTransportConfig, -) -from prime_rl.configs.trainer import TokenizerConfig -from prime_rl.utils.config import BaseConfig, default_output_dir - - -class ModelConfig(BaseModelConfig): - client: PolicyClientConfig = Field(default_factory=PolicyClientConfig) - """Client of the live deployment (``[orchestrator.model.client]``).""" - - -class TrainSamplingConfig(BaseConfig): - temperature: Annotated[float, Live()] = Field(1.0, ge=0, le=2.0) - """Sampling temperature.""" - - top_p: float = Field(1.0, gt=0, le=1.0) - """Nucleus (top-p) sampling for train rollouts. Values below 1.0 truncate the sampling - distribution; the ``rl`` entrypoint auto-enables sampling replay so trainer and - rollout distributions stay consistent — see docs/inference.md (Sampling Replay).""" - - top_k: int | None = Field(None, ge=1) - """Top-k sampling for train rollouts. Truncation triggers sampling replay, and a default top-k - is set when only top-p truncates so every replayed support is bounded — see docs/inference.md - (Sampling Replay).""" - - max_completion_tokens: Annotated[int | None, Live()] = None - """Maximum output tokens per turn. If None, generates until max context length or EOS.""" - - logprobs: int | None = Field(None, ge=1) - """Record this many top sampler probabilities per token, in addition to its sampled logprob.""" - - # Strictly speaking, extra_body is not a sampling parameter, but it is the - # easiest way to pass arbitrary extra parameters to the server via verifiers - extra_body: Annotated[dict[str, Any], Live()] = {} - """Extra body forwarded with each request to the inference server.""" - - def truncates_distribution(self) -> bool: - return self.top_p < 1.0 or self.top_k is not None - - @model_validator(mode="after") - def validate_no_extra_body_truncation(self): - """Truncating values must come from the typed fields — the replay policy reads - them. Disabled values (``top_k = -1`` / ``min_p = 0.0``) pass, so configs - saved with these sentinels re-validate cleanly.""" - smuggled = [ - key - for key, truncates in ( - ("top_p", self.extra_body.get("top_p", 1.0) < 1.0), - ("top_k", self.extra_body.get("top_k") not in (None, -1, 0)), - ("min_p", self.extra_body.get("min_p", 0.0) > 0.0), - ) - if truncates - ] - if smuggled: - raise ValueError( - f"extra_body carries truncating {smuggled}; set them as fields on the train " - "sampling config instead (they drive sampling replay)." - ) - return self - - -class EnvConfig(BaseConfig): - """One environment a run pulls from: the verifiers blocks it composes (``env`` — what - runs, ``serve`` — how it's hosted) plus this orchestrator's own per-env knobs.""" - - env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig() - """The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id.""" - - serve: ServeConfig = ServeConfig() - """How this source's env worker pool is hosted. Each replica has a broker endpoint - and workers running the source's env configuration. An unset ``address`` lets the - launcher start the pool and discover its bound address. Setting ``address`` selects - one externally managed pool; the launcher neither writes its config nor starts it.""" - - name: str | None = None - """Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group.""" - - select: vf.SelectConfig = vf.SelectConfig() - """Which of the taskset's tasks this source uses: ``include``/``exclude`` by ``idx``, ``ids``, ``keys`` or ``names``, then ``shuffle``, ``skip`` and ``limit``, applied in that order.""" - - @model_validator(mode="before") - @classmethod - def _resolve_env(cls, data): - """Narrow ``env`` to the selected env's config class.""" - return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls)) - - @property - def env_id(self) -> str: - return self.env.env_id or "" - - @property - def resolved_name(self) -> str: - return self.name or self.env_id - - @model_validator(mode="after") - def validate_env(self): - if not self.env_id: - raise ValueError('no env configured — set env = { taskset = { id = "" } }') - if self.resolved_name == "agg": - raise ValueError( - 'Environment name "agg" is reserved for cross-env metric aggregation. Use a different name or id.' - ) - return self - - -def inherit_defaults(defaults: dict[str, Any], source: dict) -> dict: - """Fill in one raw source with its group's ``defaults`` (field name to validated - group value). A config block such as ``sampling`` is filled in key by key with - ``vf.merge_defaults``; a plain value such as ``group_size`` is used only when the - source leaves it unset. The source's own values always win, and a block that the - source passes as an already-built config is kept as is.""" - merged = dict(source) - for name, value in defaults.items(): - own = source.get(name) - if isinstance(value, BaseModel): - if own is None or isinstance(own, dict): - merged[name] = vf.merge_defaults(value, own) - elif name not in source: - merged[name] = value - return merged - - -def raw_field(data: dict, name: str, field: FieldInfo) -> tuple[bool, Any]: - """Whether raw ``data`` sets field ``name``, under its name or an alias (``-r`` - arrives as ``r``), and the value it sets.""" - alias = field.validation_alias - keys = [name, *(alias.choices if isinstance(alias, AliasChoices) else [alias] if alias else [])] - for key in keys: - if isinstance(key, str) and key in data: - return True, data[key] - return False, None - - -class StandardSamplerConfig(BaseConfig): - type: Literal["standard"] = "standard" - - -class DifficultyPoolConfig(BaseConfig): - threshold: float - """Inclusive maximum reward assigned to this pool.""" - - weight: float = Field(ge=0) - """Relative per-task sampling weight.""" - - -def default_difficulty_pools() -> dict[str, DifficultyPoolConfig]: - return { - "hard": DifficultyPoolConfig(threshold=0.25, weight=0.2), - "normal": DifficultyPoolConfig(threshold=0.75, weight=1.0), - "easy": DifficultyPoolConfig(threshold=1.0, weight=0.2), - } - - -class DifficultyPoolSamplerConfig(BaseConfig): - type: Literal["difficulty_pool"] = "difficulty_pool" - - pools: dict[str, DifficultyPoolConfig] = Field(default_factory=default_difficulty_pools) - """Named pools ordered by their reward thresholds.""" - - unseen_weight: float = Field(1.0, ge=0) - """Relative per-task sampling weight of tasks without a score yet.""" - - seed: int = 42 - - @model_validator(mode="after") - def validate_pools(self): - if not self.pools: - raise ValueError("DifficultyPoolSampler requires at least one pool") - thresholds = [pool.threshold for pool in self.pools.values()] - if len(set(thresholds)) != len(thresholds): - raise ValueError("Difficulty pool thresholds must be unique") - if not any(pool.weight > 0 for pool in self.pools.values()): - raise ValueError("At least one difficulty pool must have a positive weight") - return self - - -TaskSamplerConfig: TypeAlias = Annotated[ - StandardSamplerConfig | DifficultyPoolSamplerConfig, - Field(discriminator="type"), -] - - -class AdvRangeGateConfig(BaseConfig): - type: Literal["advantage_range"] = "advantage_range" - - reject_min: float = 0.0 - reject_max: float = 0.0 - - @model_validator(mode="after") - def validate_range(self): - if self.reject_min > self.reject_max: - raise ValueError("reject_min must be less than or equal to reject_max") - return self - - -AdmissionGateConfig: TypeAlias = AdvRangeGateConfig - - -class CurriculumConfig(BaseConfig): - sampler: TaskSamplerConfig = Field(default_factory=StandardSamplerConfig) - """Task selection policy. The default cycles through the task iterator in source order.""" - - gates: dict[str, AdmissionGateConfig] = Field(default_factory=dict) - """Named admission policies. Every gate observes every finalized group, - and a group trains only when every gate admits it.""" - - -class TrainSourceConfig(EnvConfig): - sampling: TrainSamplingConfig = TrainSamplingConfig() - """Per-env sampling overrides. Unset fields inherit from the group-level train sampling config.""" - - ratio: Annotated[float, Live()] = Field(1.0, gt=0) - """Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env.""" - - group_size: Annotated[int, Live()] = Field(1, ge=1) - """Rollouts generated per example for GRPO group-relative advantages. Overrides the - train group's ``group_size`` for this env, so envs can use different sizes. A live - change applies to groups drawn after it; open groups keep the size they started with.""" - - algo: AlgoConfig = GRPOAlgoConfig() - """Training algorithm for this env: sampling plus the per-token training signal - (credit assignment and loss routing, fused — its ``type`` names the algorithm). - Setting only some params keeps the group's algorithm; a different ``type`` is - this env's own algorithm. Frozen except its live fields (the GRPO ``length_penalty``).""" - - curriculum: CurriculumConfig | None = None - """User-authored task sampler and admission gates. The default cycles - through the taskset and admits every finalized group.""" - - @model_validator(mode="after") - def validate_policy_sampling(self): - if self.algo.rollout_model != "policy": - return self - # The source owns the distribution replayed by the trainer; agents may - # change generation limits and rendering without changing that distribution. - agent_options = {"max_tokens", "reasoning_effort", "chat_template_kwargs", "skip_special_tokens"} - supported = ( - agent_options - | TrainSamplingConfig.model_fields.keys() - | {"min_p", "logprobs", "return_token_ids", "cache_salt"} - ) - sampling = vf.SamplingConfig(**self.sampling.model_dump(exclude_none=True)) - if getattr(sampling, "extra_args", None) == {"prl_replay": self.sampling.truncates_distribution()}: - supported.add("extra_args") - if unsupported := sampling.model_dump(exclude_none=True).keys() - supported: - raise ValueError( - f"Policy source '{self.resolved_name}' has unsupported sampling parameters: {sorted(unsupported)}" - ) - for name, agent in agent_config_fields(self.env).items(): - # An agent with its own client does not sample from the policy. - if agent.sampling is None or agent.client is not None: - continue - if unsupported := agent.sampling.model_dump(exclude_unset=True).keys() - agent_options: - raise ValueError( - f"Agent '{name}' in policy source '{self.resolved_name}' sets sampling {sorted(unsupported)}. " - "Set distribution parameters on the source's sampling config; agent sampling only supports " - f"{sorted(agent_options)}." - ) - return self - - -class EvalSourceConfig(EnvConfig): - sampling: vf.SamplingConfig = vf.SamplingConfig() - """Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config.""" - - group_size: int = Field(1, ge=1) - """Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8).""" - - -class OnlineEvalSourceConfig(EvalSourceConfig): - """An eval source of a training run: evaluated on a step interval.""" - - interval: Annotated[int, Live()] = Field(100, ge=1) - """Step interval at which to evaluate this env.""" - - -class SourceGroupConfig(BaseConfig): - """A list of sources plus defaults for them. - - Any field that both the group and its source type declare (``env``, ``sampling``, - ``select``, ``group_size``, ...) is a default. Before validation, each source gets - the group's value for every such field that the group sets: - - - a field the source sets itself keeps the source's value; - - a nested block is filled in key by key (``vf.merge_defaults``); - - a block with a different ``type``/``id`` (e.g. another ``algo``) is the source's - alone. - - A field the group leaves unset is not passed on, so each group field must default - to the same value as the source field it feeds.""" - - env: vf.SharedEnvConfig = vf.SharedEnvConfig() - """Env knobs that every source inherits: the fields every env and taskset has, such - as ``retries`` and ``timeout``.""" - - @model_validator(mode="before") - @classmethod - def inherit_group_defaults(cls, data: Any) -> Any: - """Pass the group's set defaults down into each raw source.""" - if not isinstance(data, dict) or not isinstance(data.get("source"), list): - return data - (source_type,) = get_args(cls.model_fields["source"].annotation) - defaults: dict[str, Any] = {} - for name, field in cls.model_fields.items(): - if name == "source" or name not in source_type.model_fields: - continue - is_set, raw = raw_field(data, name, field) - if not is_set: - continue - try: - defaults[name] = TypeAdapter(field.rebuild_annotation()).validate_python(raw) - except ValidationError: - continue # the group field reports its own errors once, not once per source - data["source"] = [ - inherit_defaults(defaults, source) if isinstance(source, dict) else source for source in data["source"] - ] - return data - - -class TrainConfig(SourceGroupConfig): - source: list[TrainSourceConfig] = Field(default_factory=list) - """Training sources.""" - - sampling: Annotated[TrainSamplingConfig, Frozen()] = TrainSamplingConfig() - """Sampling that every training source inherits.""" - - select: vf.SelectConfig = vf.SelectConfig() - """Task selection that every training source inherits.""" - - group_size: int = Field(1, ge=1) - """Rollouts generated per example that every training source inherits unless it - sets its own. ``batch_size`` must be divisible by every source's group size.""" - - algo: Annotated[AlgoConfig, Frozen()] = GRPOAlgoConfig() - """Training algorithm that every training source inherits. Defaults to ``grpo``.""" - - @model_validator(mode="after") - def validate_unique_env_names(self): - env_names = [env.resolved_name for env in self.source] - duplicates = [n for n in env_names if env_names.count(n) > 1] - if duplicates: - raise ValueError( - f"Duplicate training environment names: {set(duplicates)}. Each env must have a unique name." - ) - return self - - -class EvalSourcesConfig(SourceGroupConfig): - """Eval sources and the defaults they inherit.""" - - source: list[EvalSourceConfig] = Field(default_factory=list) - """Evaluation sources.""" - - sampling: vf.SamplingConfig = Field(default_factory=vf.SamplingConfig) - """Sampling that every eval source inherits; can differ from training sampling.""" - - select: vf.SelectConfig = vf.SelectConfig() - """Task selection that every eval source inherits, e.g. ``limit = 128`` to evaluate - 128 tasks of each taskset.""" - - group_size: int = Field(1, ge=1) - """Rollouts per example that every eval source inherits.""" - - @model_validator(mode="after") - def validate_non_empty_sources(self): - if not self.source: - raise ValueError( - "At least one eval source is required. Add a source block " - "(e.g. [[source]] or [[orchestrator.eval.source]]) or drop the eval block entirely to disable eval." - ) - return self - - @model_validator(mode="after") - def validate_unique_env_names(self): - env_names = [source.resolved_name for source in self.source] - duplicates = [n for n in env_names if env_names.count(n) > 1] - if duplicates: - raise ValueError( - f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name." - ) - return self - - -class ScheduledEvalConfig(EvalSourcesConfig): - """Eval sources evaluated on a step interval next to training.""" - - source: list[OnlineEvalSourceConfig] = Field(default_factory=list) - """Evaluation sources, each with its own step interval.""" - - interval: int = Field(100, ge=1) - """Step interval that every eval source inherits.""" - - skip_first_step: bool = False - """If True, skip the startup eval that otherwise runs before any - train rollouts.""" - - retrigger_on_resume: bool = False - """If True, re-trigger evals at the checkpoint step on resume (e.g. after a - crash that left in-flight evals unfinished). By default, assumes a clean - exit where all evals already completed.""" - - @property - def intervals(self) -> dict[str, int]: - """Step interval per eval env, by resolved name.""" - return {source.resolved_name: source.interval for source in self.source} - - -class RLOnlineEvalConfig(ScheduledEvalConfig): - """The ``[orchestrator.eval]`` block: online evals against the orchestrator's - inference pool, on the policy the train rollouts see.""" - - -class CheckpointConfig(BaseCheckpointConfig): - rollouts: bool = False - """Also checkpoint the pipeline: the finished but unshipped train episodes, and the - running train rollouts, each as a memory checkpoint of its sandbox. A resumed run - continues them, so it starts with the batches the checkpointed run would have - shipped. A rollout that cannot take a memory checkpoint starts over. The checkpoint - of step N is then written when the trainer publishes the weights of N, not when N - ships. Eval rollouts are never checkpointed.""" - - rollouts_save_timeout: int = Field(120, ge=1) - """Seconds each running train rollout gets to take its memory checkpoint. A rollout - that takes longer has no restore point and starts over on resume. The trainer - waits in its weight broadcast for the whole save. The save takes at most this - long, plus the time the env worker pools take to write the restore files.""" - - -class ConcurrencyConfig(BaseConfig): - """Adaptive in-flight concurrency control. The orchestrator sizes the - in-flight episode cap from engine load; these fields only bound and - seed it.""" - - initial_inflight: Annotated[int | None, Live()] = Field(None, ge=1) - """Optional initial in-flight episodes to start from. Set it when a good value is known to skip the initial ramp; otherwise auto-derive a pessimistic bound at runtime.""" - - min_inflight: Annotated[int, Live()] = Field(1, ge=1) - """Minimum number of in-flight episodes. Set ``min_inflight = max_inflight`` to recover fixed concurrency.""" - - max_inflight: Annotated[int | None, Live()] = Field(None, ge=1) - """Maximum number of in-flight episodes. None (the default) leaves the cap to the controller. Set it to bound other external resources the episodes hold (e.g. sandboxes).""" - - @model_validator(mode="after") - def validate_bounds(self): - if self.max_inflight is not None: - if self.initial_inflight is not None and self.initial_inflight > self.max_inflight: - raise ValueError("concurrency.initial_inflight must not exceed concurrency.max_inflight") - if self.min_inflight > self.max_inflight: - raise ValueError("concurrency.min_inflight must not exceed concurrency.max_inflight") - return self - - -# Top-k set on truncated policy sampling that has none: the kept ids of every sampled token travel to the -# trainer, and top-p alone can keep most of the vocabulary on a flat distribution. -TRAIN_TOP_K_DEFAULT = 10000 - - -class OrchestratorControlConfig(ControlConfig): - port: int = Field(8041, ge=1, le=65535) - """Port the control API listens on, next to the trainer's 8040 on a single node.""" - - -class SpeculativeDecodingConfig(BaseConfig): - draft: Annotated[Path, Live()] - """Draft checkpoint the inference engines serve; at launch, the one they started with. A live update - loads the new draft on every engine at the next policy weight sync. It must keep the served draft's - architecture and tensor shapes. A failed load restores the previous draft and reverts this value.""" - - -class OrchestratorConfig(BaseConfig): - model: ModelConfig = ModelConfig() - """The model being trained: its model fields plus the client of the live - vLLM deployment (``[orchestrator.model] name = ...`` with - ``[orchestrator.model.client]``). Algorithm components reference it as - ``"policy"``.""" - - train: TrainConfig = TrainConfig() - - tokenizer: TokenizerConfig = TokenizerConfig() - - renderer: RendererConfig = AutoRendererConfig() - """Typed renderer config (``renderers.RendererConfig`` discriminated union), required — - training is renderer-only. Defaults to ``"auto"``, which resolves from - ``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.""" - - eval: RLOnlineEvalConfig | None = None - """Evaluation configuration.""" - - log: LogConfig = LogConfig() - - env_vars: EnvVars = {} - """Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults.""" - - monitors: MonitorsConfig = MonitorsConfig() - """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).""" - - collect_inference_metrics: bool = True - """Mirror inference-server metrics to W&B (requires wandb). The ``/metrics`` poll itself always runs — it feeds the concurrency controller.""" - - inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None - """P/D role of each policy admin client: labels inference metrics, and prefill engines pause before decode engines on weight updates.""" - - ckpt: CheckpointConfig | None = None - """Checkpoint configuration.""" - - resume: ResumeConfig | None = None - """Resume the orchestrator from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints.""" - - weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig() - """Transport used to receive updated weights from the trainer.""" - - rollout_transport: ZMQTransportConfig = ZMQTransportConfig() - """Transport used to ship rollouts from orchestrator to trainer.""" - - env_worker_pool_replicas: int | None = Field(None, ge=1) - """Replicas of each launcher-managed env worker pool, each publishing its address to - ``..address``; the orchestrator spreads each source's episodes over them, - least loaded first. None means one pool publishing to ``.address``. Set by the - ``rl`` launcher: multi-node runs start one replica per inference node, so pool - memory spreads over all of them.""" - - output_dir: Path = Field(default_factory=default_output_dir) - """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. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" - - dispatch_per_minute: int | None = Field(None, ge=1) - """Rate limit on episode dispatch, shared by train and eval: at most this many episodes start per minute. Each episode counts once, so a group of ``group_size`` episodes counts ``group_size`` times. Recommended for sandbox-backed environments to pace provisioning during autoscaling. None disables it.""" - - batch_size: Annotated[int, Live()] = Field(128, ge=1) - """Samples to train on per step.""" - - constant_trainer_batch_size: bool = True - """Require each batch to reach its effective sample target.""" - - concurrency: ConcurrencyConfig = ConcurrencyConfig() - """Adaptive in-flight concurrency control (``[orchestrator.concurrency]``).""" - - gc: GCConfig | None = GCConfig() - """Garbage collection config. Freezes the startup heap, turns off automatic full collections (each one holds the GIL and stalls the event loop for as long as it takes to walk every held episode) and runs one every N steps instead. Young collections still run. Set to null to use Python's default GC behavior.""" - - seq_len: int = 2048 - """Training sequence length. Shorter samples are padded; longer samples are truncated.""" - - max_steps: int | None = None - """Maximum training steps. If None, runs indefinitely.""" - - max_staleness: Annotated[int, Live()] = Field(8, ge=0) - """Maximum token staleness: the version a batch trains on (v{step-1}) minus the policy version that sampled the token, queue time included. Engines label each sampled token with the policy step (vLLM ``weight_versions``); unlabelled tokens (Dynamo engines) count as old as their episode's dispatch version. Older tokens are masked out of every loss component; the rest of the sample still trains with its own advantage and inference logprobs. A sample is dropped only when nothing is left to train. Rollouts are never cancelled for staleness, unless ``strict_staleness`` is set. Higher values yield better throughput at the cost of noisier, more off-policy updates.""" - - strict_staleness: Annotated[bool, Live()] = False - """Bound the staleness of every KV a trained token attends to, not only of the trained tokens. A train rollout counts as old as the policy version it was dispatched with, since its prompt and early-turn KVs come from that version. The orchestrator drops whole rollouts past ``max_staleness``: queued rollouts at the queue sweep, and in-flight groups before each weight update, which also saves their inference. Fresher tokens of a dropped rollout never train.""" - - heartbeat: HeartbeatConfig | None = None - """BetterStack heartbeat configuration for monitoring training progress.""" - - control: OrchestratorControlConfig | None = None - """Serve the orchestrator's control API (pause or checkpoint at a step the trainer - accepted, update the config live). If None, it takes no control requests.""" - - speculative_decoding: SpeculativeDecodingConfig | None = None - """Draft model served by the policy engines. Auto-filled by the ``rl`` entrypoint from the inference - servers' speculative config; set it for standalone orchestrator runs that should swap drafts.""" - - def dynamo_sampling_conflict(self) -> str | None: - """Why the policy sampling cannot run on Dynamo engines, or None. Dynamo's sidecar rejects - prime-rl's request extensions (``extra_args``), which sampling replay and logprob heads use.""" - for sampling in self.policy_samplings: - if sampling.truncates_distribution(): - return f"truncated sampling (top_p = {sampling.top_p}, top_k = {sampling.top_k}) needs sampling replay" - if sampling.logprobs: - return f"a logprob head (sampling.logprobs = {sampling.logprobs}, also set by score centering)" - return None - - @model_validator(mode="after") - def validate_dynamo_sampling(self): - dynamo = self.model.client.dynamo - if dynamo is not None and dynamo.enabled and (conflict := self.dynamo_sampling_conflict()): - raise ValueError(f"Dynamo engines cannot serve {conflict}: their sidecar rejects prime-rl's extra_args") - return self - - @model_validator(mode="after") - def validate_draft_swaps(self): - dynamo = self.model.client.dynamo - if self.speculative_decoding is not None and dynamo is not None and dynamo.enabled: - raise ValueError("Draft swaps use prime-rl's engine admin routes, which Dynamo deployments do not serve") - return self - - @model_validator(mode="after") - def auto_setup_tokenizer(self): - if self.tokenizer.name is None: - self.tokenizer.name = self.model.name - if self.tokenizer.trust_remote_code is None: - self.tokenizer.trust_remote_code = self.model.trust_remote_code - return self - - @model_validator(mode="after") - def auto_setup_prime_monitor_name(self): - """Default ``monitors.prime.name`` to the W&B run name when monitoring - is enabled and the user hasn't named the platform run explicitly.""" - if self.monitors.prime is None or self.monitors.prime.name is not None: - return self - if self.monitors.wandb is not None and self.monitors.wandb.name: - self.monitors.prime.name = self.monitors.wandb.name - return self - - @model_validator(mode="after") - def validate_env_algorithms(self): - """Let each algorithm reject environments it cannot score correctly.""" - for env_cfg in self.train.source: - env_cfg.algo.validate_env(env_cfg.env) - return self - - @model_validator(mode="after") - def validate_loss_aggregation(self): - """The trainer divides the rl loss by the batch's summed rl weights, so token-mean (weight - 1 per token) and prompt-mean (weight 1 per group) envs can't share a batch.""" - algos = [env.algo for env in self.train.source if env.algo.action_loss_type == "rl"] - aggregations = {algo.loss_aggregation if isinstance(algo, GRPOAlgoConfig) else "token" for algo in algos} - if len(aggregations) > 1: - raise ValueError( - "All train envs with an rl loss must use the same loss_aggregation: a prompt-mean group " - "would weigh as much as a single token of a token-mean env." - ) - return self - - @model_validator(mode="after") - def setup_truncated_sampling(self): - """Truncated policy sampling trains with sampling replay (rollout - logprobs are renormalized — see docs/inference.md, Sampling Replay). - Owned here: every truncating config gets a top-k (bounds the replayed supports); opd/opsd - is rejected (full-vocab prefill refs would mix normalizations). Frozen-source envs sample - externally and are exempt.""" - truncating = [sampling for sampling in self.policy_samplings if sampling.truncates_distribution()] - if not truncating: - return self - - if any(sampling.temperature == 0 for sampling in truncating): - raise ValueError( - "Truncated train sampling (top_p/top_k) requires temperature > 0: greedy sampling has " - "no truncated distribution to replay, and the inference server rejects such requests " - "while sampling-mask capture is on." - ) - - algos = [env.algo for env in self.train.source] or [self.train.algo] - if any(algo.type in ("opd", "opsd") for algo in algos): - raise ValueError( - "opd/opsd is not supported with truncated train sampling: reference logprobs are full-vocab " - "prefill scores while trainer logprobs are renormalized over the sampling mask, biasing the " - "ref_kl term. Remove the truncation (top_p/top_k) or the opd/opsd algo." - ) - - if any(sampling.top_k is None for sampling in truncating): - warnings.warn( - f"Truncated train sampling: defaulting top_k = {TRAIN_TOP_K_DEFAULT} so every replayed " - "support is bounded. Set top_k explicitly to override.", - stacklevel=2, - ) - self.update_policy_samplings( - lambda sampling: ( - sampling.model_copy(update={"top_k": TRAIN_TOP_K_DEFAULT}) - if sampling.truncates_distribution() and sampling.top_k is None - else sampling - ) - ) - - return self - - @property - def policy_samplings(self) -> list[TrainSamplingConfig]: - """Sampling of each train source that samples from the policy, else the group's when - there are no sources.""" - if not self.train.source: - return [self.train.sampling] - return [env.sampling for env in self.train.source if env.algo.rollout_model == "policy"] - - def update_policy_samplings(self, update: Callable[[TrainSamplingConfig], TrainSamplingConfig]) -> None: - """Replace each of ``policy_samplings`` with ``update(sampling)``. The group's sampling is - a frozen field, so its config is copied rather than assigned.""" - if not self.train.source: - self.train = self.train.model_copy(update={"sampling": update(self.train.sampling)}) - for env in self.train.source: - if env.algo.rollout_model == "policy": - env.sampling = update(env.sampling) - - @property - def any_policy_sourced(self) -> bool: - """True when at least one train env samples rollouts from the live policy.""" - return any(env.algo.rollout_model == "policy" for env in self.train.source) - - @model_validator(mode="after") - def validate_renderer_auto_resolves(self): - """Reject the silent DefaultRenderer fallback at config time. - - When ``renderer.name='auto'`` and the model isn't in - ``MODEL_RENDERER_MAP``, ``create_renderer`` would fall back to - ``DefaultRenderer``. That fallback doesn't fix the - position-dependent chat-template bug the renderer client exists - to solve, and rejects envs that pass tools (the rollout dies - with "RendererPool does not support tools") unless - ``DefaultRendererConfig.tool_parser`` is configured. Surface at - config time so ``--dry-run`` reports the error. - """ - if self.renderer.name != "auto": - return self - from renderers.base import MODEL_RENDERER_MAP - - model_id = self.tokenizer.name or self.model.name - if model_id in MODEL_RENDERER_MAP: - return self - raise ValueError( - f"orchestrator.renderer.name='auto' but " - f"{model_id!r} is not in renderers.base.MODEL_RENDERER_MAP, so it " - f"would silently fall back to DefaultRenderer. Pick one: " - f"(a) [orchestrator.renderer] name='default' — for fine-tunes / " - f"vendored mirrors with custom chat templates (DefaultRenderer " - f"calls apply_chat_template); set tool_parser= if the env " - f"uses tools. " - f"(b) [orchestrator.renderer] name= — " - f"if {model_id!r} is template-identical to a mapped family " - f"(and ideally also add it upstream to " - f"renderers.base.MODEL_RENDERER_MAP)." - ) - - @model_validator(mode="after") - def resolve_batching(self): - group_sizes = [source.group_size for source in self.train.source] or [self.train.group_size] - if any(self.batch_size % size for size in group_sizes): - raise ValueError( - f"Batch size {self.batch_size} must be divisible by every train source's group_size {sorted(set(group_sizes))}" - ) - - for field in ("max_inflight", "initial_inflight"): - value = getattr(self.concurrency, field) - if value is not None and value < max(group_sizes): - raise ValueError( - f"concurrency.{field} must be at least the largest train group_size ({max(group_sizes)})" - ) - - return self - - @model_validator(mode="after") - def resolve_sampling_replay(self): - """Opt policy train sources into replay and keep eval sampling independent.""" - for env in self.train.source: - # Only truncated policy sampling needs replay. Frozen-sourced rollouts may hit external - # OAI endpoints, and policy engines without prime-rl's extension (Dynamo), that reject the flag. - if env.algo.rollout_model == "policy" and env.sampling.truncates_distribution(): - extra_args = dict(env.sampling.extra_body.get("extra_args") or {}) - extra_args["prl_replay"] = True - env.sampling.extra_body["extra_args"] = extra_args - if self.eval is not None: - for env in self.eval.source: - if getattr(env.sampling, "top_k", None) is None: - env.sampling.top_k = -1 - env.sampling.logprobs = None - return self - - @property - def env_sources(self) -> list[tuple[str, EnvConfig]]: - """Every ``(split, source)`` this run pulls from, train first then eval — the - order used by the launcher to write per-source pool configs.""" - sources: list[tuple[str, EnvConfig]] = [("train", source) for source in self.train.source] - if self.eval is not None: - sources += [("eval", source) for source in self.eval.source] - return sources - - @property - def managed_env_sources(self) -> list[tuple[str, EnvConfig]]: - """``(split, source)`` for every source whose env worker pool the run starts: those - without ``serve.address``. A source with one is externally managed — its pool runs - elsewhere and only the orchestrator connects to it.""" - return [(split, source) for split, source in self.env_sources if source.serve.address is None] - - @property - def env_addresses(self) -> dict[tuple[str, str], str | None]: - """Where each source's env worker pool lives, keyed by ``(split, resolved_name)``: the - source's own ``serve.address`` when set (an externally managed pool), else None — - the launcher starts the pool, whose broker binds an OS-assigned port and publishes it - to the source's address file for the orchestrator to pick up.""" - return {(split, source.resolved_name): source.serve.address for split, source in self.env_sources} diff --git a/packages/prime-rl-configs/src/prime_rl/configs/pretrain.py b/packages/prime-rl-configs/src/prime_rl/configs/pretrain.py deleted file mode 100644 index 24f4bb1bc65..00000000000 --- a/packages/prime-rl-configs/src/prime_rl/configs/pretrain.py +++ /dev/null @@ -1,119 +0,0 @@ -from pathlib import Path -from typing import Annotated, Literal, TypeAlias - -from pydantic import Field, model_validator - -from prime_rl.configs.supervised import ( - BaseDataConfig, - BaseSourceConfig, - SupervisedTrainerConfig, - ValConfig, - check_sources, -) -from prime_rl.configs.trainer import ( - AdamWConfig, - ConstantSchedulerConfig, - CosineSchedulerConfig, - InitConfig, - LinearSchedulerConfig, - ModelConfig, - MuonConfig, - ScratchInit, - SignSGDConfig, -) - - -class TokenSourceConfig(BaseSourceConfig): - """A folder of datatrove tokenized shards, one source of the training data.""" - - path: Path - """Folder of ``*.ds`` token files, each with its ``.ds.index`` and ``.ds.metadata``.""" - - repetitions: float | None = Field(None, ge=1) - """How often every token of a fixed subset of the source is seen over the run (needs ``max_steps``). If None, the - whole source is read.""" - - -class PretrainDataConfig(BaseDataConfig): - """Training shards: documents sampled from one or more sources into rows of ``seq_len`` tokens.""" - - type: Literal["datatrove"] = "datatrove" - - source: list[TokenSourceConfig] = Field(min_length=1) - """The folders to sample documents from (``[[data.source]]``).""" - - seed: int = Field(0, ge=0) - """Seed for the order of the documents, within rows too, and for the subsets.""" - - document_masking: bool = True - """Attention and positions restart at every document and piece. If False, a row is one sequence.""" - - eod_mask_loss: bool = True - """Don't train the model to predict the first token of the next, unrelated document: no loss where the input is - the document separator. The separator is the special token the training shards' documents end with, detected at - startup; startup fails if they don't all end with one, unless they start with BOS (then there is nothing to - mask).""" - - @model_validator(mode="after") - def validate_sources(self): - check_sources(self.source) - return self - - -class PretrainAdamWConfig(AdamWConfig): - lr: float = Field(1e-3, ge=0) - """Peak learning rate. Defaults to PyTorch's AdamW default.""" - - -class PretrainMuonConfig(MuonConfig): - lr: float = Field(1e-3, ge=0) - """Peak learning rate. Defaults to 1e-3, as for AdamW.""" - - -PretrainOptimizerConfig: TypeAlias = Annotated[ - PretrainAdamWConfig | PretrainMuonConfig | SignSGDConfig, Field(discriminator="type") -] - - -class PretrainLinearSchedulerConfig(LinearSchedulerConfig): - decay_steps: int = Field(0, ge=0) - """Steps to decay the learning rate during the final portion of training. Defaults to 0: a decay needs - ``max_steps``.""" - - -PretrainSchedulerConfig: TypeAlias = Annotated[ - ConstantSchedulerConfig | PretrainLinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type") -] - - -class PretrainModelConfig(ModelConfig): - init: InitConfig = ScratchInit() - - -class PretrainConfig(SupervisedTrainerConfig): - """Pretraining: next-token loss on tokenized shards, with the weights initialized from scratch by default.""" - - model: PretrainModelConfig = PretrainModelConfig() - - mode: Literal["pretrain"] | None = None - """Run kind of this config. ``uv run launch`` picks the entrypoint from it; ``uv run pretrain`` accepts only - "pretrain" (or no mode).""" - - data: PretrainDataConfig - - val: ValConfig | None = None - """Validation on held-out document sets. If None, no validation runs.""" - - optim: PretrainOptimizerConfig = PretrainAdamWConfig() - - scheduler: PretrainSchedulerConfig = PretrainLinearSchedulerConfig() - """Learning rate schedule. Defaults to a linear warmup over 10 steps, then constant: from a random init, Adam's - first updates at the full learning rate are unstable.""" - - @model_validator(mode="after") - def validate_repetitions(self): - if self.max_steps is None and any(source.repetitions is not None for source in self.data.source): - raise ValueError( - "data.source: repetitions sizes a source's subset by the run's tokens, so it needs max_steps" - ) - return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/router.py b/packages/prime-rl-configs/src/prime_rl/configs/router.py deleted file mode 100644 index 5ac06b9f7aa..00000000000 --- a/packages/prime-rl-configs/src/prime_rl/configs/router.py +++ /dev/null @@ -1,25 +0,0 @@ -from pydantic import ConfigDict, Field - -from prime_rl.configs.inference import ( - InferenceDeploymentConfig, - RouterConfig, - ServerConfig, - SingleNodeInferenceDeploymentConfig, - VllmConfig, - VllmRouterConfig, -) -from prime_rl.utils.config import BaseConfig - - -class RouterEntrypointConfig(BaseConfig): - model_config = ConfigDict(extra="ignore") - - server: ServerConfig = ServerConfig() - router: RouterConfig | None = Field(default_factory=VllmRouterConfig) - vllm: VllmConfig = Field(default_factory=VllmConfig) - deployment: InferenceDeploymentConfig = SingleNodeInferenceDeploymentConfig() - worker_urls: list[str] = Field(default_factory=list) - prefill_urls: list[str] = Field(default_factory=list) - decode_urls: list[str] = Field(default_factory=list) - intra_node_data_parallel_size: int | None = Field(default=None, ge=1) - prometheus_port: int | None = Field(default=None, ge=1, le=65535) diff --git a/packages/prime-rl-configs/src/prime_rl/configs/sft.py b/packages/prime-rl-configs/src/prime_rl/configs/sft.py deleted file mode 100644 index 07f50f440d9..00000000000 --- a/packages/prime-rl-configs/src/prime_rl/configs/sft.py +++ /dev/null @@ -1,172 +0,0 @@ -from typing import Any, Literal - -from pydantic import Field, model_validator -from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig -from renderers.base import MODEL_RENDERER_MAP - -from prime_rl.configs.supervised import ( - BaseDataConfig, - BaseSourceConfig, - BaseValConfig, - SupervisedTrainerConfig, - check_sources, -) -from prime_rl.utils.config import BaseConfig - - -class LossMaskConfig(BaseConfig): - system: bool = False - """System messages contribute to the loss.""" - - user: bool = False - """User messages contribute to the loss.""" - - assistant: bool = True - """Assistant messages contribute to the loss.""" - - tool: bool = False - """Tool messages contribute to the loss.""" - - -class SFTColumnsConfig(BaseConfig): - """Dataset columns the trainer reads. Set a field to read a column under another name.""" - - messages: str = "messages" - """Column with the whole chat as a list of OpenAI chat messages.""" - - prompt: str = "prompt" - """Column with the prompt as a list of OpenAI chat messages, read with ``completion`` when a row has no messages.""" - - completion: str = "completion" - """Column with the completion as a list of OpenAI chat messages.""" - - tools: str = "tools" - """Column with the tool schemas in OpenAI function-calling format.""" - - message_loss_mask: str = "message_loss_mask" - """Optional column of booleans or integer 0/1 flags, one per resolved message (prompt + completion for split rows). Zero excludes a message from loss; one preserves its normal supervision. Missing or null masks leave supervision unchanged.""" - - renderer: dict[str, str] = {"reasoning_effort": "reasoning_effort"} - """Per-sample renderer arguments as ``renderer field = dataset column``, e.g. ``reasoning_effort = "effort"``. A row's non-null value overrides the ``[renderer]`` setting; rows and datasets without the column use it unchanged.""" - - -class HFDatasetSourceConfig(BaseSourceConfig): - """One ``(dataset, subset, split)`` of a Hugging Face dataset.""" - - dataset: str - """HF dataset name or local path.""" - - revision: str | None = None - """HF dataset revision to load. Ignored for a local path.""" - - subset: str | None = None - """Subset (config name) of the dataset.""" - - split: str = "train" - """Split of the dataset.""" - - columns: SFTColumnsConfig | None = None - """Columns of this source. Unset fields keep ``data.columns``.""" - - renderer: dict[str, Any] = {} - """Chat-template kwargs for this source's rows, applied over ``[renderer]`` and under a row's ``columns.renderer`` - values, e.g. ``{ reasoning_effort = "high" }``.""" - - -class FakeDataConfig(BaseConfig): - """Synthetic token sequences of up to ``data.seq_len`` tokens, for throughput and plumbing tests.""" - - length: Literal["fixed", "variable"] = "fixed" - """Use fixed-length samples or variable-length samples.""" - - input_ids: Literal["increasing", "random"] = "increasing" - """Token id generator: ``increasing`` for deterministic sequences, ``random`` for random ids.""" - - -class SFTDataConfig(BaseDataConfig): - """Samples drawn from one or more sources into packed rows of ``seq_len`` tokens.""" - - source: list[HFDatasetSourceConfig] = Field( - default_factory=lambda: [HFDatasetSourceConfig(name="reverse-text", dataset="PrimeIntellect/Reverse-Text-SFT")], - min_length=1, - ) - """The sources to draw samples from (``[[data.source]]``).""" - - fake: FakeDataConfig | None = None - """Train on synthetic token sequences instead of the sources. Needs no renderer.""" - - shuffle: bool = True - """Shuffle every source at the start of each of its passes.""" - - seed: int = 0 - """Seed for the order of every source, re-shuffled per pass by adding the pass count, and for fake tokens.""" - - columns: SFTColumnsConfig = SFTColumnsConfig() - """Columns of every source. A source's ``columns`` override single fields.""" - - loss_mask: LossMaskConfig = LossMaskConfig() - """Which message types contribute to the loss.""" - - @model_validator(mode="after") - def validate_sources(self): - check_sources(self.source) - for source in self.source: - overrides = source.columns.model_dump(exclude_unset=True) if source.columns is not None else {} - source.columns = SFTColumnsConfig.model_validate({**self.columns.model_dump(), **overrides}) - return self - - -class SFTValConfig(BaseValConfig): - data: SFTDataConfig - - @model_validator(mode="after") - def validate_sources(self): - if self.data.fake is not None: - raise ValueError("val.data.fake: validation scores the rows of its sources, not fake data") - return self - - -class SFTConfig(SupervisedTrainerConfig): - mode: Literal["sft"] | None = None - """Run kind of this config. ``uv run launch`` picks the entrypoint from it; ``uv run sft`` accepts only - "sft" (or no mode).""" - - renderer: RendererConfig = AutoRendererConfig() - """Renderer config. Defaults to auto-selecting from the tokenizer model name.""" - - data: SFTDataConfig = SFTDataConfig() - - val: SFTValConfig | None = None - """Validation configuration. If None, no validation runs.""" - - @model_validator(mode="after") - def validate_typed_renderer(self): - """Require a typed renderer whenever SFT renders real samples.""" - if self.data.fake is not None and self.val is None: - return self - - model_id = self.tokenizer.name or self.model.name - if isinstance(self.renderer, AutoRendererConfig): - if model_id in MODEL_RENDERER_MAP: - return self - reason = f"no typed renderer is registered for {model_id!r}" - elif isinstance(self.renderer, DefaultRendererConfig): - reason = "renderer.name='default' selects DefaultRenderer" - else: - return self - - raise ValueError( - f"SFT requires a typed renderer with sampled-token and content attribution, but {reason}. " - "Implement and register the renderer in the renderers package, or explicitly select an existing " - "typed renderer only when its template is verified to match." - ) - - @model_validator(mode="after") - def validate_vlm_constraints(self): - if self.model.vlm is None: - return self - if self.data.micro_batch_size != 1: - raise ValueError("VLM SFT requires data.micro_batch_size = 1.") - if self.val is not None and self.val.data.micro_batch_size != 1: - raise ValueError("VLM SFT requires val.data.micro_batch_size = 1.") - return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/shared.py b/packages/prime-rl-configs/src/prime_rl/configs/shared.py deleted file mode 100644 index 28f993086b9..00000000000 --- a/packages/prime-rl-configs/src/prime_rl/configs/shared.py +++ /dev/null @@ -1,355 +0,0 @@ -import os -import re -from pathlib import Path -from typing import Annotated, Literal, TypeAlias - -from pydantic import AfterValidator, Field, model_validator -from verifiers.v1.configs.client import BaseClientConfig - -from prime_rl.utils.config import BaseConfig - -# Launcher-managed env vars that a component's `env_vars` must not set: GPU partitioning -# and the single shared W&B run. The launcher always sets these last, so allowing them in -# `env_vars` would be a silent no-op (or, on multi-node, a footgun) — reject them instead. -PROTECTED_ENV_VARS = frozenset( - { - "CUDA_VISIBLE_DEVICES", - "PRL_RUN_ID", - "PRL_RUN_NAME", - "WANDB_RUN_ID", - "WANDB_SHARED_MODE", - "WANDB_SHARED_LABEL", - "WANDB_SHARED_PRIMARY", - "WANDB_SHARED_FINISHER", - } -) - - -def reject_protected_env_vars(env_vars: dict[str, str]) -> dict[str, str]: - clobbered = sorted(PROTECTED_ENV_VARS & env_vars.keys()) - if clobbered: - raise ValueError( - f"env_vars cannot set launcher-managed vars {clobbered} — set by the launcher, not overridable" - ) - return env_vars - - -EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_env_vars)] -"""A per-component `env_vars` mapping, validated to not clobber `PROTECTED_ENV_VARS`.""" - - -class BaseWeightBroadcastConfig(BaseConfig): - timeout: int = 3600 - """Timeout in seconds for the broadcast handshake and transfer, including the orchestrator's wait - for the trainer's startup broadcast. The trainer fails the run when no consumer acknowledges an - offered version in time. Raise it for large models on slow shared filesystems.""" - - -class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig): - type: Literal["filesystem"] = "filesystem" - - -class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig): - host: str = "localhost" - """Weight transfer host.""" - - port: int - """Weight transfer port.""" - - inference_world_size: int = Field(1, ge=1) - """Total inference workers across all servers. Set automatically by ``rl`` and ``sft``.""" - - -class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig): - type: Literal["nccl"] = "nccl" - - port: int = 29501 - """Port for the NCCL broadcast rendezvous.""" - - -class ModelExpressWeightBroadcastConfig(InMemoryWeightBroadcastConfig): - type: Literal["modelexpress"] = "modelexpress" - - port: int = 8001 - """ModelExpress gRPC port.""" - - metadata_port: int = 5655 - """Base port of the trainer's NIXL metadata listener. Each local rank listens on this plus its device id.""" - - staging_mode: Literal["COPY_TO_HOST", "COPY_TO_DEVICE", "IN_PLACE"] = "COPY_TO_HOST" - """Trainer storage policy passed to ModelExpress.""" - - staging_buffer_bytes: int | None = Field(None, gt=0) - """Receiver staging capacity per buffer. None stages a complete update.""" - - staging_buffers_count: int = Field(1, ge=1) - """Number of receiver buffers. Two overlap the next read with installation.""" - - -WeightBroadcastConfig: TypeAlias = Annotated[ - FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | ModelExpressWeightBroadcastConfig, - Field(discriminator="type"), -] -"""Weight transfer from trainer to inference. ``rl`` copies its ``[weight_broadcast]`` to the trainer and orchestrator.""" - - -class BaseDeploymentConfig(BaseConfig): - gpus_per_node: int = 8 - """GPUs per node.""" - - -class BaseSingleNodeDeploymentConfig(BaseDeploymentConfig): - type: Literal["single_node"] = "single_node" - - num_train_gpus: int = 1 - """GPUs allocated to the trainer.""" - - num_infer_gpus: int = 1 - """GPUs allocated to inference. ``sft`` uses them only for online evals with an ``[inference]`` block.""" - - -class BaseMultiNodeDeploymentConfig(BaseDeploymentConfig): - type: Literal["multi_node"] = "multi_node" - - num_train_nodes: int = Field(ge=1) - """Training nodes.""" - - -class RunConfig(BaseConfig): - name: str | None = None - """Run name. Auto-generated as ``----`` when unset, so every launch gets a fresh, readable run directory; set an explicit name (e.g. an experiment name) to get a predictable run directory, which is also required to resume a previous run. Unless set explicitly, the W&B run name and the Prime platform run name inherit it.""" - - dir: str | None = None - """Run directory name — the run writes all its artifacts to ``output_dir / dir``. Defaults to ``run.name``; set it only when the directory should differ from the display name.""" - - -class BaseCheckpointConfig(BaseConfig): - output_dir: Path | None = None - """Override directory for checkpoints. If set, checkpoints are written here instead of under the run's - ``output_dir``, e.g. on a separate storage volume. In an RL run the trainer and the orchestrator each write - their half of a step here.""" - - interval: int | None = Field(None, ge=1) - """Step interval at which to save checkpoints.""" - - 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.""" - - keep_interval: int | None = Field(None, ge=1) - """Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping.""" - - -def ckpt_output_dir(output_dir: Path, ckpt_config: BaseCheckpointConfig | None) -> Path: - """Where a run's checkpoints live: ``ckpt.output_dir`` when set, else the run's ``output_dir``.""" - return (ckpt_config.output_dir if ckpt_config else None) or output_dir - - -class ControlConfig(BaseConfig): - host: str = "0.0.0.0" - """Address the control API binds to.""" - - port: int = Field(8040, ge=1, le=65535) - """Port the control API listens on.""" - - admin_token_var: str = "PRIME_RL_ADMIN_TOKEN" - """Name of the environment variable holding the run's admin token. When it, or ``_SHA256`` holding the token's SHA-256 digest, is set, every control request must carry the token in the ``X-Prime-Admin-Token`` header.""" - - -class ResumeConfig(BaseConfig): - """Resume the run from a checkpoint. A bare ``--resume`` (or empty ``[resume]`` block) - resumes from the latest checkpoint.""" - - step: int | None = Field(None, ge=1) - """Checkpoint step to resume from. None resumes from the latest checkpoint.""" - - dir: Path | None = None - """External checkpoint step directory to resume from (e.g. ``other/run/checkpoints/step_50``) — forks another run's checkpoint into this run. Mutually exclusive with ``step``.""" - - @model_validator(mode="after") - def validate_step_xor_dir(self): - if self.step is not None and self.dir is not None: - raise ValueError( - "resume.step and resume.dir are mutually exclusive — the step is taken from the directory name" - ) - if self.dir is not None: - validate_step_dir(self.dir, field="resume.dir") - return self - - @property - def dir_step(self) -> int: - """The step encoded in ``dir``'s name (validated to exist).""" - assert self.dir is not None - return int(self.dir.name.removeprefix("step_")) - - -class SlurmConfig(BaseConfig): - job_name: str | None = None - """SLURM job name. Defaults to ``run.name`` for ``rl`` and ``sft``, and to ``inference`` for ``inference``.""" - - project_dir: Path = Path(".") - """Path to the project root, used to source .env, activate .venv, and run uv sync.""" - - template_path: Path | None = None - """SLURM template file. If None, uses the bundled single-node or multi-node template.""" - - partition: str | None = None - """SLURM partition (#SBATCH --partition). If None, the job goes to the cluster's default partition.""" - - nodelist: str | None = None - """Comma-separated list of specific nodes to run on (#SBATCH --nodelist).""" - - exclude: str | None = None - """Comma-separated list of nodes to exclude (#SBATCH --exclude).""" - - account: str | None = None - """SLURM account to charge (#SBATCH --account).""" - - time: str | None = None - """Maximum wall time, e.g. '24:00:00' or '7-00:00:00' (#SBATCH --time).""" - - pre_run_command: str | None = None - """Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes.""" - - launch_modelexpress: bool = True - """Start a job-scoped ModelExpress server for ModelExpress weight broadcasts on multi-node jobs.""" - - cleanup_grace_period: int = Field(3600, ge=0) - """Maximum seconds a multi-node RL job that hit a non-zero exit waits for an in-flight trainer checkpoint to finish before tearing down. Without an in-flight checkpoint (or without ``[ckpt]``) it tears down immediately. Set to 0 to never wait.""" - - shared_fs: bool = True - """Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun.""" - - sync_args: str = "--all-extras --all-packages" - """Arguments of the ``uv sync`` the job runs before it starts. Narrow them to install less, e.g. ``--extra train`` for an SFT job without online evals. Set it in a TOML file: on the command line a value starting with ``--`` is read as a flag.""" - - @property - def template_vars(self) -> dict: - """Common template variables for all SLURM templates.""" - return { - "job_name": self.job_name, - "project_dir": self.project_dir, - "partition": self.partition, - "nodelist": self.nodelist, - "exclude": self.exclude, - "account": self.account, - "time": self.time, - "pre_run_command": self.pre_run_command, - "cleanup_grace_period": self.cleanup_grace_period, - "shared_fs": self.shared_fs, - "sync_args": self.sync_args, - } - - @model_validator(mode="after") - def resolve_project_dir(self): - self.project_dir = self.project_dir.resolve() - return self - - -class VLMConfig(BaseConfig): - freeze_vision_encoder: bool = True - """Freeze the vision encoder parameters during training.""" - - -class BaseModelConfig(BaseConfig): - name: str = "Qwen/Qwen3-0.6B" - """HF model name or local path.""" - - trust_remote_code: bool = False - """Trust remote code when initializing the tokenizer.""" - - -class DynamoConfig(BaseConfig): - enabled: bool = True - """Enable Dynamo worker discovery for the inference admin plane.""" - - discovery_url: str | None = Field(default=None, min_length=1, max_length=2048) - """Dynamo frontend URL used to discover inference workers for RL control.""" - - -ADMIN_TOKEN_HEADER = "X-Prime-Admin-Token" - - -class ClientConfig(BaseClientConfig): - wait_for_ready_timeout: int = 3600 - """Seconds to wait at startup for the inference pool to become ready.""" - - skip_model_check: bool = False - """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 multi-replica or disaggregated P/D deployments where the router must not handle admin traffic.""" - - admin_token_var: str | None = None - """Name of the environment variable holding the admin token of the inference servers. When it is set and non-empty, engine admin requests carry it in the ``X-Prime-Admin-Token`` header.""" - - -class VLLMClientConfig(ClientConfig): - """Client defaults for the live inference deployment managed by training.""" - - base_url: str = "http://localhost:8000/v1" - api_key_var: str = "VLLM_API_KEY" - admin_token_var: str | None = "PRIME_RL_ADMIN_TOKEN" - - -class PolicyClientConfig(VLLMClientConfig): - """Client of the policy deployment the orchestrator drives (weight updates, admin plane).""" - - dynamo: DynamoConfig | None = None - """Dynamo RL worker-discovery configuration.""" - - -class LogConfig(BaseConfig): - level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info")) - """Log level for the process and the verifiers library it runs, env worker pools included. - Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``.""" - - json_logging: bool = False - """Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.).""" - - log_data: bool = False - """Log the first data sample at startup.""" - - interval: float = Field(10.0, gt=0) - """Interval (seconds) for periodic logs across components.""" - - -class TrainerLogConfig(LogConfig): - ranks_filter: list[int] = [0] - """Trainer ranks to show in console output. Passed to ``torchrun --local-ranks-filter``.""" - - -class GCConfig(BaseConfig): - interval: int = Field(50, ge=1) - """Run a scheduled garbage collection every N training steps, in place of Python's automatic collections that would run at unpredictable times.""" - - -class HeartbeatConfig(BaseConfig): - url: str - """URL to send the heartbeat to.""" - - min_interval: float = Field(30.0, gt=0) - """Minimum seconds between pings. Beats can arrive far more often (evals beat once - per landed episode); surplus beats are dropped to stay under Better Stack's heartbeat - rate limit. Size it well under the monitor's period.""" - - -class ZMQTransportConfig(BaseConfig): - host: str = "localhost" - """Host address for ZMQ transport.""" - - port: int = 5555 - """Port for ZMQ transport.""" - - retain: bool = False - """Keep every shipped step, and the training arrays the env worker pools hold for it, - until a trainer checkpoint covers it, so a restarted trainer resumes from its newest - checkpoint and trains the steps since again. Needs a checkpoint interval, the filesystem - weight broadcast, a run directory the orchestrator and trainer share, and a rollout store - in every train env worker pool: the ``rl`` launcher sets ``store_dir`` for the pools it - starts, a pool started separately needs it in its own config.""" - - -def validate_step_dir(path: Path, *, field: str) -> None: - """Raise unless ``path`` names a checkpoint step directory (``.../step_``).""" - if not re.fullmatch(r"step_\d+", path.name): - raise ValueError(f"{field} must point at a checkpoint step directory (`.../step_`), got '{path}'") diff --git a/packages/prime-rl-configs/src/prime_rl/configs/supervised.py b/packages/prime-rl-configs/src/prime_rl/configs/supervised.py deleted file mode 100644 index 7ca372e8f2f..00000000000 --- a/packages/prime-rl-configs/src/prime_rl/configs/supervised.py +++ /dev/null @@ -1,458 +0,0 @@ -import uuid -import warnings -from pathlib import Path -from typing import Annotated, Literal, TypeAlias -from urllib.parse import urlparse - -from pydantic import Field, model_validator - -from prime_rl.configs.eval import SFTOnlineEvalConfig -from prime_rl.configs.inference import InferenceConfig, setup_dummy_load -from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig -from prime_rl.configs.monitors import MonitorsConfig -from prime_rl.configs.shared import ( - BaseMultiNodeDeploymentConfig, - BaseSingleNodeDeploymentConfig, - FileSystemWeightBroadcastConfig, - NCCLWeightBroadcastConfig, - ResumeConfig, - RunConfig, - SlurmConfig, - WeightBroadcastConfig, -) -from prime_rl.configs.trainer import BaseTrainerConfig, mega_moe_max_tokens_per_rank -from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource - - -class BaseDataConfig(BaseConfig): - batch_size: int = Field(128, ge=1) - """Global batch size.""" - - seq_len: int = Field(128, ge=1) - """Sequence length.""" - - micro_batch_size: int = Field(1, ge=1) - """Per-step micro batch size. ``batch_size`` must be divisible by this.""" - - num_workers: int = Field(1, ge=1) - """Number of dataloader worker processes. Batches are prepared and pinned in the background so tokenization/packing overlaps with training.""" - - pad_to_seq_len: bool = False - """Pad every packed row to ``seq_len * micro_batch_size`` instead of to a multiple of ``model.cp``. Rows then have - one static shape, which avoids recompilation on dynamic sequence lengths (torch.compile, DeepGEMM JIT kernels, ...) - at the cost of extra padding.""" - - @model_validator(mode="after") - def validate_batch_size(self): - if self.batch_size % self.micro_batch_size != 0: - raise ValueError("Batch size must be divisible by micro batch size") - if self.batch_size < self.micro_batch_size: - raise ValueError("Batch size must be greater than or equal to micro batch size") - return self - - -class BaseSourceConfig(BaseConfig): - """One named source of the training data (``[[data.source]]``), in pretraining and SFT.""" - - name: str = Field(pattern=r"^[^/]+$") - """Names the source in the ``progress//*`` metrics.""" - - weight: float | None = Field(None, ge=0) - """The source's relative weight: its share of the training data (tokens in pretraining, samples in SFT) is its - weight over the sum of all weights. If None on every source, the share is the source's share of all sources' data - (tokens in pretraining, rows in SFT).""" - - -def check_sources(sources: list[BaseSourceConfig]) -> None: - """Raise if two sources share a name, or the weights are set on only some sources or sum to 0.""" - names = [source.name for source in sources] - if len(set(names)) < len(names): - raise ValueError(f"data.source: the names must be unique, got {names}") - weights = [source.weight for source in sources] - if None in weights and any(weight is not None for weight in weights): - raise ValueError("data.source: set weight on every source or on none (natural shares)") - if None not in weights and sum(weights) <= 0: - raise ValueError("data.source: the weights must sum to more than 0") - - -class BaseValConfig(BaseConfig): - interval: int = Field(50, ge=1) - """Run validation every N training steps.""" - - eval_on_start: bool = False - """Run validation before the first training step.""" - - data: BaseDataConfig - - -class DocumentsValSetConfig(BaseConfig): - """Pre-tokenized documents. Every document is scored on its own, from its first token, in non-overlapping windows - of ``seq_len`` scored tokens: a longer document continues in the next window, which does not see the tokens - before it.""" - - type: Literal["documents"] = "documents" - - name: str = Field(pattern=r"^[^/]+$") - """Names the set's metrics, ``val//@``, e.g. ``val/fineweb-edu/bpb@2k``.""" - - path: Path - """Folder of datatrove tokenized shards, as for a pretraining source's ``path``. The tokens are scored as stored.""" - - seq_len: int | None = Field(None, ge=1) - """Context length: the most input tokens a scored sequence has. Defaults to the training ``data.seq_len``.""" - - -class ValConfig(BaseConfig): - interval: int = Field(50, ge=1) - """Run validation every N training steps.""" - - eval_on_start: bool = False - """Run validation before the first training step.""" - - set: list[DocumentsValSetConfig] = Field(min_length=1) - """The validation sets (``[[val.set]]``). Each logs ``val//loss@``, the mean loss per scored - token, and with a byte-level BPE tokenizer ``val//bpb@``, bits per UTF-8 byte of the scored - tokens.""" - - num_samples: int | None = Field(None, ge=1) - """Items per set and validation: the first ``num_samples`` documents of each set, the same ones every time. If - None, every item.""" - - micro_batch_tokens: int | None = Field(None, ge=1) - """Tokens per packed row of the sets (one forward pass). Defaults to the training micro-batch - (``data.seq_len * data.micro_batch_size``) or the longest set ``seq_len``, whichever is larger, rounded up to a - multiple of ``model.cp``; must be at least that longest ``seq_len``.""" - - save_arrays: bool = False - """Write the per-item arrays (npz) and summary (json) of every set to ``/val/step_N/``.""" - - @model_validator(mode="after") - def validate_unique_names(self): - names = [val_set.name for val_set in self.set] - if len(set(names)) < len(names): - raise ValueError(f"val.set names must be unique: {names}") - return self - - -class SingleNodeDeploymentConfig(BaseSingleNodeDeploymentConfig): - @model_validator(mode="after") - def validate_gpu_count(self): - if self.num_train_gpus > self.gpus_per_node: - raise ValueError(f"num_train_gpus ({self.num_train_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).") - return self - - -class MultiNodeDeploymentConfig(BaseMultiNodeDeploymentConfig): - num_infer_nodes: int = Field(0, ge=0) - """Inference nodes for online evals. These nodes share one SLURM allocation with the - trainer nodes.""" - - -SupervisedDeploymentConfig: TypeAlias = Annotated[ - SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type") -] - - -class SupervisedTrainerConfig(BaseTrainerConfig): - """SFT and pretraining: next-token loss on a fixed dataset, as opposed to RL.""" - - auto_freeze_moe_router = False - # Standard L2 regularization for supervised training. - auto_weight_decay = 0.01 - data: BaseDataConfig - - val: BaseValConfig | ValConfig | None = None - """Validation configuration. If None, no validation runs.""" - - eval: SFTOnlineEvalConfig | None = None - """Online evaluation configuration: rollout-based evals against a live inference - server that receives the trainer's weight broadcasts. If None, no online evals run.""" - - inference: InferenceConfig | None = None - """Inference server for online evals. If None (with ``eval`` set), the launcher - does not start a server and evals connect to ``eval.client.base_url``.""" - - weight_broadcast: WeightBroadcastConfig | None = None - """Trainer-to-inference weight transport for online evals. Defaults to NCCL; set - ``type = "modelexpress"`` to send weights through ModelExpress. LoRA and external - inference use filesystem broadcast.""" - - resume: ResumeConfig | None = None - """Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. The checkpoint supplies the training state; the hyperparameters and the learning rate schedule come from this config. If None, does not resume.""" - - monitors: MonitorsConfig = MonitorsConfig() - """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).""" - - run: RunConfig = Field(default_factory=RunConfig) - """Run metadata. ``run.name`` names the run directory under ``output_dir``.""" - - output_dir: Path = Field(default_factory=default_output_dir) - """Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" - - clean: bool = False - """Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming.""" - - @property - def run_dir(self) -> Path: - assert self.run.dir is not None # resolved at construction - return self.output_dir / self.run.dir - - @model_validator(mode="after") - def auto_setup_run_identity(self): - """Auto-generate the run name (``----``, with the source only if it is the only - one) when unset and default the run directory, W&B run name and platform run name to it when not set - explicitly.""" - if self.run.name is None: - sources = getattr(self.data, "source", []) - dataset = "fake" if getattr(self.data, "fake", None) else sources[0].name if len(sources) == 1 else "" - model = self.model.name.split("/")[-1] - parts = [part for part in (dataset, model) if part] - self.run.name = "--".join([*parts, uuid.uuid4().hex[:8]]).lower() - if self.run.dir is None: - self.run.dir = self.run.name - if self.monitors.wandb is not None and self.monitors.wandb.name is None: - self.monitors.wandb.name = self.run.name - if self.monitors.prime is not None and self.monitors.prime.name is None: - self.monitors.prime.name = self.run.name - return self - - deployment: SupervisedDeploymentConfig = SingleNodeDeploymentConfig() - - slurm: SlurmConfig | None = None - """SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally.""" - - dashboard: bool = True - """Make sure a local dashboard daemon serves this run's output dir (started on - demand in interactive sessions; an already-running daemon's URL is logged).""" - - dry_run: bool = False - """Only validate and dump resolved configs, then exit early.""" - - ### Pre-validation normalization - - @model_validator(mode="before") - @classmethod - def propagate_model_to_inference(cls, data): - """Fill ``inference.vllm.model`` and ``tokenizer`` from ``model.name`` and ``tokenizer.name`` before - InferenceConfig construction, so its parser auto-resolution sees the right names.""" - if not isinstance(data, dict): - return data - inference = data.get("inference") - if not isinstance(inference, dict): - return data - vllm = inference.setdefault("vllm", {}) - if not isinstance(vllm, dict): - return data - for section, key in (("model", "model"), ("tokenizer", "tokenizer")): - config = data.get(section) - name = config.get("name") if isinstance(config, dict) else None - if name: - vllm.setdefault(key, name) - return data - - ### Validate configs (e.g. raise for unsupported (combinations of) configs) - - @model_validator(mode="after") - def validate_deployment(self): - if self.deployment.type == "multi_node" and self.slurm is None: - raise ValueError("Must use SLURM for multi-node deployment.") - return self - - @model_validator(mode="after") - def auto_setup_online_eval(self): - """Wire online evals and the trainer-to-inference weight transport.""" - if self.eval is None: - if self.inference is not None: - raise ValueError("[inference] is only used for online evals — add an [eval] block or remove it.") - return self - - # LoRA runs broadcast the raw adapter, which evals reload via /load_lora_adapter - if self.model.lora is not None: - if self.inference is not None: - self.inference.vllm.enable_lora = True - self.inference.vllm.max_lora_rank = self.model.lora.rank - else: - warnings.warn( - "LoRA is enabled, but inference is not configured. When manually starting the inference server, " - "make sure to set --enable_lora and --max-lora-rank.", - stacklevel=2, - ) - - # A scratch init reaches the server with the trainer's startup broadcast. - if self.inference is not None: - setup_dummy_load(self.inference, self.model.init.type == "scratch") - - if self.weight_broadcast is None: - if self.model.lora is not None or self.inference is None: - self.weight_broadcast = FileSystemWeightBroadcastConfig() - else: - self.weight_broadcast = NCCLWeightBroadcastConfig() - if self.weight_broadcast.type != "filesystem" and self.model.lora is not None: - raise ValueError( - "LoRA training is not yet supported with in-memory weight broadcast. " - "Set weight_broadcast.type = 'filesystem'." - ) - - if self.deployment.type == "multi_node": - # Dedicated nodes in the SFT allocation run the inference pool, router, - # env worker pools, and evals process. - if self.inference is None: - raise ValueError( - "Multi-node online evals require an [inference] block - dedicated nodes in the " - "SFT allocation run the inference pool and evals process." - ) - if self.deployment.num_infer_nodes < 1: - raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.") - if self.inference.router is None: - raise ValueError( - "Multi-node online evals require an inference router - the launcher starts one " - "router in front of the per-rank engines. Remove inference.router = 'None'." - ) - if self.inference.vllm.model != self.model.name: - raise ValueError( - f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name " - f"({self.model.name}). Remove inference.vllm.model to inherit it." - ) - if self.deployment.gpus_per_node % self.inference.vllm.tensor_parallel_size != 0: - raise ValueError( - f"deployment.gpus_per_node ({self.deployment.gpus_per_node}) must be divisible by " - f"inference.vllm.tensor_parallel_size ({self.inference.vllm.tensor_parallel_size})." - ) - if self.weight_broadcast.type != "filesystem": - # Every inference GPU is an in-memory transfer worker. - self.weight_broadcast.inference_world_size = ( - self.deployment.num_infer_nodes * self.deployment.gpus_per_node - ) - self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type) - if self.max_steps is None: - warnings.warn( - "Online evals without max_steps: the evals process never sees a final checkpoint, " - "so the SFT SLURM job holds its allocation until its walltime.", - stacklevel=2, - ) - # The client is wired at runtime by the SFT sbatch script (the router and - # per-rank admin URLs are only known once SLURM assigns hosts). - return self - - if self.inference is None: - warnings.warn( - "Online evals are configured without an [inference] block - the launcher will not " - f"start an inference server. Make sure one is running at eval.client.base_url " - f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', " - "otherwise the online-eval process will hang waiting for it. If a router fronts the " - "deployment, set eval.client.admin_base_url to the engine URLs - admin ops " - "(pause/update_weights/resume) must bypass the router.", - stacklevel=2, - ) - return self - - total_gpus = self.deployment.num_train_gpus + self.deployment.num_infer_gpus - if total_gpus > self.deployment.gpus_per_node: - raise ValueError( - f"Total GPU count ({total_gpus} = {self.deployment.num_train_gpus} train + " - f"{self.deployment.num_infer_gpus} infer) exceeds gpus_per_node " - f"({self.deployment.gpus_per_node})." - ) - - if self.inference.vllm.model != self.model.name: - raise ValueError( - f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name " - f"({self.model.name}). Remove inference.vllm.model to inherit it." - ) - - # Fill inference capacity with DP ranks (mirrors RLConfig.auto_setup_deployment). - num_infer_gpus = self.deployment.num_infer_gpus - vllm = self.inference.vllm - if num_infer_gpus != vllm.data_parallel_size * vllm.tensor_parallel_size: - if num_infer_gpus % vllm.tensor_parallel_size != 0: - raise ValueError( - f"deployment.num_infer_gpus ({num_infer_gpus}) must be divisible by " - f"inference.vllm.tensor_parallel_size ({vllm.tensor_parallel_size})." - ) - vllm.data_parallel_size = num_infer_gpus // vllm.tensor_parallel_size - if vllm.api_server_count < vllm.data_parallel_size and not vllm.enable_lora: - vllm.api_server_count = vllm.data_parallel_size - if self.weight_broadcast.type != "filesystem": - self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size - self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type) - - host = self.inference.server.host or "localhost" - client = self.eval.client - if "base_url" not in client.model_fields_set: - client.base_url = f"http://{host}:{self.inference.server.port}/v1" - elif urlparse(client.base_url).port != self.inference.server.port: - raise ValueError( - f"eval.client.base_url port ({urlparse(client.base_url).port}) does not match " - f"inference.server.port ({self.inference.server.port})." - ) - if self.inference.router is not None and "admin_base_url" not in client.model_fields_set: - # Admin ops (pause/update_weights/resume) must bypass the router and hit - # the engine directly. - client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"] - return self - - @model_validator(mode="after") - def auto_setup_val(self): - if not isinstance(self.val, ValConfig): - return self - for val_set in self.val.set: - if val_set.seq_len is None: - val_set.seq_len = self.data.seq_len - longest = max(val_set.seq_len for val_set in self.val.set) - if self.val.micro_batch_tokens is None: - row_len = max(self.data.seq_len * self.data.micro_batch_size, longest) - self.val.micro_batch_tokens = -(-row_len // self.model.cp) * self.model.cp - elif self.val.micro_batch_tokens < longest: - raise ValueError(f"val.micro_batch_tokens must be at least the longest set seq_len ({longest})") - return self - - @model_validator(mode="after") - def validate_cp_seq_len(self): - if self.model.cp > 1: - if self.data.seq_len % self.model.cp != 0: - raise ValueError("Sequence length must be divisible by CP degree") - if isinstance(self.val, ValConfig) and self.val.micro_batch_tokens % self.model.cp != 0: - raise ValueError("val.micro_batch_tokens must be divisible by CP degree") - if isinstance(self.val, BaseValConfig) and self.val.data.seq_len % self.model.cp != 0: - raise ValueError("Validation sequence length must be divisible by CP degree") - return self - - @model_validator(mode="after") - def resolve_mega_moe_max_tokens_per_rank(self): - dispatch = self.model.moe.dispatch - if dispatch.type == "mega_moe": - row_lens = [self.data.micro_batch_size * self.data.seq_len] - if isinstance(self.val, ValConfig): - row_lens.append(self.val.micro_batch_tokens) - elif self.val is not None: - row_lens.append(self.val.data.micro_batch_size * self.val.data.seq_len) - dispatch.max_tokens_per_rank = mega_moe_max_tokens_per_rank( - dispatch.max_tokens_per_rank, - max(row_lens), - self.model.cp, - ) - return self - - @model_validator(mode="after") - def validate_cp_micro_batch_size(self): - if self.model.cp > 1: - if self.data.micro_batch_size != 1: - raise ValueError("Micro batch size must be 1 when CP is enabled") - if isinstance(self.val, BaseValConfig) and self.val.data.micro_batch_size != 1: - raise ValueError("Validation micro batch size must be 1 when CP is enabled") - return self - - ### Auto-setup and validate shared configs - - @model_validator(mode="after") - def auto_setup_slurm_template(self): - if self.slurm is not None and self.slurm.job_name is None: - self.slurm.job_name = self.run.name - if self.slurm is not None and self.slurm.template_path is None: - templates_dir = find_package_resource("templates") - if templates_dir is not None: - if self.deployment.type == "single_node": - self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2" - else: - self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2" - return self diff --git a/packages/prime-rl-configs/src/prime_rl/configs/trainer.py b/packages/prime-rl-configs/src/prime_rl/configs/trainer.py deleted file mode 100644 index 18eebef208d..00000000000 --- a/packages/prime-rl-configs/src/prime_rl/configs/trainer.py +++ /dev/null @@ -1,947 +0,0 @@ -import re -import warnings -from pathlib import Path -from typing import Annotated, Any, ClassVar, Literal, TypeAlias - -from pydantic import Field, field_validator, model_validator - -from prime_rl.configs.monitors import MonitorsConfig -from prime_rl.configs.shared import ( - BaseCheckpointConfig, - BaseModelConfig, - ControlConfig, - EnvVars, - FileSystemWeightBroadcastConfig, - GCConfig, - HeartbeatConfig, - ResumeConfig, - TrainerLogConfig, - VLMConfig, - WeightBroadcastConfig, - ZMQTransportConfig, -) -from prime_rl.utils.config import BaseConfig, default_output_dir - -# -- Shared trainer configs (used by both SFT and RL trainers) -- - -AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"] -DSABackend: TypeAlias = Literal["tilelang", "cudnn_flashmla"] - -MODULE_TARGET_SEPARATOR = "@" - - -class ActivationCheckpointConfig(BaseConfig): - mode: Literal["full", "selective"] = "full" - """Both modes checkpoint whole transformer blocks. ``selective`` additionally retains selected operations.""" - - freq: int = Field(1, ge=1) - """Apply activation checkpointing to every N layers.""" - - targets: list[str] | None = None - """Operator names or namespaces retained in selective mode. ``None`` uses the default targets; an explicit list replaces them. Append ``@`` to retain an operator only inside matching modules, for example ``"prime_rl::fp8_blockwise_mm@self_attn.o_b_proj"``. The pattern is an ``fnmatch`` glob over module paths relative to the checkpointed block, and it also covers the matching modules' descendants. Module-qualified targets require ``model.compile``, and the trainer raises after the first training forward if one matched no traced operation.""" - - @field_validator("targets") - @classmethod - def validate_targets(cls, targets: list[str] | None) -> list[str] | None: - for target in targets or []: - operation, separator, module_pattern = target.partition(MODULE_TARGET_SEPARATOR) - if not operation or (separator and (not module_pattern or MODULE_TARGET_SEPARATOR in module_pattern)): - raise ValueError( - f"Invalid activation checkpointing target {target!r}: expected an operator or namespace, " - "optionally followed by '@'." - ) - return targets - - token_chunk_size: int | None = Field(None, ge=3) - """Experimental. Checkpoint token-local blocks in chunks of this many tokens per rank, so their recompute and backward hold one chunk's activations at a time. Only supported for Nemotron-H, whose MoE layers are the only blocks it chunks; it has no effect on other models. Requires ``ep == 1`` or ``ep == cp``. ``None`` checkpoints every block whole.""" - - -class ActivationOffloadingConfig(BaseConfig): - """Offload tensors saved for backward to pinned CPU memory during the forward pass.""" - - max_inflight_activations: int = Field(5, ge=1) - """Max activations kept on GPU while their offload copies are in flight on the side stream. Higher values give more copy/compute overlap at the cost of GPU memory.""" - - -OffloadMode: TypeAlias = Literal["none", "optimizer", "full"] - - -class CompileConfig(BaseConfig): - fullgraph: bool = False - """Compile transformer blocks with ``fullgraph=True``.""" - - mode: Literal["reduce-overhead", "max-autotune", "max-autotune-no-cudagraphs", "lite"] | None = None - """``torch.compile`` mode. ``reduce-overhead`` records CUDA graphs to cut kernel launch overhead; ``max-autotune`` modes trade longer compile times for tuned kernels (``max-autotune`` also records CUDA graphs, ``max-autotune-no-cudagraphs`` does not). CUDA-graphed layers re-record on new input shapes. ``None`` uses PyTorch's default mode.""" - - -class FusionsConfig(BaseConfig): - enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"] - """Runtime parameter fusions. ``gate_up`` runs each MoE expert's gate and up projections as one grouped GEMM; ``qkv`` runs attention's q, k and v projections as one GEMM. Only modules that support a fusion are packed, checkpoints keep the canonical parameter names and shapes, and fusions are skipped when LoRA is enabled. Set to ``[]`` to disable.""" - - shard_fused_on_dim1: bool = False - """Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size.""" - - -class LoRAConfig(BaseConfig): - rank: int = Field(16, ge=1) - """Rank of the low-rank decomposition matrices.""" - - alpha: float = Field(32.0, ge=0) - """LoRA scaling parameter.""" - - dropout: float = Field(0.0, ge=0, le=1) - """LoRA dropout rate.""" - - target_modules: list[str] = [ - "q_proj", - "k_proj", - "v_proj", - "o_proj", - "gate_proj", - "up_proj", - "down_proj", - "experts", - "fc1_latent_proj", - "fc2_latent_proj", - ] - """Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches the ReLU² grouped experts; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba.""" - - -class DebugModelConfig(BaseConfig): - num_layers: int | None = None - """Override the number of transformer layers (truncates the model).""" - - force_balanced_routing: bool = False - """Replace MoE token-choice routing with a round-robin assignment so every expert sees an equal share. Intended for fake-data smoke tests where untrained routing would otherwise OOM under severe imbalance. Gating scores are still gathered from the override indices so the forward pass stays consistent.""" - - -MXFP8Recipe: TypeAlias = Literal["mxfp8_rceil", "mxfp8_rceil_wgrad_with_hp"] - -_DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [ - "lm_head", - "router", - # Use escaped dots — re.search treats `.` as any-char, so the previous - # "mlp.gate." pattern was also matching dense MLP `mlp.gate_proj` (the - # trailing `.` was matching `_`). That left the dense MLP gate projection - # in BF16 on the trainer while inference quantized it to FP8, causing - # hidden-state drift before the MoE router. - r"mlp\.gate\.", - r"shared_expert\.output_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False) - "eh_proj", - "weights_proj", - "in_proj_a", - "in_proj_b", -] - - -class FP8Config(BaseConfig): - type: Literal["fp8"] = "fp8" - ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS - """Dense linear module names excluded from DeepGEMM FP8 replacement.""" - - extra_ignore_patterns: list[str] = [] - """Patterns appended to `ignore_patterns`, to exclude model-specific modules while keeping the defaults.""" - - -class MXFP8Config(BaseConfig): - type: Literal["mxfp8"] = "mxfp8" - recipe: MXFP8Recipe = "mxfp8_rceil" - """MXFP8 recipe for dense linear modules.""" - - ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS - """Dense linear module names excluded from torchao MXFP8 replacement.""" - - extra_ignore_patterns: list[str] = [] - """Patterns appended to `ignore_patterns`, to exclude model-specific modules while keeping the defaults.""" - - -QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")] - - -class MoEComputeConfigBase(BaseConfig): - apply_to: str | list[Annotated[int, Field(ge=0, strict=True)]] = "all" - """Model layers to use this backend for: ``"all"``, a percentage such as ``"85%"``, - or zero-based layer indices such as ``[0, 1, 2]``. Percentages select the first fraction - of model layers, rounded down. Other expert groups use BF16 compute and transport. - """ - - @field_validator("apply_to") - @classmethod - def validate_apply_to(cls, value: str | list[int]) -> str | list[int]: - if isinstance(value, str) and value != "all": - if re.fullmatch(r"\d+(?:\.\d+)?%", value) is None or float(value[:-1]) > 100: - raise ValueError('apply_to must be "all", a percentage from "0%" to "100%", or a list of layer indices') - return value - - def resolve_layers(self, num_layers: int) -> set[int]: - if isinstance(self.apply_to, list): - invalid = [index for index in self.apply_to if index >= num_layers] - if invalid: - raise ValueError( - f"apply_to layer indices {invalid} are out of range for a model with {num_layers} layers" - ) - return set(self.apply_to) - count = num_layers if self.apply_to == "all" else int(num_layers * float(self.apply_to[:-1]) / 100) - return set(range(count)) - - -class BF16MoEComputeConfig(MoEComputeConfigBase): - """Run routed experts in bfloat16.""" - - type: Literal["bf16"] = "bf16" - backend: Literal["torch", "sonicmoe"] = "torch" - """Expert compute implementation.""" - - -class DeepGemmFP8MoEComputeConfig(MoEComputeConfigBase): - """Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels.""" - - type: Literal["deepgemm_fp8"] = "deepgemm_fp8" - - -class MXFP8MoEComputeConfig(MoEComputeConfigBase): - """Run routed-expert grouped GEMMs with Prime's vendored MXFP8 implementation.""" - - type: Literal["mxfp8"] = "mxfp8" - recipe: MXFP8Recipe = "mxfp8_rceil" - """MXFP8 expert-compute recipe.""" - - -class NVFP4MoEComputeConfig(MoEComputeConfigBase): - """Run routed experts with the numerics of vLLM's online ``nvfp4_per_token`` MoE: NVFP4 forward with per-token - activation scales and the engines' load-time weight quantizer, MXFP8 backward on the dequantized operands (SM100). - In ``rl`` the engines must run ``quantization = "online"`` with ``quantization_config.moe = "nvfp4_per_token"``.""" - - type: Literal["nvfp4"] = "nvfp4" - four_over_six: bool = False - """Choose each activation block's scale with 4/6 (the lower-error of the max-6 and max-4 scales), as FlashInfer's - ``FLASHINFER_NVFP4_4OVER6``. ``rl`` applies the same setting to the engines. Weights never use it.""" - - @property - def flashinfer_env(self) -> dict[str, str]: - """FlashInfer quantizer settings the trainer and the engines share: IEEE division, 4/6 on or off.""" - return { - "FLASHINFER_DISABLE_FP4_QUANT_FAST_MATH": "1", - "FLASHINFER_NVFP4_4OVER6": "1" if self.four_over_six else "0", - } - - -MoEComputeConfig: TypeAlias = Annotated[ - BF16MoEComputeConfig | DeepGemmFP8MoEComputeConfig | MXFP8MoEComputeConfig | NVFP4MoEComputeConfig, - Field(discriminator="type"), -] - - -class TorchMoEDispatchConfig(BaseConfig): - """Dispatch and combine routed tokens with torch all-to-all collectives.""" - - type: Literal["torch"] = "torch" - transport: Literal["bf16", "mxfp8"] = "bf16" - """Wire format for routed activations and their reverse-path gradients.""" - - -class DeepEPMoEDispatchConfig(BaseConfig): - """Dispatch and combine routed tokens with DeepEP.""" - - type: Literal["deepep"] = "deepep" - num_sms: int = Field(32, ge=1) - """SMs allocated to DeepEP communication kernels.""" - - -class LLEPConfig(BaseConfig): - """Least-loaded expert parallelism (https://arxiv.org/abs/2601.17111): a rank whose experts are overloaded hands - part of their routes, with a copy of the experts' weights, to the least-loaded ranks. The computation stays exact.""" - - alpha: float = Field(1.05, ge=1.0) - """A rank counts as full at ``alpha`` times the mean routes per rank.""" - - min_chunk: int = Field(1024, ge=1) - """Fewest routes worth copying an expert's weights to another rank.""" - - lam: float = Field(1.1, ge=0.0) - """Below this busiest-rank over mean-rank load, every expert stays on its own rank (standard EP).""" - - max_foreign: int = Field(8, ge=1) - """Experts a rank can compute for other ranks; each costs one expert's weights (and gradients) of memory.""" - - chunk_tokens: int | None = Field(None, ge=1) - """Tokens per rank per kernel call. A larger batch runs as several calls, so the symmetric buffers hold one chunk - instead of the whole batch (for long sequences). ``None``: one call per layer.""" - - max_recv: float = Field(1.3, gt=0.0) - """Routes a rank's buffers hold, as a multiple of its own routes (``max_tokens_per_rank * top_k``). The plan keeps - every rank within about ``max(alpha, lam)`` of the mean, so this can be far below the ``ep`` multiple plain Mega MoE - reserves. A plan that would exceed it (only when helpers run out of foreign slots) stops the kernel with an error.""" - - @model_validator(mode="after") - def validate_max_recv(self): - if self.max_recv < max(self.alpha, self.lam): - raise ValueError("model.moe.dispatch.llep.max_recv must be at least max(alpha, lam).") - return self - - -class MegaMoeMoEDispatchConfig(BaseConfig): - type: Literal["mega_moe"] = "mega_moe" - precision: Literal["bf16", "mxfp8", "mxfp8_qat", "fp8", "fp8_bwd", "nvfp4"] = "bf16" - """Expert GEMM precision. ``mxfp8``: forward and backward in MXFP8 (SM100). ``mxfp8_qat``: MXFP8 forward, BF16 - backward on the forward's dequantized weights, as MXFP8 quantization-aware training computes (SM100). ``fp8``: - forward and backward in blockwise FP8 (SM90). ``fp8_bwd``: BF16 forward, blockwise FP8 backward (SM90). - ``nvfp4``: NVFP4 forward as vLLM's online ``nvfp4_per_token`` MoE computes it (per-token activation and per-expert - weight scales), MXFP8 backward on the forward's NVFP4 operands (SM100). In ``rl`` the engines must run that MoE - quantization with the same ``four_over_six``.""" - - four_over_six: bool = False - """``nvfp4`` only: choose each activation block's scale with 4/6, as FlashInfer's ``FLASHINFER_NVFP4_4OVER6``.""" - - max_tokens_per_rank: int | None = Field(None, ge=1) - """Tokens per rank per MoE call that the symmetric buffer is sized for. Defaults to the rank's share of the - micro batch under context parallelism (``model.seq_len / model.cp`` for RL, - ``data.micro_batch_size * data.seq_len / model.cp`` for SFT) and cannot be smaller.""" - - num_reserved_sms: int = Field(16, ge=2) - """SMs left free for concurrent NCCL kernels. In the worst case each NCCL kernel uses all ``NCCL_MAX_CTAS``, so - at most ``num_reserved_sms // NCCL_MAX_CTAS`` NCCL kernels can run concurrently. FSDP overlaps an all-gather and - a reduce-scatter, and HSDP (``dp_replicate > 1``) adds an all-reduce, so the trainer sets ``NCCL_MAX_CTAS`` to - this value divided by 2 (3 under HSDP) when it is unset and requires it to be at most that. Defaults to 32 with - ``llep``, whose weight copies run next to the grid.""" - - llep: LLEPConfig | None = None - """Balance imbalanced routing with least-loaded expert parallelism. Requires ``precision = "bf16"`` (SM90), - ``"mxfp8"``, ``"mxfp8_qat"`` or ``"nvfp4"`` (SM100).""" - - @model_validator(mode="after") - def validate_llep_precision(self): - if self.llep is not None and self.precision not in ("bf16", "mxfp8", "mxfp8_qat", "nvfp4"): - raise ValueError( - "model.moe.dispatch.llep requires model.moe.dispatch.precision 'bf16', 'mxfp8', 'mxfp8_qat' or 'nvfp4'." - ) - return self - - @model_validator(mode="after") - def validate_four_over_six(self): - if self.four_over_six and self.precision != "nvfp4": - raise ValueError("model.moe.dispatch.four_over_six requires model.moe.dispatch.precision 'nvfp4'.") - return self - - @model_validator(mode="after") - def llep_reserved_sms(self): - if self.llep is not None and "num_reserved_sms" not in self.model_fields_set: - self.num_reserved_sms = 32 - return self - - -def rl_micro_batch_multiple(model: "ModelConfig") -> int: - """RL micro batches are padded to a multiple of this: one shard per CP rank, and MXFP8 linears quantize - grad_output in 32-token blocks per CP rank.""" - if isinstance(model.quantization, MXFP8Config): - return model.cp * 32 - return model.cp - - -def mega_moe_max_tokens_per_rank(max_tokens_per_rank: int | None, micro_batch_tokens: int, cp: int) -> int: - """A rank with more tokens than its buffer fails alone while its peers wait in the kernel, so the - buffer must hold the rank's full share of the micro batch. Context parallelism splits every micro - batch evenly over the ``cp`` ranks, so that share is ``micro_batch_tokens / cp``.""" - rank_tokens = -(-micro_batch_tokens // cp) - if max_tokens_per_rank is None: - return rank_tokens - if max_tokens_per_rank < rank_tokens: - raise ValueError( - f"model.moe.dispatch.max_tokens_per_rank ({max_tokens_per_rank}) must be at least the tokens a rank " - f"holds per micro batch ({micro_batch_tokens} tokens over cp={cp}: {rank_tokens})." - ) - return max_tokens_per_rank - - -MoEDispatchConfig: TypeAlias = Annotated[ - TorchMoEDispatchConfig | DeepEPMoEDispatchConfig | MegaMoeMoEDispatchConfig, - Field(discriminator="type"), -] - - -class MoERuntimeConfig(BaseConfig): - """Independent routed-expert compute and token-dispatch choices.""" - - compute: MoEComputeConfig = BF16MoEComputeConfig() - dispatch: MoEDispatchConfig = TorchMoEDispatchConfig() - - -class ScratchInit(BaseConfig): - """The model's own random init (its ``_init_weights``, with the ``initializer_range`` of ``model.name``'s - config.json); ``model.name`` supplies only the architecture and the tokenizer.""" - - type: Literal["scratch"] = "scratch" - - seed: int = 0 - """Seed of the init: the same seed gives the same weights on the same GPU layout.""" - - -class PretrainedInit(BaseConfig): - """The weights stored at ``model.name``: an HF model (Hub id or local directory), or a checkpoint step directory - (``.../step_``) of another run, whose ``trainer/`` weights load and whose ``config.json`` and tokenizer files - supply the architecture and the tokenizer. A step directory starts the run at step 0 with a fresh optimizer, - scheduler and data.""" - - type: Literal["pretrained"] = "pretrained" - - -InitConfig: TypeAlias = Annotated[ScratchInit | PretrainedInit, Field(discriminator="type")] - - -class ModelConfig(BaseModelConfig): - vlm: VLMConfig | None = None - """VLM configuration. Setting this enables vision-language model support.""" - - conversion_dir: Path | None = None - """Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory.""" - - init: InitConfig = PretrainedInit() - """Where the weights start. A resumed run loads its own checkpoint instead, whatever the type.""" - - seq_len: int = 2048 - """Sequence length the model is trained on.""" - - attn: AttnImplementation = "auto" - """Attention implementation. ``auto`` selects FA3 on Hopper (SM90) and FA4 on Blackwell (SM100+).""" - - compile: CompileConfig | None = CompileConfig() - """Compile the model with ``torch.compile``.""" - - fusions: FusionsConfig = FusionsConfig() - """Runtime parameter fusions, on by default.""" - - ac: ActivationCheckpointConfig | None = ActivationCheckpointConfig() - """Activation checkpointing configuration. If None, activation checkpointing is disabled.""" - - ac_offloading: ActivationOffloadingConfig | None = ActivationOffloadingConfig() - """Activation offloading configuration. If None, activation offloading is disabled.""" - - offload: OffloadMode = "optimizer" - """CPU offloading. ``optimizer`` keeps optimizer states (momentum, variance) in CPU RAM and weights on GPU. ``full`` keeps FP32 masters, optimizer states, and accumulated gradients in CPU RAM and runs each optimizer chunk on CPU as soon as its last gradient arrives, overlapped with backward; it supports AdamW and SignSGD only, disables gradient clipping, and rounds each gradient to BF16 once before the FP32 CPU update. ``none`` keeps everything on GPU.""" - - reshard_after_forward: bool = True - """Reshard the model after each forward pass.""" - - dp_replicate: int = 1 - """Data parallel dim where model weights are replicated.""" - - ep: int | Literal["auto"] = "auto" - """Expert parallelism degree for MoE layers. 1 disables EP. ``auto`` resolves for MoE models to the largest degree up to 8 that divides both ``fsdp_island_size = world_size // dp_replicate`` and the expert count and is a multiple of ``cp``, and to 1 for non-MoE models. Set an explicit integer to override.""" - - moe: MoERuntimeConfig = MoERuntimeConfig() - """Routed-expert compute and token-dispatch runtime.""" - - cp: int = 1 - """Context parallelism degree. 1 disables CP.""" - - optimization_dtype: Literal["bfloat16", "float32"] = "float32" - """dtype for model optimization.""" - - reduce_dtype: Literal["bfloat16", "float32"] = "float32" - """dtype for gradient/parameter reductions.""" - - reduce_scatter_max_input_buffers: int = Field(1, ge=1) - """Maximum number of FSDP gradient reduce-scatter input buffers kept in flight. Raising it trades memory (about one layer's gradients per extra buffer) for overlap when reduce-scatters are exposed, e.g. MoE without EP or full activation checkpointing.""" - - quantization: QuantizationConfig | None = None - - dsa_backend: DSABackend = "cudnn_flashmla" - """Kernels for the sparse attention of ``glm_moe_dsa`` (DSA sparse MLA, e.g. GLM-5) and ``deepseek_v4``. ``cudnn_flashmla`` (default) runs the FlashMLA sparse prefill forward with the cuDNN frontend CuTe-DSL backward; it needs an SM90, SM100 or SM103 GPU, vLLM's bundled FlashMLA (installed with the ``gpu`` extra), 64 or 128 attention heads and head_dim 512, and setup fails otherwise. ``tilelang`` runs the TileLang forward and backward.""" - - dsv4_kv_precision: Literal["bf16", "fp8"] = "fp8" - """Precision DeepSeek V4 attention reads keys and values at. ``fp8`` rounds them as vLLM's ``fp8_ds_mla`` KV cache stores them, with a straight-through gradient.""" - - dsv4_compressor_backend: Literal["cudnn", "torch"] = "cudnn" - """Backend of the DeepSeek V4 compressors' softmax-gated pooling. ``cudnn`` (default) runs the cuDNN frontend's fused CSA/HCA compressor where its kernels apply: an SM100 or newer GPU, bf16 activations, and a compress rate of 2 or 4, or 128 with head_dim 128 or 512. Elsewhere it silently runs the torch ops, so on SM90 GPUs such as the H100 and H200 ``cudnn`` runs torch. ``cudnn`` scans each entry's document list, so it wins on rows of few long documents and loses to the flat torch ops on rows of many short documents. ``torch`` always runs the torch ops.""" - - freeze_moe_router: bool | Literal["auto"] = "auto" - """Freeze MoE router gate parameters. ``auto`` (default): ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys.""" - - lora: LoRAConfig | None = None - """LoRA configuration. If None, LoRA is disabled.""" - - debug: DebugModelConfig = DebugModelConfig() - """Debugging knobs for the model and distributed training.""" - - fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192 - """Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. In SFT the fused head computes the summed cross-entropy and its gradients chunk by chunk, holding one chunk's full-vocab logits at a time.""" - - @model_validator(mode="after") - def validate_scratch_lora(self): - if self.init.type == "scratch" and self.lora is not None: - raise ValueError('model.lora adapts pretrained weights, which model.init.type = "scratch" does not load') - return self - - @model_validator(mode="after") - def validate_cp(self): - if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]: - raise ValueError("CP is only supported with flash attention 2, 3, or 4") - return self - - @model_validator(mode="after") - def module_qualified_ac_targets_require_compile(self): - if ( - self.compile is None - and self.ac is not None - and any(MODULE_TARGET_SEPARATOR in target for target in self.ac.targets or []) - ): - raise ValueError("Module-qualified model.ac.targets require model.compile.") - return self - - @model_validator(mode="after") - def ac_offloading_requires_ac(self): - """Activation offloading requires activation checkpointing, so ``ac = None`` disables both.""" - if self.ac is None: - self.ac_offloading = None - return self - - @model_validator(mode="after") - def validate_moe_runtime(self): - if self.ep == 1: - return self - - compute = self.moe.compute - dispatch = self.moe.dispatch - if isinstance(dispatch, TorchMoEDispatchConfig) and dispatch.transport == "mxfp8": - if not isinstance(compute, MXFP8MoEComputeConfig): - raise ValueError("MXFP8 transport requires model.moe.compute.type='mxfp8'.") - return self - - -class TokenizerConfig(BaseConfig): - name: str | None = None - """Tokenizer name or path. If None, the model's default tokenizer is used.""" - - trust_remote_code: bool | None = None - """Trust remote code when initializing the tokenizer. If None, inherits the model's ``trust_remote_code`` setting.""" - - chat_template: str | None = None - """Chat template for the tokenizer. Either a Jinja2 template string or a path to a template file. If None, the tokenizer's default chat template is used.""" - - -class ConstantSchedulerConfig(BaseConfig): - type: Literal["constant"] = "constant" - - start_step: int = Field(0, ge=0) - """The step the schedule starts at. A constant schedule is the same at every step.""" - - -class LinearSchedulerConfig(BaseConfig): - type: Literal["linear"] = "linear" - - warmup_steps: int = Field(10, ge=0) - """Warmup steps for the learning rate scheduler.""" - - decay_steps: int = Field(10, ge=0) - """Steps to decay the learning rate during the final portion of training.""" - - min_lr: float = Field(0.0, ge=0) - """Learning rate the base param group, whose peak is ``optim.lr``, warms up from and decays to. Every other param - group warms up from and decays to ``min_lr / optim.lr`` times its own peak. 0 means a factor of ``1e-8``.""" - - start_step: int = Field(0, ge=0) - """The step the schedule starts at: its warmup and decay span the ``max_steps - start_step`` steps after it. Set - it to a resume step to start a fresh schedule there.""" - - -class CosineSchedulerConfig(BaseConfig): - type: Literal["cosine"] = "cosine" - - warmup_steps: int = Field(10, ge=0) - """Warmup steps for the learning rate scheduler.""" - - min_lr: float = Field(0.0, ge=0) - """Learning rate the base param group, whose peak is ``optim.lr``, warms up from and decays to. Every other param - group warms up from and decays to ``min_lr / optim.lr`` times its own peak. 0 means a warmup from ``1e-8`` times - the peak and a decay to 0.""" - - start_step: int = Field(0, ge=0) - """The step the schedule starts at: its warmup and decay span the ``max_steps - start_step`` steps after it. Set - it to a resume step to start a fresh schedule there.""" - - -SchedulerConfig: TypeAlias = Annotated[ - ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type") -] - - -def validate_scheduler(scheduler: SchedulerConfig, max_steps: int | None) -> None: - """Check scheduler phases against max_steps so misconfigurations fail at config time.""" - if max_steps is not None and scheduler.start_step >= max_steps: - raise ValueError(f"start_step ({scheduler.start_step}) must be less than max_steps ({max_steps})") - # The steps the schedule spans - horizon = max_steps - scheduler.start_step if max_steps is not None else None - if isinstance(scheduler, LinearSchedulerConfig): - if scheduler.warmup_steps == 0 and scheduler.decay_steps == 0: - raise ValueError( - "Linear scheduler requires warmup_steps > 0 or decay_steps > 0 (use the constant scheduler instead)" - ) - if scheduler.decay_steps == 1: - raise ValueError("decay_steps must be 0 or at least 2") - if scheduler.decay_steps > 0: - if horizon is None: - raise ValueError("Must specify max_steps when using a linear scheduler with decay_steps > 0") - if scheduler.warmup_steps + scheduler.decay_steps > horizon: - raise ValueError( - f"warmup_steps ({scheduler.warmup_steps}) + decay_steps ({scheduler.decay_steps}) " - f"must not exceed max_steps - start_step ({horizon})" - ) - if isinstance(scheduler, CosineSchedulerConfig): - if horizon is None: - raise ValueError("Must specify max_steps when using a cosine scheduler") - if scheduler.warmup_steps >= horizon: - raise ValueError( - f"warmup_steps ({scheduler.warmup_steps}) must be less than max_steps - start_step ({horizon})" - ) - - -class BaseOptimizerConfig(BaseConfig): - lr: float = Field(1e-6, ge=0) - """Peak learning rate.""" - - weight_decay: Annotated[float, Field(ge=0)] | Literal["auto"] = "auto" - """L2 weight-decay coefficient. ``"auto"`` (default) resolves to ``0.0`` for RL and ``0.01`` for SFT.""" - - max_norm: float | None = Field(1.0, ge=0) - """Maximum gradient norm to clip to. If None, gradient clipping is disabled.""" - - -class AdamWConfig(BaseOptimizerConfig): - type: Literal["adamw"] = "adamw" - - betas1: float = Field(0.9, ge=0) - """Adam first-moment (β1) decay.""" - - betas2: float = Field(0.999, ge=0) - """Adam second-moment (β2) decay.""" - - eps: float = Field(1e-8, gt=0) - """Adam epsilon, added to the denominator of the update.""" - - -class MuonConfig(BaseOptimizerConfig): - type: Literal["muon"] = "muon" - - mu: float = Field(0.95, ge=0) - """Momentum factor for the Muon algorithm.""" - - nesterov: bool = True - """Nesterov momentum for the Muon updates.""" - - betas1: float = Field(0.9, ge=0) - """β1 for the AdamW sub-optimizer used on non-Muon params.""" - - betas2: float = Field(0.95, ge=0) - """β2 for the AdamW sub-optimizer used on non-Muon params.""" - - eps: float = Field(1e-8, gt=0) - """Epsilon for the AdamW sub-optimizer used on non-Muon params, and for the Newton-Schulz normalization.""" - - update_rms: float = Field(0.2, gt=0) - """RMS of each Muon update matrix, so Muon reuses the AdamW learning rate. DeepSeek-V4.1 uses 0.18.""" - - newton_schulz_schedule: Literal["default", "deepseek_v4", "polar_express", "step3p5"] = "default" - """Coefficient schedule of the Newton-Schulz iteration that orthogonalizes the updates. ``default``: 5 quintic steps with per-step coefficients. ``deepseek_v4``: 8 steps of (3.4445, -4.7750, 2.0315), then 2 steps of (2, -1.5, 0.5) that pin the singular values at 1. ``polar_express``: 5 steps of Polar Express (arXiv 2505.16932) in bf16, with its 1.01 safety factor. ``step3p5``: 6 Polar Express steps in fp16, as in Step 3.5 Flash.""" - - -class SignSGDConfig(BaseOptimizerConfig): - type: Literal["sign_sgd"] = "sign_sgd" - - -OptimizerConfig: TypeAlias = Annotated[AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")] - - -class RemoteCheckpointConfig(BaseConfig): - dir: str - """Object store URL checkpoints are mirrored to, e.g. ``s3://bucket/run/checkpoints`` (credentials and endpoint from the ``AWS_*`` environment).""" - - keep_last: int | None = Field(None, ge=1) - """Keep at most this many recent step checkpoints in the remote. If None, never clean old remote checkpoints based on recency.""" - - keep_interval: int | None = Field(None, ge=1) - """Keep remote checkpoints at every N steps permanently. If None, no interval-based keeping.""" - - -class CheckpointConfig(BaseCheckpointConfig): - remote: RemoteCheckpointConfig | None = None - """Mirror checkpoints to an object store. A sync process per node uploads each step once it is on disk, with ``.metadata`` last; ``keep_last``/``keep_interval`` apply to the disk and ``remote.keep_last``/``remote.keep_interval`` to the remote. Resume pulls a step that is not complete on disk while the trainer starts up.""" - - skip_dataloader: bool = False - """Skip loading the dataloader from checkpoint.""" - - skip_optimizer: bool = False - """Start the optimizer state fresh: new moments and Muon step counts. Loads none of the checkpoint's param - groups, so it has no hyperparameters to compare and logs no mismatch warning.""" - - async_save: bool = False - """Write checkpoints in the background. A save copies this rank's model and optimizer state into pinned host - buffers and returns; a background thread writes the copy while training continues. The buffers are kept for - the next save, so this costs pinned host memory about the size of the rank's checkpoint shard. Without - optimizer offload the copy also overlaps the next step, until its optimizer step. A save first waits for the - previous write to finish.""" - - -class IPOLossConfig(BaseConfig): - type: Literal["ipo"] = "ipo" - eps: float = Field(0.3, ge=0) - """Maximum absolute probability change before a token is masked.""" - - max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False) - """Cap the importance weight of accepted tokens while preserving its policy gradient.""" - - adv_tau: float = Field(1.0, ge=0) - """Temperature for the advantage term.""" - - -class IcePopLossConfig(BaseConfig): - type: Literal["icepop"] = "icepop" - - ratio_low: float = Field(0.2, gt=0) - """Lower accepted trainer-to-inference probability ratio.""" - - ratio_high: float = Field(5.0, gt=0) - """Upper accepted trainer-to-inference probability ratio.""" - - adv_tau: float = Field(1.0, ge=0) - """Temperature for the advantage term.""" - - score_centering: bool = False - """Center the ratio-masked importance-weighted score under the sampler.""" - - score_centering_topk: int = Field(128, ge=1) - """Captured head size for an untruncated sampler with a proportional tail. - Probabilities retain full-vocabulary normalization. With sampling replay, the - complete recorded support is captured instead.""" - - @model_validator(mode="after") - def validate_ratio_bounds(self): - if self.ratio_low > self.ratio_high: - raise ValueError("ratio_low must not exceed ratio_high") - return self - - -class CustomLossConfig(BaseConfig): - type: Literal["custom"] = "custom" - - import_path: str - """Import path to the loss function (e.g. ``my_module.my_loss``).""" - - kwargs: dict[str, Any] = Field(default_factory=dict) - """Kwargs forwarded to the loss function.""" - - -LossConfig: TypeAlias = Annotated[ - IPOLossConfig | IcePopLossConfig | CustomLossConfig, - Field(discriminator="type"), -] - - -class FakeDataLoaderConfig(BaseConfig): - batch_size: int = Field(2, ge=1) - """Batch size of the fake data loader.""" - - generate_samples: bool = False - """Generate separate samples and pack them into a single micro-batch instead of using random tensors.""" - - doc_len: int | None = Field(None, ge=1) - """Length of each generated sample, the last one cut to fill the micro batch. If None, lengths are random up to a micro batch's length / 8. Requires generate_samples.""" - - @model_validator(mode="after") - def doc_len_requires_generate_samples(self): - if self.doc_len is not None and not self.generate_samples: - raise ValueError("data.fake.doc_len requires data.fake.generate_samples") - return self - - -class DataLoaderConfig(BaseConfig): - fake: FakeDataLoaderConfig | None = None - """Use a fake data loader sampling random micro-batches (for debugging).""" - - num_workers: int = Field(1, ge=0) - """Number of background threads that prepare micro batches ahead of the training loop, analogous to torch DataLoader's ``num_workers`` but with threads instead of processes. 0 prepares them on the main thread.""" - - pad_to_seq_len: bool = False - """Pad every micro batch to ``model.seq_len`` instead of to a multiple of the context-parallel degree. Rows then have one static shape, which avoids recompilation on dynamic sequence lengths (torch.compile, DeepGEMM JIT kernels, ...) at the cost of extra padding.""" - - -class BaseTrainerConfig(BaseConfig): - """Fields and validators shared by the RL trainer (``TrainerConfig``) and the SFT and pretraining trainer - (``SupervisedTrainerConfig``).""" - - auto_freeze_moe_router: ClassVar[bool] - auto_weight_decay: ClassVar[float] - - model: ModelConfig = ModelConfig() - - tokenizer: TokenizerConfig = TokenizerConfig() - - optim: OptimizerConfig = AdamWConfig() - - scheduler: SchedulerConfig = ConstantSchedulerConfig() - - ckpt: CheckpointConfig | None = None - - log: TrainerLogConfig = TrainerLogConfig() - - matmul_precision: Literal["highest", "high", "medium"] = "high" - """Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``.""" - - max_steps: int | None = None - """Maximum number of training steps. If None, runs indefinitely.""" - - memory_profiler_path: Path | None = None - """Path to write the memory profile to.""" - - gc: GCConfig | None = GCConfig() - """Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior.""" - - trace_path: Path | None = None - """Path to write the PyTorch profiler trace to.""" - - dist_timeout_seconds: int = 900 - """Timeout in seconds for torch distributed ops: a hung collective (e.g. a dead rank) fails the run after this long.""" - - heartbeat: HeartbeatConfig | None = None - """BetterStack heartbeat configuration for monitoring training progress.""" - - control: ControlConfig | None = None - """Serve the run control API on the master rank (pause or checkpoint the run - after the next step). If None, the run takes no control requests.""" - - env_vars: EnvVars = {} - """Extra environment variables for the trainer process(es). Merged on top of the launcher defaults.""" - - @model_validator(mode="after") - def resolve_auto_defaults(self): - if self.model.freeze_moe_router == "auto": - self.model.freeze_moe_router = self.auto_freeze_moe_router - if self.optim.weight_decay == "auto": - self.optim.weight_decay = self.auto_weight_decay - return self - - @model_validator(mode="after") - def full_optimizer_offload_requires_supported_optimizer(self): - if self.model.offload == "full" and self.optim.type not in ("adamw", "sign_sgd"): - raise ValueError("Full optimizer offload only supports AdamW and SignSGD") - return self - - @model_validator(mode="after") - def full_optimizer_offload_disables_grad_clipping(self): - if self.model.offload == "full" and self.optim.max_norm is not None: - warnings.warn( - "Gradient clipping prevents optimizer-in-backward overlap with CPU optimizer offload. " - "Automatically setting optim.max_norm to None (disabled).", - stacklevel=1, - ) - self.optim.max_norm = None - return self - - @model_validator(mode="after") - def vlm_freeze_incompatible_with_lora(self): - if self.model.vlm is not None and not self.model.vlm.freeze_vision_encoder and self.model.lora is not None: - raise ValueError( - "freeze_vision_encoder=false is incompatible with LoRA. " - "LoRA freezes all non-adapter parameters including the vision encoder." - ) - return self - - @model_validator(mode="after") - def dont_do_massive_traces(self): - if self.trace_path: - if self.max_steps is None: - raise ValueError("Must specify max_steps when tracing") - if self.max_steps >= 10: - raise ValueError( - "Tracing more than 10 steps is not recommended as your trace will be massive. Remove this line if you really want to trace more steps." - ) - return self - - @model_validator(mode="after") - def validate_scheduler_steps(self): - validate_scheduler(self.scheduler, self.max_steps) - return self - - @model_validator(mode="after") - def auto_setup_tokenizer(self): - if self.tokenizer.name is None: - self.tokenizer.name = self.model.name - if self.tokenizer.trust_remote_code is None: - self.tokenizer.trust_remote_code = self.model.trust_remote_code - return self - - -class TrainerConfig(BaseTrainerConfig): - # RL keeps the pretrained router. - auto_freeze_moe_router = True - # RL optimizes the reward objective, not a fixed dataset; L2 decay toward zero fights it. - auto_weight_decay = 0.0 - - data: DataLoaderConfig = DataLoaderConfig() - - loss: LossConfig = IPOLossConfig() - """Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this.""" - - resume: ResumeConfig | None = None - """Resume training from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints. The checkpoint supplies the training state; the hyperparameters and the learning rate schedule come from this config.""" - - weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig() - """Transport used to broadcast updated weights from trainer to inference.""" - - rollout_transport: ZMQTransportConfig = ZMQTransportConfig() - """Transport used to ship rollouts from orchestrator to trainer.""" - - monitors: MonitorsConfig = MonitorsConfig() - """Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).""" - - output_dir: Path = Field(default_factory=default_output_dir) - """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. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" - - annotations: bool = True - """Write the trainer's recomputed per-token logprobs and entropies as trace annotations, - so a trace can show trainer against sampler token by token. Needs ``monitors.file``. - Each step gathers every trained token to the master rank before the optimizer step; - disable with ``--no-annotations`` to skip that work.""" - - warmup: bool = True - """Before waiting for the first batch, run the training step's forward and backward on synthetic micro batches - that train nothing, so compilation, kernel JIT and communicator setup happen while the trainer would idle. The - warmup leaves the weights and the optimizer state unchanged.""" - - enable_router_replay: bool = False - """Return routed experts in the batch so the trainer can replay routing. Requires ``enable_return_routed_experts=true`` on the vLLM server (or ``--enable-return-routed-experts``) and is only supported for custom models.""" - - @model_validator(mode="after") - def validate_lora_broadcast(self): - if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "modelexpress"): - raise ValueError( - "LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a " - "PEFT-shaped directory on disk - in-memory transports have no disk artifact to load from." - ) - return self - - @model_validator(mode="after") - def validate_retain(self): - if not self.rollout_transport.retain: - return self - if not (self.ckpt and self.ckpt.interval): - raise ValueError("rollout_transport.retain needs ckpt.interval: only a checkpoint releases a retained step") - if self.weight_broadcast.type != "filesystem": - raise ValueError( - f"rollout_transport.retain is not yet supported with weight_broadcast.type = " - f"'{self.weight_broadcast.type}': a restarted trainer cannot rejoin its transfer group. " - "Use weight_broadcast.type = 'filesystem'." - ) - return self - - @model_validator(mode="after") - def resolve_mega_moe_max_tokens_per_rank(self): - """RL micro batches are one packed sequence of up to ``model.seq_len`` tokens, padded to - ``rl_micro_batch_multiple`` and split over the CP ranks.""" - dispatch = self.model.moe.dispatch - if dispatch.type == "mega_moe": - multiple = rl_micro_batch_multiple(self.model) - micro_batch_tokens = -(-self.model.seq_len // multiple) * multiple - dispatch.max_tokens_per_rank = mega_moe_max_tokens_per_rank( - dispatch.max_tokens_per_rank, micro_batch_tokens, self.model.cp - ) - return self diff --git a/packages/prime-rl-configs/src/prime_rl/utils/config.py b/packages/prime-rl-configs/src/prime_rl/utils/config.py index 31d6f576bae..510cc4bb725 100644 --- a/packages/prime-rl-configs/src/prime_rl/utils/config.py +++ b/packages/prime-rl-configs/src/prime_rl/utils/config.py @@ -3,61 +3,25 @@ import sys import tomllib from pathlib import Path -from typing import TYPE_CHECKING, Any +from typing import Any from pydantic import BaseModel -from pydantic_config import BaseConfig as BaseConfig # noqa: F401 from pydantic_config import cli # noqa: F401 -if TYPE_CHECKING: - from prime_rl.configs.inference import InferenceConfig - from prime_rl.configs.rl import RLConfig - def default_output_dir() -> Path: """Default output directory: ``$PRL_OUTPUT_DIR`` if set, else ``outputs``.""" return Path(os.environ.get("PRL_OUTPUT_DIR", "outputs")) -def dump_resolved_config(config: BaseModel, exclude: set[str] | dict[str, Any] | None = None) -> dict: +def dump_resolved_config(config: BaseModel) -> dict: """Dump a resolved config for a machine-written JSON artifact. Resolved configs are written as JSON, not TOML: JSON keeps nulls, so explicit None overrides (e.g. ``--trainer.optim.max-norm None``) round-trip exactly on re-parse. Hand-written configs stay TOML (sparse, commented); the format split is the marker. """ - return config.model_dump(exclude=exclude, mode="json") - - -def dump_pd_components(inference: "InferenceConfig") -> dict[str, dict]: - if inference.deployment.type != "disaggregated": - return {} - out: dict[str, dict] = {} - for role in ("prefill", "decode"): - role_config = dump_resolved_config( - inference.for_pd_role(role), exclude={"deployment", "slurm", "output_dir", "dry_run"} - ) - role_config["router"] = None - out[role] = role_config - return out - - -def dump_rl_components(config: "RLConfig") -> dict[str, dict]: - """Serialize a validated RL config without importing launchers or writing files. - - Keep arbitrary schema fields and explicit nulls. Hosted compilers can use - this from the CPU-only configs distribution, alongside the local launcher. - """ - components = { - "trainer": dump_resolved_config(config.trainer), - "orchestrator": dump_resolved_config(config.orchestrator), - } - if config.inference is not None: - exclude = {"slurm", "output_dir", "dry_run"} - if config.inference.deployment.type != "disaggregated": - exclude.add("deployment") - components["inference"] = dump_resolved_config(config.inference, exclude=exclude) - return components + return config.model_dump(mode="json") def resolve_client_roles(num_clients: int, roles: list[str | None] | None) -> list[str | None]: @@ -79,37 +43,6 @@ def resolve_client_roles(num_clients: int, roles: list[str | None] | None) -> li raise ValueError(f"Got {len(roles)} inference metric role(s) for {num_clients} admin client(s)") -def env_worker_pool_key(split: str, name: str) -> str: - """How a run names one of its env worker pools: ``/``.""" - return f"{split}/{name}" - - -def dump_env_worker_pool_components(config: "RLConfig") -> dict[str, dict]: - """The ``EnvWorkerPoolConfig`` of every pool the run starts, keyed by - ``env_worker_pool_key``, without writing files. - - An external orchestrator runs ``env-worker-pool @ `` for each, bound with - ``PRL_ENV_BIND_ADDRESS``, and tells the orchestrator where each listens with - ``PRL_ENV_ADDRESSES``. Unlike the local launcher's configs these carry no - ``address_file``, and paths are kept as configured rather than made absolute here. - """ - from prime_rl.configs.env_worker_pool import ROLLOUT_STORE_DIR, env_worker_pool_config - from prime_rl.configs.shared import ckpt_output_dir - - orchestrator = config.orchestrator - retain = config.rollout_transport is not None and config.rollout_transport.retain - save_dir = ckpt_output_dir(orchestrator.output_dir, orchestrator.ckpt) - return { - env_worker_pool_key(split, source.resolved_name): env_worker_pool_config( - source, - orchestrator.log, - save_dir, - store_dir=ROLLOUT_STORE_DIR if retain and split == "train" else None, - ) - for split, source in orchestrator.managed_env_sources - } - - def find_package_resource(subdir: str) -> Path | None: """Find a directory contributed to the `prime_rl` namespace package by any installed wheel. diff --git a/packages/prime-rl-configs/src/prime_rl/configs/diff.py b/packages/prime-rl-configs/src/prime_rl/utils/diff.py similarity index 100% rename from packages/prime-rl-configs/src/prime_rl/configs/diff.py rename to packages/prime-rl-configs/src/prime_rl/utils/diff.py diff --git a/packages/prime-rl-configs/src/prime_rl/utils/validation.py b/packages/prime-rl-configs/src/prime_rl/utils/validation.py index 78984ad667f..f8555703b22 100644 --- a/packages/prime-rl-configs/src/prime_rl/utils/validation.py +++ b/packages/prime-rl-configs/src/prime_rl/utils/validation.py @@ -79,30 +79,6 @@ def propagate(shared_path: str, *targets: str) -> None: "inference.log.json_logging", ) - # [ckpt] leaves. (Bare empty ``[ckpt]`` block enablement is at the end.) - for leaf in ("output_dir", "interval", "keep_last", "keep_interval"): - propagate(f"ckpt.{leaf}", f"trainer.ckpt.{leaf}", f"orchestrator.ckpt.{leaf}") - propagate("ckpt.rollouts", "orchestrator.ckpt.rollouts") - propagate("ckpt.rollouts_save_timeout", "orchestrator.ckpt.rollouts_save_timeout") - propagate("ckpt.async_save", "trainer.ckpt.async_save") - propagate("ckpt.remote", "trainer.ckpt.remote") - - # [monitors.wandb] leaves. (Bare empty ``[monitors.wandb]`` block enablement is at the end.) - # ``monitors.wandb.name`` flows verbatim to both sub-configs: the rl entrypoint - # always runs W&B in shared mode, so both log to one run. - for leaf in ("project", "entity", "name", "group", "tags", "offline"): - propagate( - f"monitors.wandb.{leaf}", - f"trainer.monitors.wandb.{leaf}", - f"orchestrator.monitors.wandb.{leaf}", - ) - - # [monitors.file] leaf. (Bare empty ``[monitors.file]`` block enablement is at the end.) - propagate("monitors.file.path", "trainer.monitors.file.path", "orchestrator.monitors.file.path") - - # [monitors.prime] leaf. - propagate("monitors.prime.name", "trainer.monitors.prime.name", "orchestrator.monitors.prime.name") - # [tokenizer]. ``name`` also flows to ``inference.vllm`` (vLLM's ``--tokenizer``, which also picks its "auto" # parsers) and ``chat_template`` too (vLLM's ``--chat-template``); ``trust_remote_code`` can legitimately differ # between sub-configs (auto-derived from model names, which may differ for FP8-quantized inference variants). @@ -119,25 +95,12 @@ def propagate(shared_path: str, *targets: str) -> None: "inference.vllm.chat_template", ) - propagate("resume", "trainer.resume", "orchestrator.resume") - - # [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node). - propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport") - - # Top-level scalars. - propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps") propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len") # [deployment] gpus_per_node → inference: the nested inference deployment sizes its # engines per node from its own copy. propagate("deployment.gpus_per_node", "inference.deployment.gpus_per_node") - # [slurm] → inference: a multi-node RL run drives its inference deployment under - # the same SLURM allocation, so the nested inference inherits [slurm]. This is - # what lets the nested InferenceConfig's multi-node / disaggregated SLURM check - # pass (the per-rank inference.toml drops slurm, so each rank still runs locally). - propagate("slurm", "inference.slurm") - # Cascade trainer.tokenizer.chat_template → inference.vllm.chat_template # (vLLM ``--chat-template``). Read trainer's value *after* the shared # propagation above so we cover both: @@ -150,32 +113,6 @@ def propagate(shared_path: str, *targets: str) -> None: if trainer_chat_template is not None: fill("inference.vllm.chat_template", trainer_chat_template) - # Bare ``[ckpt]`` / ``[monitors.wandb]`` block: presence-only signal that - # enables the section with defaults on both sub-configs. Necessary because - # ``trainer.ckpt`` / ``orchestrator.ckpt`` are Optional[None] by default — - # without this an empty shared block would be a no-op. Leaf-level conflicts - # (e.g. shared ``ckpt.interval`` vs ``trainer.ckpt.interval``) are already - # caught above; the bare block is exempt because ``[ckpt]`` + - # ``[trainer.ckpt] skip_optimizer = true`` is a legitimate "enable + customise - # per side" pattern. CLI ``--no-ckpt`` / ``--no-monitors.wandb`` land as the - # *string* ``"None"`` until ``BaseConfig``'s parent-class validator converts - # it, which happens after this one — the disable must propagate too, since - # the monitor sub-configs default to enabled. - presence_targets = { - "ckpt": ("trainer", "orchestrator"), - "monitors.wandb": ("trainer", "orchestrator"), - "monitors.file": ("trainer", "orchestrator"), - "monitors.prime": ("trainer", "orchestrator"), - } - for key, targets in presence_targets.items(): - value = get(key) - if isinstance(value, dict): - for target in targets: - fill(f"{target}.{key}", {}) - elif value == "None": - for target in targets: - fill(f"{target}.{key}", "None") - if conflicts: lines = [ "Shared config conflicts with matching sub-config field(s). Pick one place " diff --git a/pyproject.toml b/pyproject.toml index 0deb4a02d89..552a9c01b9d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,11 +45,12 @@ rl = "prime_rl.entrypoints.rl:main" sft = "prime_rl.entrypoints.sft:main" pretrain = "prime_rl.entrypoints.pretrain:main" inference = "prime_rl.entrypoints.inference:main" -router = "prime_rl.entrypoints.router:main" -trainer = "prime_rl.entrypoints.trainer:main" -orchestrator = "prime_rl.entrypoints.orchestrator:main" +router = "prime_rl.components.router:main" +engine = "prime_rl.components.engine:main" +trainer = "prime_rl.components.trainer:main" +orchestrator = "prime_rl.components.orchestrator:main" eval = "prime_rl.entrypoints.eval:main" -env-worker-pool = "prime_rl.entrypoints.env_worker_pool:main" +env-worker-pool = "prime_rl.components.env_worker_pool:main" dashboard = "prime_rl.entrypoints.dashboard:main" [project.entry-points."vllm.general_plugins"] diff --git a/skills/configs/SKILL.md b/skills/configs/SKILL.md index cc47b5afca7..a1947f7af84 100644 --- a/skills/configs/SKILL.md +++ b/skills/configs/SKILL.md @@ -92,6 +92,6 @@ In TOML, an empty section header (`[ckpt]`) does the same. ## Key files -- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli` +- `packages/prime-rl-configs/src/prime_rl/configs/` — `entrypoints/` holds the public configs users write (`RLConfig`, `SFTConfig`, ...); `components/` holds the configs each process reads (`TrainerConfig`, `OrchestratorConfig`, `RouterConfig`, ...); `blocks/` holds the blocks that several modules use; `base.py` holds `BaseConfig` and the entrypoint/component contract. Find a field by its TOML path (`[trainer.optim]` → `components/trainer/optim.py`); the layout rules are in the package README. `utils/config.py` re-exports `cli` - `dev/` — debug configs and small environment runs (e.g. `examples/reverse-text/`) - `recipes/` — frontier-model configs, one folder per model diff --git a/skills/eval/SKILL.md b/skills/eval/SKILL.md index a3dfbac52be..fc600085887 100644 --- a/skills/eval/SKILL.md +++ b/skills/eval/SKILL.md @@ -21,7 +21,7 @@ uv run eval @ eval.toml --dry-run # resolve an uv run eval @ eval.toml --no-monitors.prime # keep the run off the platform (on by default) ``` -- Config: `EvalConfig` (`packages/prime-rl-configs/src/prime_rl/configs/eval.py`); `uv run eval -h` lists the fields. +- Config: `EvalConfig` (`packages/prime-rl-configs/src/prime_rl/configs/entrypoints/eval.py`); `uv run eval -h` lists the fields. - Entrypoint: `src/prime_rl/entrypoints/eval.py`; implementation `src/prime_rl/eval/eval.py`, shared engine `src/prime_rl/eval/runner.py`. - Shorthands (single-source runs): ``, `--env. `, `-n` `select.limit`, `-s` `select.shuffle`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. `` cannot be combined with a TOML that defines `[[source]]` blocks; next to such a TOML, `--env.` sets the shared `env` block. - Concurrency: an API exposes no vLLM `/metrics`, so run pinned there; against `uv run inference` set `min_inflight < max_inflight` in `[concurrency]` to adapt to the engines' load (queued share and measured throughput; `docs/inference.md`). diff --git a/skills/model-factory/SKILL.md b/skills/model-factory/SKILL.md index e77bfb310c9..e0daa0a692f 100644 --- a/skills/model-factory/SKILL.md +++ b/skills/model-factory/SKILL.md @@ -125,8 +125,8 @@ import sys import tomllib from pathlib import Path -from prime_rl.configs.rl import RLConfig -from prime_rl.configs.sft import SFTConfig +from prime_rl.configs.entrypoints.rl import RLConfig +from prime_rl.configs.entrypoints.sft import SFTConfig data = tomllib.loads(Path(sys.argv[1]).read_text()) schema = SFTConfig if "data" in data and not {"trainer", "orchestrator"} & data.keys() else RLConfig diff --git a/skills/training/start-run/SKILL.md b/skills/training/start-run/SKILL.md index 6bc94323ff2..ec424ec2d4f 100644 --- a/skills/training/start-run/SKILL.md +++ b/skills/training/start-run/SKILL.md @@ -42,7 +42,7 @@ uv run rl @ dev/examples/reverse-text/rl.toml uv run rl @ dev/examples/reverse-text/rl.toml --dry-run # write scripts, don't run ``` -- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`) +- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/entrypoints/rl.py`) - Entrypoint: `src/prime_rl/entrypoints/rl.py` - SLURM: single- and multi-node - Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`. @@ -67,14 +67,14 @@ uv run sft @ dev/examples/reverse-text/sft.toml --slurm uv run sft @ dev/examples/reverse-text/sft.toml --dry-run ``` -- Config: `SFTConfig` (`packages/prime-rl-configs/src/prime_rl/configs/sft.py`) +- Config: `SFTConfig` (`packages/prime-rl-configs/src/prime_rl/configs/entrypoints/sft.py`) - Entrypoint: `src/prime_rl/entrypoints/sft.py` - SLURM: single- and multi-node - Multi-node online evals use one SLURM job with `num_train_nodes + num_infer_nodes` nodes. The generated `launcher/sft.sbatch` assigns inference nodes first, then trainer nodes. ## `inference` — vLLM server -OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly. The default `sticky_least_loaded` policy keeps each rollout on one replica while assigning new sessions to the least-loaded replica; RL and SFT online eval automatically release completed sessions. +OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default `server.port + 100`, i.e. 8100); admin endpoints must target the engine port directly. The default `sticky_least_loaded` policy keeps each rollout on one replica while assigning new sessions to the least-loaded replica; RL and SFT online eval automatically release completed sessions. ```bash uv run inference --vllm.model Qwen/Qwen3-0.6B @@ -91,7 +91,7 @@ curl http://localhost:8000/v1/chat/completions \ -d '{"model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "Hi"}], "max_tokens": 50}' ``` -- Config: `InferenceConfig` (`packages/prime-rl-configs/src/prime_rl/configs/inference.py`) +- Config: `InferenceConfig` (`packages/prime-rl-configs/src/prime_rl/configs/entrypoints/inference.py`) - Entrypoint: `src/prime_rl/entrypoints/inference.py` - SLURM: single-node, multi-node, and disaggregated deployments diff --git a/src/prime_rl/components/engine.py b/src/prime_rl/components/engine.py new file mode 100644 index 00000000000..eed75da2b77 --- /dev/null +++ b/src/prime_rl/components/engine.py @@ -0,0 +1,63 @@ +import os +import resource + +from prime_rl.configs.components.engine import EngineConfig +from prime_rl.utils.config import cli +from prime_rl.utils.logger import setup_logger +from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, DEFAULT_INFERENCE_ENV_VARS, set_proc_title + + +def apply_multi_node_dp_env(config: EngineConfig) -> None: + """Resolve hybrid-LB DP start rank and head address from PRL_DP_* env vars when a DP group spans nodes.""" + dp_local = config.vllm.data_parallel_size_local or config.vllm.data_parallel_size + if config.vllm.data_parallel_size <= dp_local: + return + raw_rank = os.environ.get("PRL_DP_NODE_RANK") + if raw_rank is None: + return + node_rank = int(raw_rank) + if node_rank < 0: + raise ValueError(f"PRL_DP_NODE_RANK must be non-negative, got {node_rank}") + if getattr(config.vllm, "data_parallel_start_rank", None) is None: + config.vllm.data_parallel_start_rank = node_rank * dp_local + if getattr(config.vllm, "data_parallel_address", None) is None: + var = "PRL_DP_BIND_HOST" if node_rank == 0 else "PRL_DP_HEAD_HOST" + head = os.environ.get(var) + if not head: + raise ValueError(f"Multi-node DP node rank {node_rank} requires {var} to be set") + config.vllm.data_parallel_address = head + + +def setup_engine_process(config: EngineConfig) -> None: + """Prepare this process to serve an engine. Call it before vLLM is imported and before a router starts.""" + from prime_rl.inference.server import setup_vllm_env + + apply_multi_node_dp_env(config) + + # The launchers inject the same env into a server subprocess. config.env_vars wins over the defaults; the + # existing os.environ loses. + os.environ.update({**DEFAULT_COMMON_ENV_VARS, **DEFAULT_INFERENCE_ENV_VARS, **config.env_vars}) + setup_vllm_env(config) + + # The router and the engine hold a socket per in-flight request; a 1024 soft limit runs out at ~500. + _, hard_nofile = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (hard_nofile, hard_nofile)) + + +def engine(config: EngineConfig) -> None: + logger = setup_logger(config.log.level, json_logging=config.log.json_logging) + setup_engine_process(config) + logger.info(f"Starting inference on http://{config.server.host or '0.0.0.0'}:{config.server.port}/v1\n") + + from prime_rl.inference.vllm.server import server # pyright: ignore + + server(config) + + +def main(): + set_proc_title("Engine") + engine(cli(EngineConfig)) + + +if __name__ == "__main__": + main() diff --git a/src/prime_rl/entrypoints/env_worker_pool.py b/src/prime_rl/components/env_worker_pool.py similarity index 99% rename from src/prime_rl/entrypoints/env_worker_pool.py rename to src/prime_rl/components/env_worker_pool.py index 0d6829de9c8..9949301edce 100644 --- a/src/prime_rl/entrypoints/env_worker_pool.py +++ b/src/prime_rl/components/env_worker_pool.py @@ -15,7 +15,7 @@ from verifiers.v1.configs.agent import agent_config_fields from verifiers.v1.runtimes import set_base_sandbox_labels -from prime_rl.configs.env_worker_pool import EnvWorkerPoolConfig +from prime_rl.configs.components.env_worker_pool import EnvWorkerPoolConfig from prime_rl.env import run_env_worker_pool, set_episode_hook from prime_rl.env.sample_server import run_sample_server from prime_rl.env.sandbox_owners import register_sandbox_pool diff --git a/src/prime_rl/entrypoints/orchestrator.py b/src/prime_rl/components/orchestrator.py similarity index 91% rename from src/prime_rl/entrypoints/orchestrator.py rename to src/prime_rl/components/orchestrator.py index 4434e1b4d0e..6488ef28fc2 100644 --- a/src/prime_rl/entrypoints/orchestrator.py +++ b/src/prime_rl/components/orchestrator.py @@ -11,7 +11,7 @@ import asyncio -from prime_rl.configs.orchestrator import OrchestratorConfig +from prime_rl.configs.components.orchestrator import OrchestratorConfig from prime_rl.utils.config import check_mode, cli from prime_rl.utils.process import set_proc_title diff --git a/src/prime_rl/components/router.py b/src/prime_rl/components/router.py new file mode 100644 index 00000000000..5209b1d7895 --- /dev/null +++ b/src/prime_rl/components/router.py @@ -0,0 +1,69 @@ +import os +import resource + +from prime_rl.configs.components.router import RouterConfig +from prime_rl.utils.config import cli + + +def router_command(config: RouterConfig) -> list[str]: + """The vllm-router command line for ``config``.""" + is_pd = bool(config.prefill_urls or config.decode_urls) + if is_pd: + if config.worker_urls: + raise ValueError("Specify either worker_urls or prefill_urls/decode_urls, not both.") + if not config.prefill_urls or not config.decode_urls: + raise ValueError("Disaggregated routing requires both prefill_urls and decode_urls.") + elif not config.worker_urls: + raise ValueError("Colocated routing requires at least one entry in worker_urls.") + + cmd = [ + "vllm-router", + "--policy", + config.router.policy, + "--host", + config.host, + "--port", + str(config.port), + "--request-id-headers", + "x-session-id", + "--request-timeout-secs", + str(config.router.request_timeout_secs), + "--worker-startup-timeout-secs", + "4200", + # Default 30s check interval delays initial engine admission. + "--worker-startup-check-interval", + "1", + ] + if config.prometheus_port is not None: + cmd.extend(["--prometheus-port", str(config.prometheus_port)]) + + if is_pd: + cmd.append("--vllm-pd-disaggregation") + for url in config.prefill_urls: + cmd.extend(["--prefill", url]) + for url in config.decode_urls: + cmd.extend(["--decode", url]) + if config.intra_node_data_parallel_size > 1: + cmd.extend(["--intra-node-data-parallel-size", str(config.intra_node_data_parallel_size)]) + cmd.extend(["--pd-turn-retries", str(config.router.pd_turn_retries)]) + if config.pd_bidirectional_ttl_s is not None: + cmd.extend(["--pd-bidirectional-kv", "--pd-bidirectional-ttl-secs", str(config.pd_bidirectional_ttl_s)]) + else: + cmd.extend( + ["--intra-node-data-parallel-size", str(config.intra_node_data_parallel_size), "--worker-urls"] + + config.worker_urls + ) + + return cmd + + +def main() -> None: + cmd = router_command(cli(RouterConfig)) + # The router holds a socket per in-flight request; a 1024 soft limit runs out at ~500. + _, hard_nofile = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (hard_nofile, hard_nofile)) + os.execvp(cmd[0], cmd) + + +if __name__ == "__main__": + main() diff --git a/src/prime_rl/entrypoints/trainer.py b/src/prime_rl/components/trainer.py similarity index 92% rename from src/prime_rl/entrypoints/trainer.py rename to src/prime_rl/components/trainer.py index 9c2367296c6..8ee957ee123 100644 --- a/src/prime_rl/entrypoints/trainer.py +++ b/src/prime_rl/components/trainer.py @@ -8,7 +8,7 @@ the ``rl`` launcher under torchrun). """ -from prime_rl.configs.trainer import TrainerConfig +from prime_rl.configs.components.trainer import TrainerConfig from prime_rl.utils.config import check_mode, cli from prime_rl.utils.process import set_proc_title diff --git a/src/prime_rl/control/controller.py b/src/prime_rl/control/controller.py index f5866df41d9..aa93e0ffda1 100644 --- a/src/prime_rl/control/controller.py +++ b/src/prime_rl/control/controller.py @@ -6,7 +6,6 @@ from pydantic import BaseModel, ValidationError -from prime_rl.configs.diff import ConfigChange, diff_config, frozen_raw_changes from prime_rl.control.types import ( Action, ActionNotFoundError, @@ -18,6 +17,7 @@ UpdateConfigRequest, ) from prime_rl.utils.config import dump_resolved_config +from prime_rl.utils.diff import ConfigChange, diff_config, frozen_raw_changes from prime_rl.utils.logger import get_logger CheckConfig = Callable[[dict[str, Any]], tuple[BaseModel, list[ConfigChange]]] diff --git a/src/prime_rl/control/server.py b/src/prime_rl/control/server.py index de9b465d803..e05383374e6 100644 --- a/src/prime_rl/control/server.py +++ b/src/prime_rl/control/server.py @@ -7,7 +7,8 @@ from fastapi import FastAPI, Request, status from fastapi.responses import JSONResponse -from prime_rl.configs.shared import ADMIN_TOKEN_HEADER, ControlConfig +from prime_rl.configs.blocks.client import ADMIN_TOKEN_HEADER +from prime_rl.configs.blocks.run import ControlConfig from prime_rl.control.app import create_app from prime_rl.control.controller import Controller from prime_rl.utils.admin_token import admin_token_matches, digest_var, expected_admin_digest diff --git a/src/prime_rl/control/types.py b/src/prime_rl/control/types.py index 79cac8adc9d..f0fdbdefe02 100644 --- a/src/prime_rl/control/types.py +++ b/src/prime_rl/control/types.py @@ -5,10 +5,10 @@ from pydantic import BaseModel, Field -from prime_rl.configs.diff import ConfigChange +from prime_rl.utils.diff import ConfigChange if TYPE_CHECKING: - from prime_rl.configs.orchestrator import OrchestratorConfig + from prime_rl.configs.components.orchestrator import OrchestratorConfig ActionState = Literal["pending", "accepted", "committed", "applied"] """A pause or checkpoint goes pending -> accepted -> committed, a config update pending -> applied.""" diff --git a/src/prime_rl/entrypoints/dashboard.py b/src/prime_rl/entrypoints/dashboard.py index 6217af6f03c..931c8cb8945 100644 --- a/src/prime_rl/entrypoints/dashboard.py +++ b/src/prime_rl/entrypoints/dashboard.py @@ -32,7 +32,7 @@ from prime_rl.utils.pathing import CACHE_DIR if TYPE_CHECKING: - from prime_rl.configs.monitors import MonitorsConfig + from prime_rl.configs.blocks.monitors import MonitorsConfig STATE_DIR = CACHE_DIR / "dashboard" DAEMON_FILE = STATE_DIR / "daemon.json" diff --git a/src/prime_rl/entrypoints/eval.py b/src/prime_rl/entrypoints/eval.py index ab2f8434004..26e0a5584a2 100644 --- a/src/prime_rl/entrypoints/eval.py +++ b/src/prime_rl/entrypoints/eval.py @@ -16,10 +16,10 @@ from subprocess import Popen from typing import Any -from prime_rl.configs.eval import EvalConfig -from prime_rl.configs.shared import ControlConfig +from prime_rl.configs.blocks.run import ControlConfig +from prime_rl.configs.entrypoints.eval import EvalConfig from prime_rl.utils.admin_token import AdminTokenUses, TokenUse -from prime_rl.utils.config import check_mode, cli, config_files, dump_resolved_config +from prime_rl.utils.config import check_mode, cli, config_files from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes, set_proc_title USAGE = """\ @@ -117,11 +117,13 @@ def main(): from prime_rl.entrypoints.dashboard import ensure_dashboard, log_run_links, run_links from prime_rl.utils.logger import setup_logger from prime_rl.utils.pathing import ( + env_worker_pool_command, format_config_message, format_log_message, prepare_attempt_dirs, prepare_run, - write_env_worker_pool_config, + write_component_configs, + write_config, write_launch_artifacts, ) @@ -135,22 +137,18 @@ def main(): logger.info("Starting eval") write_launch_artifacts(config_dir, "eval") - (config_dir / "eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2)) - components: list[tuple[str, Path | str]] = [("Eval", config_dir / "eval.json")] + write_config(config_dir / "eval.json", config) # One env worker pool per source without an explicit `serve.address`, like the rl launcher's: # `env-worker-pool @ ` binds an OS-assigned port and publishes it to the source's # address file, where the eval picks it up. + write_component_configs(config_dir, config.components()) + components: list[tuple[str, Path | str]] = [("Eval", config_dir / "eval.json")] env_worker_pools = [source for source in config.source if source.serve.address is None] env_names = [source.resolved_name for source in env_worker_pools] if env_worker_pools: components.append(("Envs", f"{config_dir}/envs/eval/*.json")) - for source in env_worker_pools: - components.append( - ( - f" {source.resolved_name}", - write_env_worker_pool_config(config_dir, "eval", source, config.log, config.run_dir), - ) - ) + for name in env_names: + components.append((f" {name}", config_dir / "envs" / "eval" / f"{name}.json")) if config.dry_run: logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}") logger.success("Dry run complete. To start the eval, remove --dry-run from your command.") @@ -173,7 +171,7 @@ def main(): with open(env_worker_pool_log, "w") as log_file_handle: processes.append( Popen( - ["env-worker-pool", "@", (config_dir / "envs" / "eval" / f"{name}.json").as_posix()], + env_worker_pool_command(config_dir, "eval", name), env=pool_env, stdout=log_file_handle, stderr=log_file_handle, diff --git a/src/prime_rl/entrypoints/inference.py b/src/prime_rl/entrypoints/inference.py index 25e24b9dc7d..86e2348be51 100644 --- a/src/prime_rl/entrypoints/inference.py +++ b/src/prime_rl/entrypoints/inference.py @@ -1,27 +1,28 @@ import json import os -import resource import signal import subprocess from pathlib import Path from threading import Event, Thread from typing import Any -from prime_rl.configs.inference import ( - InferenceConfig, - MooncakeKVCacheOffloadConfig, - prefill_uses_deepep_high_throughput, -) -from prime_rl.entrypoints.router import build_vllm_router_cmd +from prime_rl.components.engine import setup_engine_process +from prime_rl.components.router import router_command +from prime_rl.configs.components.engine.deployment import prefill_uses_deepep_high_throughput +from prime_rl.configs.components.engine.kv_cache import MooncakeKVCacheOffloadConfig +from prime_rl.configs.components.router import RouterConfig +from prime_rl.configs.entrypoints.inference import InferenceConfig, InferenceSection from prime_rl.entrypoints.slurm import load_slurm_template, submit_sbatch from prime_rl.utils.admin_token import digest_var -from prime_rl.utils.config import cli, dump_pd_components, dump_resolved_config +from prime_rl.utils.config import cli from prime_rl.utils.logger import setup_logger from prime_rl.utils.pathing import ( format_log_message, get_launcher_dir, get_launcher_log_dir, prepare_attempt_dirs, + write_component_configs, + write_config, write_launch_artifacts, ) from prime_rl.utils.process import ( @@ -32,6 +33,7 @@ ) INFERENCE_CONFIG = "inference.json" +ENGINE_CONFIG = "engine.json" INFERENCE_SBATCH = "inference.sbatch" @@ -46,31 +48,7 @@ def vllm_overrides_fragment(overrides: dict[str, Any]) -> str: return ", " + json.dumps(overrides)[1:-1].replace('"', '\\"') -def write_config( - config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None, engine_only: bool = False -) -> Path: - """Write resolved config to disk. - - With ``engine_only``, the router is nulled so per-rank processes run bare - engines — the sbatch script starts the single global router. - """ - output_dir.mkdir(parents=True, exist_ok=True) - config_path = output_dir / INFERENCE_CONFIG - config_dict = dump_resolved_config(config, exclude=exclude) - if engine_only: - config_dict["router"] = None - with open(config_path, "w") as f: - json.dump(config_dict, f, indent=2) - return config_path - - -def write_pd_configs(config: InferenceConfig, output_dir: Path) -> None: - """Write one engine config per P/D role (``inference-{role}.json``); the sbatch picks it by ``$ROLE``.""" - for role, role_config in dump_pd_components(config).items(): - (output_dir / f"inference-{role}.json").write_text(json.dumps(role_config, indent=2)) - - -def mooncake_offloads(config: InferenceConfig | None) -> dict[str, MooncakeKVCacheOffloadConfig]: +def mooncake_offloads(config: InferenceSection | None) -> dict[str, MooncakeKVCacheOffloadConfig]: """Mooncake offload per role (``prefill``/``decode``, or ``all``), for the shared-store launch in the SLURM templates.""" if config is None: return {} @@ -128,7 +106,6 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, log_dir: Path config.deployment.prefill_vllm_overrides ), decode_vllm_extra_json=vllm_overrides_fragment(config.deployment.decode_vllm_overrides), - pd_bidirectional=config.deployment.bidirectional_kv_transfer, nixl_nic_affinity=config.deployment.nixl_nic_affinity, ) elif is_multi_node: @@ -154,14 +131,12 @@ def inference_slurm(config: InferenceConfig): config_dir, log_dir = prepare_attempt_dirs(config.output_dir) write_launch_artifacts(config_dir, "inference") - is_multi_node = config.deployment.type in ("multi_node", "disaggregated") - exclude = {"deployment", "slurm", "dry_run"} if is_multi_node else {"slurm", "dry_run"} - config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node) - write_pd_configs(config, config_dir) - logger.info(f"Wrote config to {config_path}") + write_config(config_dir / INFERENCE_CONFIG, config) + write_component_configs(config_dir, config.components()) + logger.info(f"Wrote configs to {config_dir}") script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH - write_slurm_script(config, config_path, log_dir, script_path) + write_slurm_script(config, config_dir / ENGINE_CONFIG, log_dir, script_path) logger.info(f"Wrote SLURM script to {script_path}") num_nodes = getattr(config.deployment, "num_nodes", 1) @@ -174,78 +149,31 @@ def inference_slurm(config: InferenceConfig): submit_sbatch(script_path, log_message) -def start_router(config: InferenceConfig) -> subprocess.Popen: - """Start the vllm-router on ``server.port``, fronting the local engine at ``backend_port``.""" - host = config.server.host - worker_host = "localhost" if host in (None, "0.0.0.0") else host - cmd = build_vllm_router_cmd( - router=config.router, - host=host or "0.0.0.0", - port=config.server.port, - intra_node_dp=config.vllm.data_parallel_size_local or config.vllm.data_parallel_size, - worker_urls=[f"http://{worker_host}:{config.backend_port}"], - prometheus_port=config.server.port + 21000, - ) +def start_router(config: RouterConfig, admin_token_var: str) -> subprocess.Popen: + """Start the vllm-router of ``config``.""" # The router never calls the engine's admin routes. - token_vars = (config.server.admin_token_var, digest_var(config.server.admin_token_var)) + token_vars = (admin_token_var, digest_var(admin_token_var)) env = {key: value for key, value in os.environ.items() if key not in token_vars} - return subprocess.Popen(cmd, env=env) - - -def apply_multi_node_dp_env(config: InferenceConfig) -> None: - """Resolve hybrid-LB DP start rank and head address from PRL_DP_* env vars when a DP group spans nodes.""" - dp_local = config.vllm.data_parallel_size_local or config.vllm.data_parallel_size - if config.vllm.data_parallel_size <= dp_local: - return - raw_rank = os.environ.get("PRL_DP_NODE_RANK") - if raw_rank is None: - return - node_rank = int(raw_rank) - if node_rank < 0: - raise ValueError(f"PRL_DP_NODE_RANK must be non-negative, got {node_rank}") - if getattr(config.vllm, "data_parallel_start_rank", None) is None: - config.vllm.data_parallel_start_rank = node_rank * dp_local - if getattr(config.vllm, "data_parallel_address", None) is None: - var = "PRL_DP_BIND_HOST" if node_rank == 0 else "PRL_DP_HEAD_HOST" - head = os.environ.get(var) - if not head: - raise ValueError(f"Multi-node DP node rank {node_rank} requires {var} to be set") - config.vllm.data_parallel_address = head + return subprocess.Popen(router_command(config), env=env) def inference_local(config: InferenceConfig): """Run inference locally: a router on ``server.port`` fronting the engine on ``backend_port``.""" - from prime_rl.inference.server import setup_vllm_env - logger = setup_logger(config.log.level, json_logging=config.log.json_logging) if config.dry_run: logger.success("Dry run complete. To start inference locally, remove --dry-run from your command.") return - apply_multi_node_dp_env(config) - - host = config.server.host or "0.0.0.0" - port = config.server.port - - # Apply the inference env (defaults + [inference.env_vars]) in-process so a standalone - # `uv run inference` gets the same environment the rl/SLURM launchers inject into the - # server subprocess. config.env_vars wins over the defaults; existing os.environ loses. - os.environ.update({**DEFAULT_COMMON_ENV_VARS, **DEFAULT_INFERENCE_ENV_VARS, **config.env_vars}) - - setup_vllm_env(config) - - # The router holds a socket per in-flight request on each side; a 1024 soft limit runs out at ~500. - _, hard_nofile = resource.getrlimit(resource.RLIMIT_NOFILE) - resource.setrlimit(resource.RLIMIT_NOFILE, (hard_nofile, hard_nofile)) + engine = config.engine_config(config.weight_broadcast.type) + router = config.router_config() + setup_engine_process(engine) router_process: subprocess.Popen | None = None router_stopping = Event() - if config.router is not None: - logger.info(f"Starting router on http://{host}:{port}/v1 (engine on port {config.backend_port})\n") - router_process = start_router(config) - # The router owns the client-facing port; the engine moves behind it. - config.server.port = config.backend_port + if router is not None: + logger.info(f"Starting router on http://{router.host}:{router.port}/v1 (engine on port {engine.server.port})\n") + router_process = start_router(router, engine.server.admin_token_var) def watch_router(): router_process.wait() @@ -255,12 +183,12 @@ def watch_router(): Thread(target=watch_router, daemon=True).start() else: - logger.info(f"Starting inference on http://{host}:{port}/v1\n") + logger.info(f"Starting inference on http://{engine.server.host or '0.0.0.0'}:{engine.server.port}/v1\n") from prime_rl.inference.vllm.server import server # pyright: ignore try: - server(config) + server(engine) finally: if router_process is not None: router_stopping.set() diff --git a/src/prime_rl/entrypoints/launcher.py b/src/prime_rl/entrypoints/launcher.py index 5e9b774ae6c..d1cbd498012 100644 --- a/src/prime_rl/entrypoints/launcher.py +++ b/src/prime_rl/entrypoints/launcher.py @@ -3,28 +3,27 @@ import sys from pathlib import Path -from prime_rl.configs.eval import SFTOnlineEvalConfig -from prime_rl.configs.orchestrator import OnlineEvalSourceConfig -from prime_rl.configs.shared import LogConfig -from prime_rl.configs.supervised import BaseValConfig, SupervisedTrainerConfig +from prime_rl.configs.components.orchestrator.sources import OnlineEvalSourceConfig +from prime_rl.configs.components.trainer.data import BaseValConfig +from prime_rl.configs.entrypoints._supervised import SupervisedConfig from prime_rl.entrypoints.dashboard import ensure_dashboard, log_run_links, run_links from prime_rl.entrypoints.modelexpress_server import modelexpress_template_vars, start_modelexpress from prime_rl.entrypoints.slurm import load_slurm_template, submit_sbatch from prime_rl.scripts.resume_cleanup import clean_resume_state, resolve_resume_step from prime_rl.utils.admin_token import AdminTokenUses, TokenUse -from prime_rl.utils.config import dump_resolved_config from prime_rl.utils.logger import setup_logger from prime_rl.utils.pathing import ( + env_worker_pool_command, format_config_message, format_log_message, - get_broadcast_dir, get_ckpt_dir, get_launcher_dir, get_launcher_log_dir, launcher_attempt_env, prepare_attempt_dirs, prepare_run, - write_env_worker_pool_config, + write_component_configs, + write_config, write_launch_artifacts, ) from prime_rl.utils.process import ( @@ -37,14 +36,14 @@ ) TRAINER_CONFIG = "trainer.json" - -INFERENCE_CONFIG = "inference.json" -ONLINE_EVAL_CONFIG = "eval.json" +ENGINE_CONFIG = "engine.json" +ROUTER_CONFIG = "router.json" +ONLINE_EVAL_CONFIG = "online-eval.json" ENVS_DIR = "envs" -def eval_env_worker_pools(config: SupervisedTrainerConfig) -> list[OnlineEvalSourceConfig]: +def eval_env_worker_pools(config: SupervisedConfig) -> list[OnlineEvalSourceConfig]: """Every launcher-managed eval source. A source with ``serve.address`` set is externally managed — the launcher neither writes its config nor spawns a server for it.""" if config.eval is None: @@ -52,7 +51,7 @@ def eval_env_worker_pools(config: SupervisedTrainerConfig) -> list[OnlineEvalSou return [source for source in config.eval.source if source.serve.address is None] -def admin_token_uses(config: SupervisedTrainerConfig) -> AdminTokenUses: +def admin_token_uses(config: SupervisedConfig) -> AdminTokenUses: """The online evals call the engines' admin routes, so they get the token; the inference server and the control APIs only check it, so they get its digest.""" online_eval = config.eval @@ -68,86 +67,36 @@ def admin_token_uses(config: SupervisedTrainerConfig) -> AdminTokenUses: ) -def get_ckpt_base(config: SupervisedTrainerConfig) -> Path: +def get_ckpt_base(config: SupervisedConfig) -> Path: """Where checkpoints live: ``ckpt.output_dir`` when set, else the run dir.""" return (config.ckpt.output_dir if config.ckpt else None) or config.run_dir -def build_online_eval_config(config: SupervisedTrainerConfig) -> SFTOnlineEvalConfig: - """The online-eval process's config: the resolved ``[eval]`` block with the run-level - fields filled from the SFT config. The launcher spawns the env worker pools itself; the - online-eval process finds each one through the address it publishes in the shared - config attempt.""" - assert config.eval is not None - eval_config = config.eval.model_copy(deep=True) - run_fields = dict( - model=config.model.name, - weight_broadcast=config.weight_broadcast, - broadcasts_dir=get_broadcast_dir(config.run_dir), - max_steps=config.max_steps, - resume_step=resolve_resume_step(config.resume, get_ckpt_dir(get_ckpt_base(config))), - # Same run dir as the trainer: the dashboard reads the eval's - # file-monitor artifacts from the run directory, so a separate - # output dir would hide them. The train-vs-eval record collision - # is resolved by record merging in prime_rl.monitors.prime, not - # by directory separation. - output_dir=config.run_dir, - log=LogConfig(level=config.log.level, json_logging=config.log.json_logging), - monitors=config.monitors, - ) - return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields}) - - -def config_components( - config: SupervisedTrainerConfig, config_dir: Path, entrypoint: str -) -> list[tuple[str, Path | str]]: - """The resolved configs a launch leaves in ``config_dir``: the entrypoint's config and, with - online evals, the inference, online-eval and env-worker-pool configs.""" - components: list[tuple[str, Path | str]] = [(entrypoint, config_dir / f"{entrypoint}.json")] - if config.deployment.type == "multi_node": - components.append(("Trainer", config_dir / TRAINER_CONFIG)) +def config_components(config: SupervisedConfig, config_dir: Path, entrypoint: str) -> list[tuple[str, Path | str]]: + """The resolved configs ``write_configs`` leaves in ``config_dir``.""" + components: list[tuple[str, Path | str]] = [ + (entrypoint, config_dir / f"{entrypoint}.json"), + ("Trainer", config_dir / TRAINER_CONFIG), + ] if config.eval is not None: if config.inference is not None: - components.append(("Inference", config_dir / INFERENCE_CONFIG)) + components.append(("Engine", config_dir / ENGINE_CONFIG)) + if config.router_config() is not None: + components.append(("Router", config_dir / ROUTER_CONFIG)) components.append(("Eval", config_dir / ONLINE_EVAL_CONFIG)) if eval_env_worker_pools(config): components.append(("Envs", f"{config_dir}/{ENVS_DIR}/eval/*.json")) return components -def write_config(config: SupervisedTrainerConfig, config_path: Path, exclude: set[str] | None = None) -> None: - """Write resolved config to disk, excluding launcher-only fields.""" - config_path.parent.mkdir(parents=True, exist_ok=True) - with open(config_path, "w") as f: - json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2) - - -def write_eval_subconfigs(config: SupervisedTrainerConfig, config_dir: Path, strip_router: bool = False) -> None: - """Write the inference, online-eval, and env-worker-pool configs for online evals.""" - config_dir.mkdir(parents=True, exist_ok=True) - - if config.inference is not None: - # Exclude launcher-only fields that are not needed by the vLLM server - exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"} - inference_dict = dump_resolved_config(config.inference, exclude=exclude_inference) - if strip_router: - # Per-rank processes run bare engines; the sbatch starts the single global router. - inference_dict["router"] = None - with open(config_dir / INFERENCE_CONFIG, "w") as f: - json.dump(inference_dict, f, indent=2) - - with open(config_dir / ONLINE_EVAL_CONFIG, "w") as f: - json.dump(dump_resolved_config(build_online_eval_config(config)), f, indent=2) - - # One EnvWorkerPoolConfig per launcher-managed eval source: `env-worker-pool @ ` binds an - # OS-assigned port and publishes it to the source's address file, where the - # online-eval process picks it up. - for source in eval_env_worker_pools(config): - write_env_worker_pool_config(config_dir, "eval", source, config.log, config.run_dir) +def write_configs(config: SupervisedConfig, config_dir: Path, entrypoint: str) -> None: + """Write the resolved entrypoint config and the config of every component it launches.""" + write_config(config_dir / f"{entrypoint}.json", config) + write_component_configs(config_dir, config.components()) def write_slurm_script( - config: SupervisedTrainerConfig, + config: SupervisedConfig, config_path: Path, run_config_path: Path, log_dir: Path, @@ -243,7 +192,7 @@ def write_slurm_script( script_path.write_text(script) -def launch_slurm(config: SupervisedTrainerConfig, entrypoint: str): +def launch_slurm(config: SupervisedConfig, entrypoint: str): """Run SFT training and its online-eval deployment in one SLURM allocation.""" assert config.slurm is not None @@ -256,25 +205,19 @@ def launch_slurm(config: SupervisedTrainerConfig, entrypoint: str): write_launch_artifacts(config_dir, entrypoint) config_path = config_dir / f"{entrypoint}.json" if config.deployment.type == "multi_node": - # The job's run owner registers the Prime run with the whole config; nothing runs it. - write_config(config, config_path, exclude={"dry_run", "clean"}) + # The job's run owner registers the Prime run with the entrypoint config; the processes run the + # component configs. + write_configs(config, config_dir, entrypoint) trainer_config_path = config_dir / TRAINER_CONFIG - exclude = {"deployment", "slurm", "dry_run", "clean"} - if online_eval: - # The trainer job only needs [eval] for the weight-broadcast cadence; the - # inference pool runs on its dedicated nodes in the same allocation. - exclude = exclude | {"inference"} - write_config(config, trainer_config_path, exclude=exclude) else: - write_config(config, config_path, exclude={"slurm", "dry_run", "clean"}) + # The job runs this config locally: ` @ .json --slurm None`. + write_config(config_path, config) trainer_config_path = config_path # Trainer and online-eval processes log to a single shared W&B run. wandb_shared = online_eval and config.monitors.wandb is not None launcher_dir = get_launcher_dir(config.run_dir) - if online_eval: - write_eval_subconfigs(config, config_dir, strip_router=True) logger.info( f"Configs:\n{format_config_message(config_dir, entrypoint, config_components(config, config_dir, entrypoint))}" ) @@ -312,7 +255,7 @@ def launch_slurm(config: SupervisedTrainerConfig, entrypoint: str): log_run_links(dashboard_url) -def launch_local(config: SupervisedTrainerConfig, entrypoint: str): +def launch_local(config: SupervisedConfig, entrypoint: str): """Run SFT training locally with process monitoring and cleanup.""" assert config.deployment.type == "single_node" @@ -321,10 +264,7 @@ def launch_local(config: SupervisedTrainerConfig, entrypoint: str): logger.info(f"Starting {entrypoint} run") config_dir, log_dir = prepare_attempt_dirs(config.run_dir) write_launch_artifacts(config_dir, entrypoint) - config_path = config_dir / f"{entrypoint}.json" - write_config(config, config_path) - if config.eval is not None: - write_eval_subconfigs(config, config_dir) + write_configs(config, config_dir, entrypoint) logger.info( f"Configs:\n{format_config_message(config_dir, entrypoint, config_components(config, config_dir, entrypoint))}" ) @@ -371,16 +311,24 @@ def launch_local(config: SupervisedTrainerConfig, entrypoint: str): base_env, admin_envs = admin_token_uses(config).split(os.environ) with ProcessGroup() as processes: - if config.eval is not None and config.weight_broadcast.type == "modelexpress": - logger.info(f"Starting ModelExpress server on port {config.weight_broadcast.port}") - start_modelexpress(processes, config.weight_broadcast.port, log_dir, base_env) + modelexpress = config.modelexpress_server_config() + if modelexpress is not None: + logger.info(f"Starting ModelExpress server on port {modelexpress.port}") + start_modelexpress(processes, modelexpress.port, log_dir, base_env) # Optionally, start the inference server for online evals if config.inference is not None: logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}") + if config.router_config() is not None: + processes.start( + "router", + ["router", "@", (config_dir / ROUTER_CONFIG).as_posix()], + env={**base_env, **DEFAULT_COMMON_ENV_VARS, **config.env_vars}, + log_path=log_dir / "router.log", + ) processes.start( "inference", - ["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix(), "--server.require-admin-token"], + ["engine", "@", (config_dir / ENGINE_CONFIG).as_posix()], env={ **base_env, **DEFAULT_COMMON_ENV_VARS, @@ -400,7 +348,7 @@ def launch_local(config: SupervisedTrainerConfig, entrypoint: str): logger.info(f"Starting {name} env worker pool") processes.start( f"env/eval/{name}", - ["env-worker-pool", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()], + env_worker_pool_command(config_dir, "eval", name), env={**base_env, **DEFAULT_COMMON_ENV_VARS, **config.env_vars}, log_path=log_dir / ENVS_DIR / "eval" / f"{name}.log", ) @@ -445,7 +393,7 @@ def launch_local(config: SupervisedTrainerConfig, entrypoint: str): "trainer", torchrun_cmd( f"prime_rl.trainer.{entrypoint}.train", - config_path, + config_dir / TRAINER_CONFIG, config.deployment.num_train_gpus, log_dir, config.log.ranks_filter, @@ -464,7 +412,7 @@ def launch_local(config: SupervisedTrainerConfig, entrypoint: str): logger.success("Training finished!") -def clean_stale_eval_artifacts(config: SupervisedTrainerConfig) -> None: +def clean_stale_eval_artifacts(config: SupervisedConfig) -> None: """Remove eval artifacts a previous run left behind: weight broadcasts and rollout trace dirs — everything on a fresh start, steps past the resume step on resume. Without this the online-eval process would replay stale broadcasts (and then skip the @@ -478,19 +426,7 @@ def clean_stale_eval_artifacts(config: SupervisedTrainerConfig) -> None: clean_resume_state(config.run_dir, step) -def launch(config: SupervisedTrainerConfig, entrypoint: str): - # Launcher-only check: the trainer re-parses a sub-config with [inference] and - # [deployment] stripped, so the model validator cannot enforce this. - if ( - config.weight_broadcast is not None - and config.weight_broadcast.type != "filesystem" - and config.inference is None - ): - raise ValueError( - f"{config.weight_broadcast.type} weight broadcast requires launcher-managed inference. " - "Add an [inference] block or set weight_broadcast.type = 'filesystem'." - ) - +def launch(config: SupervisedConfig, entrypoint: str): prepare_run(config, config.ckpt.output_dir if config.ckpt else None) if config.eval is not None and not config.dry_run: diff --git a/src/prime_rl/entrypoints/modelexpress_server.py b/src/prime_rl/entrypoints/modelexpress_server.py index 507e255dbb8..ce7a6db5888 100644 --- a/src/prime_rl/entrypoints/modelexpress_server.py +++ b/src/prime_rl/entrypoints/modelexpress_server.py @@ -8,8 +8,8 @@ from threading import Event from typing import Any -from prime_rl.configs.modelexpress_server import ModelExpressServerConfig -from prime_rl.configs.shared import WeightBroadcastConfig +from prime_rl.configs.blocks.weight_broadcast import WeightBroadcastConfig +from prime_rl.configs.components.modelexpress_server import ModelExpressServerConfig from prime_rl.utils.config import cli from prime_rl.utils.process import ProcessGroup, wait_for_port from prime_rl.utils.utils import get_free_port @@ -82,7 +82,7 @@ def _handle_stop(signum: int, frame: object) -> None: prev_term = signal.signal(signal.SIGTERM, _handle_stop) prev_int = signal.signal(signal.SIGINT, _handle_stop) try: - start_modelexpress(processes, config.resolved_port, config.log_dir, os.environ.copy()) + start_modelexpress(processes, config.port, config.log_dir, os.environ.copy()) while not shutdown.is_set(): if processes.stop_events["valkey"].is_set() or processes.stop_events["modelexpress"].is_set(): return 1 diff --git a/src/prime_rl/entrypoints/pretrain.py b/src/prime_rl/entrypoints/pretrain.py index 9ce88b231c1..19310897ae0 100644 --- a/src/prime_rl/entrypoints/pretrain.py +++ b/src/prime_rl/entrypoints/pretrain.py @@ -1,4 +1,4 @@ -from prime_rl.configs.pretrain import PretrainConfig +from prime_rl.configs.entrypoints.pretrain import PretrainConfig from prime_rl.entrypoints.launcher import launch from prime_rl.utils.config import check_mode, cli from prime_rl.utils.process import set_proc_title diff --git a/src/prime_rl/entrypoints/rl.py b/src/prime_rl/entrypoints/rl.py index 4e372a21eec..9614e81a3e9 100644 --- a/src/prime_rl/entrypoints/rl.py +++ b/src/prime_rl/entrypoints/rl.py @@ -2,30 +2,27 @@ import os import sys from pathlib import Path -from typing import Any from urllib.parse import urlparse -from prime_rl.configs.algorithm import FrozenModelConfig -from prime_rl.configs.env_worker_pool import ROLLOUT_STORE_DIR -from prime_rl.configs.inference import VllmRouterConfig -from prime_rl.configs.orchestrator import EnvConfig -from prime_rl.configs.rl import RLConfig -from prime_rl.configs.shared import ckpt_output_dir -from prime_rl.configs.trainer import CheckpointConfig +from prime_rl.configs.blocks.algorithm import FrozenModelConfig +from prime_rl.configs.components.orchestrator.sources import EnvConfig +from prime_rl.configs.components.router import VllmRouterConfig +from prime_rl.configs.components.trainer.ckpt import TrainerCheckpointConfig +from prime_rl.configs.entrypoints.rl import RLConfig from prime_rl.entrypoints.dashboard import ensure_dashboard, log_run_links, run_links from prime_rl.entrypoints.inference import ( mooncake_offloads, prefill_uses_deepep_high_throughput, vllm_overrides_fragment, - write_pd_configs, ) from prime_rl.entrypoints.modelexpress_server import modelexpress_template_vars, start_modelexpress from prime_rl.entrypoints.slurm import load_slurm_template, submit_sbatch from prime_rl.scripts.resume_cleanup import clean_resume_state, resolve_resume_step from prime_rl.utils.admin_token import AdminTokenUses, TokenUse -from prime_rl.utils.config import check_mode, cli, dump_resolved_config, dump_rl_components +from prime_rl.utils.config import check_mode, cli from prime_rl.utils.logger import get_logger, setup_logger from prime_rl.utils.pathing import ( + env_worker_pool_command, format_config_message, format_log_message, get_ckpt_dir, @@ -34,7 +31,8 @@ launcher_attempt_env, prepare_attempt_dirs, prepare_run, - write_env_worker_pool_config, + write_component_configs, + write_config, write_launch_artifacts, ) from prime_rl.utils.process import ( @@ -52,7 +50,8 @@ TRAINER_CONFIG = "trainer.json" ORCHESTRATOR_CONFIG = "orchestrator.json" -INFERENCE_CONFIG = "inference.json" +ENGINE_CONFIG = "engine.json" +ROUTER_CONFIG = "router.json" ENVS_DIR = "envs" @@ -71,21 +70,16 @@ def env_worker_pool_names(config: RLConfig, split: str) -> list[str]: return [source.resolved_name for source_split, source in env_worker_pools(config) if source_split == split] -def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | dict[str, Any] | None = None) -> None: - """Write resolved config to disk, excluding launcher-only fields.""" - output_dir.mkdir(parents=True, exist_ok=True) - with open(output_dir / RL_CONFIG, "w") as f: - json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2) - - def rl_config_components(config: RLConfig, config_dir: Path) -> list[tuple[str, Path | str]]: - """The resolved per-component configs ``write_subconfigs`` leaves in ``config_dir``.""" + """The resolved per-component configs ``write_configs`` leaves in ``config_dir``.""" components: list[tuple[str, Path | str]] = [ ("Orchestrator", config_dir / ORCHESTRATOR_CONFIG), ("Trainer", config_dir / TRAINER_CONFIG), ] if config.inference is not None: - components.append(("Inference", config_dir / INFERENCE_CONFIG)) + components.append(("Engine", f"{config_dir}/engine*.json")) + if config.router_config() is not None: + components.append(("Router", config_dir / ROUTER_CONFIG)) if env_worker_pools(config): components.append(("Envs", f"{config_dir}/{ENVS_DIR}/*/*.json")) return components @@ -106,29 +100,10 @@ def admin_token_uses(config: RLConfig) -> AdminTokenUses: ) -def write_subconfigs(config: RLConfig, output_dir: Path) -> None: - """Write resolved subconfigs to disk as JSON files.""" - output_dir.mkdir(parents=True, exist_ok=True) - filenames = {"trainer": TRAINER_CONFIG, "orchestrator": ORCHESTRATOR_CONFIG, "inference": INFERENCE_CONFIG} - for name, component in dump_rl_components(config).items(): - if name == "inference" and config.deployment.type == "multi_node": - # SLURM runs per-rank bare engines from inference.json and launches the router itself. - component = {k: v for k, v in component.items() if k != "deployment"} - component["router"] = None - with open(output_dir / filenames[name], "w") as f: - json.dump(component, f, indent=2) - if config.inference is not None: - write_pd_configs(config.inference, output_dir) - - # One EnvWorkerPoolConfig per launcher-managed source: `env-worker-pool @ ` binds an - # OS-assigned port and publishes it to the source's address file, where the - # orchestrator picks it up. - # Train pools of a retaining run keep their arrays on node-local disk, not in memory. - retain = config.rollout_transport is not None and config.rollout_transport.retain - save_dir = ckpt_output_dir(config.orchestrator.output_dir, config.orchestrator.ckpt) - for split, source in env_worker_pools(config): - store_dir = ROLLOUT_STORE_DIR if retain and split == "train" else None - write_env_worker_pool_config(output_dir, split, source, config.orchestrator.log, save_dir, store_dir) +def write_configs(config: RLConfig, config_dir: Path) -> None: + """Write the resolved RL config and the config of every component it launches.""" + write_config(config_dir / RL_CONFIG, config) + write_component_configs(config_dir, config.components()) def rl_local(config: RLConfig): @@ -141,8 +116,9 @@ def rl_local(config: RLConfig): config_dir, log_dir = prepare_attempt_dirs(config.run_dir) write_launch_artifacts(config_dir, "rl") - write_subconfigs(config, config_dir) - logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', rl_config_components(config, config_dir))}") + write_configs(config, config_dir) + components = [("RL", config_dir / RL_CONFIG), *rl_config_components(config, config_dir)] + logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', components)}") if config.dry_run: logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.") @@ -190,15 +166,16 @@ def rl_local(config: RLConfig): ) with ProcessGroup() as processes: - if config.weight_broadcast is not None and config.weight_broadcast.type == "modelexpress": - logger.info(f"Starting ModelExpress server on port {config.weight_broadcast.port}") - start_modelexpress(processes, config.weight_broadcast.port, log_dir, base_env) + modelexpress = config.modelexpress_server_config() + if modelexpress is not None: + logger.info(f"Starting ModelExpress server on port {modelexpress.port}") + start_modelexpress(processes, modelexpress.port, log_dir, base_env) if config.inference: logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}") processes.start( "inference", - ["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix(), "--server.require-admin-token"], + ["engine", "@", (config_dir / ENGINE_CONFIG).as_posix()], env={ **base_env, **DEFAULT_COMMON_ENV_VARS, @@ -210,6 +187,13 @@ def rl_local(config: RLConfig): }, log_path=log_dir / "inference.log", ) + if config.router_config() is not None: + processes.start( + "router", + ["router", "@", (config_dir / ROUTER_CONFIG).as_posix()], + env={**base_env, **DEFAULT_COMMON_ENV_VARS, **config.env_vars}, + log_path=log_dir / "router.log", + ) else: logger.warning( "No [inference] block configured - the policy inference server will not be started here. " @@ -240,7 +224,7 @@ def rl_local(config: RLConfig): logger.info(f"Starting {name} env worker pool") processes.start( f"{split} env worker pool {name}", - ["env-worker-pool", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()], + env_worker_pool_command(config_dir, split, name), env={ **base_env, **DEFAULT_COMMON_ENV_VARS, @@ -300,7 +284,7 @@ def rl_local(config: RLConfig): ) logger.success("Launcher complete") - links = run_links(config.run_dir, log_dir, config.orchestrator.monitors, lambda: bool(processes.error_queue)) + links = run_links(config.run_dir, log_dir, config.monitors, lambda: bool(processes.error_queue)) log_run_links(dashboard_url, links) # Trainer and orchestrator completion is the successful stop condition. @@ -336,7 +320,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script modelexpress_vars = modelexpress_template_vars(config.weight_broadcast, config.slurm.launch_modelexpress) - ckpt_dir = get_ckpt_dir(config.trainer.ckpt.output_dir or config.run_dir) if config.trainer.ckpt else None + ckpt_dir = get_ckpt_dir(config.ckpt.output_dir or config.run_dir) if config.ckpt else None if config.deployment.type == "single_node": script = template.render( @@ -389,7 +373,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script prefill_vllm_extra_json=vllm_overrides_fragment(infer_deploy.prefill_vllm_overrides), prefill_deepep_high_throughput=prefill_uses_deepep_high_throughput(infer_deploy.prefill_vllm_overrides), decode_vllm_extra_json=vllm_overrides_fragment(infer_deploy.decode_vllm_overrides), - pd_bidirectional=infer_deploy.bidirectional_kv_transfer, nixl_nic_affinity=infer_deploy.nixl_nic_affinity, dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size, **mooncake_vars, @@ -460,7 +443,8 @@ def rl_slurm(config: RLConfig): write_launch_artifacts(config_dir, "rl") if config.deployment.type == "single_node": - write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"}) + # The job runs this config locally: `rl @ rl.json --slurm None`. + write_config(config_dir / RL_CONFIG, config) logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', [('RL', config_dir / RL_CONFIG)])}") train_env_names = env_worker_pool_names(config, "train") @@ -474,10 +458,8 @@ def rl_slurm(config: RLConfig): env_names={"train": train_env_names, "eval": eval_env_names}, ) else: - # The job's run owner registers the Prime run with the whole config; nothing runs it. - # It keeps [slurm], which multi-node needs, so it drops the copy in [inference]. - write_config(config, config_dir, exclude={"dry_run": True, "clean": True, "inference": {"slurm"}}) - write_subconfigs(config, config_dir) + # The job's run owner registers the Prime run with rl.json; the processes run the component configs. + write_configs(config, config_dir) components = [("RL", config_dir / RL_CONFIG), *rl_config_components(config, config_dir)] logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', components)}") @@ -523,7 +505,7 @@ def rl(config: RLConfig): ckpt_dir = get_ckpt_dir(ckpt_base) step = resolve_resume_step(config.resume, ckpt_dir, orchestrator_ckpt_dir=ckpt_dir) if config.resume is not None and config.resume.dir is None and config.resume.step is None: - validate_remote_resume(config.trainer.ckpt, step) + validate_remote_resume(config.ckpt, step) if step is not None: get_logger().info(f"Resuming from step {step}, cleaning future rollouts and broadcasts") else: @@ -542,11 +524,11 @@ def rl(config: RLConfig): if config.slurm is not None: rl_slurm(config) return - with launch_run(config, None if config.dry_run else config.orchestrator.monitors.prime): + with launch_run(config, None if config.dry_run else config.monitors.prime): rl_local(config) -def validate_remote_resume(ckpt: CheckpointConfig | None, resume_step: int | None) -> None: +def validate_remote_resume(ckpt: TrainerCheckpointConfig | None, resume_step: int | None) -> None: """The orchestrator checkpoint is only on disk, so a trainer resuming from a later step in its remote would wait for an orchestrator that started from the disk's step.""" if ckpt is None or ckpt.remote is None: diff --git a/src/prime_rl/entrypoints/router.py b/src/prime_rl/entrypoints/router.py deleted file mode 100644 index 42e8a6a2e9d..00000000000 --- a/src/prime_rl/entrypoints/router.py +++ /dev/null @@ -1,110 +0,0 @@ -import os - -from prime_rl.configs.inference import ( - DisaggregatedInferenceDeploymentConfig, - InferenceDeploymentConfig, - RouterConfig, - VllmRouterConfig, -) -from prime_rl.configs.router import RouterEntrypointConfig -from prime_rl.utils.config import cli - - -def build_vllm_router_cmd( - *, - router: RouterConfig | None, - host: str, - port: int, - intra_node_dp: int, - worker_urls: list[str] | None = None, - prefill_urls: list[str] | None = None, - decode_urls: list[str] | None = None, - deployment: InferenceDeploymentConfig | None = None, - prometheus_port: int | None = None, -) -> list[str]: - resolved_router = router if router is not None else VllmRouterConfig() - if not isinstance(resolved_router, VllmRouterConfig): - raise ValueError( - f"Unsupported router type {resolved_router.type!r}; the router entrypoint supports 'vllm-router' only." - ) - - workers = list(worker_urls or []) - prefills = list(prefill_urls or []) - decodes = list(decode_urls or []) - is_pd = bool(prefills or decodes) - if is_pd: - if workers: - raise ValueError("Specify either worker_urls or prefill_urls/decode_urls, not both.") - if not prefills or not decodes: - raise ValueError("Disaggregated routing requires both prefill_urls and decode_urls.") - elif not workers: - raise ValueError("Colocated routing requires at least one entry in worker_urls.") - - cmd = [ - "vllm-router", - "--policy", - resolved_router.policy, - "--host", - host, - "--port", - str(port), - "--request-id-headers", - "x-session-id", - "--request-timeout-secs", - str(resolved_router.request_timeout_secs), - "--worker-startup-timeout-secs", - "4200", - # Default 30s check interval delays initial engine admission. - "--worker-startup-check-interval", - "1", - ] - if prometheus_port is not None: - cmd.extend(["--prometheus-port", str(prometheus_port)]) - - if is_pd: - cmd.append("--vllm-pd-disaggregation") - for url in prefills: - cmd.extend(["--prefill", url]) - for url in decodes: - cmd.extend(["--decode", url]) - if intra_node_dp > 1: - cmd.extend(["--intra-node-data-parallel-size", str(intra_node_dp)]) - cmd.extend(["--pd-turn-retries", str(resolved_router.pd_turn_retries)]) - if isinstance(deployment, DisaggregatedInferenceDeploymentConfig) and deployment.bidirectional_kv_transfer: - cmd.extend( - [ - "--pd-bidirectional-kv", - "--pd-bidirectional-ttl-secs", - str(deployment.bidirectional_kv_transfer.effective_router_ttl_s), - ] - ) - else: - cmd.extend(["--intra-node-data-parallel-size", str(intra_node_dp), "--worker-urls", *workers]) - - return cmd - - -def router_command(config: RouterEntrypointConfig) -> list[str]: - intra_node_dp = ( - config.intra_node_data_parallel_size or config.vllm.data_parallel_size_local or config.vllm.data_parallel_size - ) - return build_vllm_router_cmd( - router=config.router, - host=config.server.host or "0.0.0.0", - port=config.server.port, - intra_node_dp=intra_node_dp, - worker_urls=config.worker_urls, - prefill_urls=config.prefill_urls, - decode_urls=config.decode_urls, - deployment=config.deployment, - prometheus_port=config.prometheus_port, - ) - - -def main() -> None: - cmd = router_command(cli(RouterEntrypointConfig)) - os.execvp(cmd[0], cmd) - - -if __name__ == "__main__": - main() diff --git a/src/prime_rl/entrypoints/run_owner.py b/src/prime_rl/entrypoints/run_owner.py index 2caf68ee5ed..6e244675073 100644 --- a/src/prime_rl/entrypoints/run_owner.py +++ b/src/prime_rl/entrypoints/run_owner.py @@ -4,9 +4,9 @@ from pathlib import Path from typing import Any -from prime_rl.configs.pretrain import PretrainConfig -from prime_rl.configs.rl import RLConfig -from prime_rl.configs.sft import SFTConfig +from prime_rl.configs.entrypoints.pretrain import PretrainConfig +from prime_rl.configs.entrypoints.rl import RLConfig +from prime_rl.configs.entrypoints.sft import SFTConfig from prime_rl.monitors.prime import launch_run @@ -18,7 +18,7 @@ def main() -> None: kind, path, *command = sys.argv[1:] config_cls = {"rl": RLConfig, "sft": SFTConfig, "pretrain": PretrainConfig}[kind] config = config_cls.model_validate_json(Path(path).read_text()) - prime = config.orchestrator.monitors.prime if isinstance(config, RLConfig) else config.monitors.prime + prime = config.monitors.prime step: subprocess.Popen | None = None def forward(signum: int, frame: Any) -> None: diff --git a/src/prime_rl/entrypoints/sft.py b/src/prime_rl/entrypoints/sft.py index 9672db446d3..c1fc5636fcd 100644 --- a/src/prime_rl/entrypoints/sft.py +++ b/src/prime_rl/entrypoints/sft.py @@ -1,4 +1,4 @@ -from prime_rl.configs.sft import SFTConfig +from prime_rl.configs.entrypoints.sft import SFTConfig from prime_rl.entrypoints.launcher import launch from prime_rl.utils.config import check_mode, cli from prime_rl.utils.process import set_proc_title diff --git a/src/prime_rl/entrypoints/slurm.py b/src/prime_rl/entrypoints/slurm.py index 13475dd08e7..8e5e0ba7263 100644 --- a/src/prime_rl/entrypoints/slurm.py +++ b/src/prime_rl/entrypoints/slurm.py @@ -3,7 +3,7 @@ from pathlib import Path from typing import TYPE_CHECKING -from prime_rl.configs.shared import SlurmConfig +from prime_rl.configs.blocks.slurm import SlurmConfig from prime_rl.utils.config import find_package_resource from prime_rl.utils.logger import get_logger diff --git a/src/prime_rl/env/pool.py b/src/prime_rl/env/pool.py index 14769c81b97..baf40de0351 100644 --- a/src/prime_rl/env/pool.py +++ b/src/prime_rl/env/pool.py @@ -34,7 +34,7 @@ import zmq.asyncio from verifiers.v1.utils.loaders import resolve_env_config -from prime_rl.configs.env_worker_pool import ElasticPoolConfig, PoolConfig, StaticPoolConfig +from prime_rl.configs.components.env_worker_pool import ElasticPoolConfig, PoolConfig, StaticPoolConfig from prime_rl.env.types import CancelResponse, HealthResponse from prime_rl.env.worker import LATE_CANCEL_SECONDS, EnvWorker from prime_rl.utils.logger import get_logger diff --git a/src/prime_rl/env/sample_server.py b/src/prime_rl/env/sample_server.py index 00a0e0e73b1..e6a090b93fd 100644 --- a/src/prime_rl/env/sample_server.py +++ b/src/prime_rl/env/sample_server.py @@ -27,7 +27,7 @@ import zmq import zmq.asyncio -from prime_rl.configs.env_worker_pool import ScoringConfig +from prime_rl.configs.components.env_worker_pool import ScoringConfig from prime_rl.env.encoding import pack, unpack from prime_rl.env.types import BaseResponse, SampleToScore, ScoreRequest from prime_rl.transports.batch.types import SampleBody @@ -64,7 +64,7 @@ def __init__(self, store: PayloadServer, address: str, scoring: ScoringConfig) - def algorithm(self, request: ScoreRequest) -> Algorithm: from pydantic import TypeAdapter - from prime_rl.configs.algorithm import AlgoConfig + from prime_rl.configs.blocks.algorithm import AlgoConfig from prime_rl.orchestrator.algo import build_algorithm key = json.dumps([request.train.algo, request.client.model_dump(mode="json"), request.model], sort_keys=True) diff --git a/src/prime_rl/env/worker.py b/src/prime_rl/env/worker.py index f297e4a6c24..ddd85553f4f 100644 --- a/src/prime_rl/env/worker.py +++ b/src/prime_rl/env/worker.py @@ -50,7 +50,7 @@ from prime_rl.utils.pathing import confined, is_file_name if TYPE_CHECKING: - from prime_rl.configs.algorithm import ActionLossType + from prime_rl.configs.blocks.algorithm import ActionLossType from prime_rl.orchestrator.algo import Algorithm @@ -284,7 +284,7 @@ def _algorithm(self, req: RunRequest) -> Algorithm: """The train source's algorithm, built once per config.""" from pydantic import TypeAdapter - from prime_rl.configs.algorithm import AlgoConfig + from prime_rl.configs.blocks.algorithm import AlgoConfig from prime_rl.orchestrator.algo import build_algorithm key = json.dumps(req.train.algo, sort_keys=True) diff --git a/src/prime_rl/eval/eval.py b/src/prime_rl/eval/eval.py index 5c44d5ad7d5..41ff19e1154 100644 --- a/src/prime_rl/eval/eval.py +++ b/src/prime_rl/eval/eval.py @@ -11,7 +11,7 @@ import verifiers.v1 as vf from prime_rl import monitors -from prime_rl.configs.eval import EvalConfig +from prime_rl.configs.entrypoints.eval import EvalConfig from prime_rl.eval import resume from prime_rl.eval.runner import EvalRunner from prime_rl.utils.config import dump_resolved_config diff --git a/src/prime_rl/eval/online.py b/src/prime_rl/eval/online.py index 030f7ac65db..4b0734003a3 100644 --- a/src/prime_rl/eval/online.py +++ b/src/prime_rl/eval/online.py @@ -1,6 +1,6 @@ """Online evals: evaluate the trainer's weight broadcasts as they appear. -Spawned by the ``sft`` launcher (``python -m prime_rl.eval.online @ eval.json``) +Spawned by the ``sft`` launcher (``python -m prime_rl.eval.online @ online-eval.json``) next to the trainer. The process watches a broadcasts directory for offered weight broadcasts through a ``WeightReceiver`` (announced by their ``.sender_ready`` marker), moves the inference server onto each of them, and runs the due eval sources against the updated weights, @@ -17,9 +17,10 @@ import os from prime_rl import monitors -from prime_rl.configs.eval import SFTOnlineEvalConfig -from prime_rl.configs.shared import FileSystemWeightBroadcastConfig +from prime_rl.configs.blocks.weight_broadcast import FileSystemWeightBroadcastConfig +from prime_rl.configs.components.online_eval import SFTOnlineEvalConfig from prime_rl.eval.runner import POLL_INTERVAL_S, EvalRunner +from prime_rl.scripts.resume_cleanup import resolve_online_eval_resume_step from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver from prime_rl.utils.config import cli, dump_resolved_config from prime_rl.utils.logger import get_logger, setup_logger @@ -212,10 +213,11 @@ async def run_online_eval(config: SFTOnlineEvalConfig) -> None: def main(): set_proc_title("OnlineEvals") config = cli(SFTOnlineEvalConfig) + config.resume_step = resolve_online_eval_resume_step(config) config_dir, log_dir = prepare_attempt_dirs(config.output_dir) os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir) os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir) - (config_dir / "eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2)) + (config_dir / "online-eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2)) setup_logger(config.log.level, json_logging=config.log.json_logging) asyncio.run(run_online_eval(config)) diff --git a/src/prime_rl/eval/resume.py b/src/prime_rl/eval/resume.py index aed1501e3be..ea64b603e03 100644 --- a/src/prime_rl/eval/resume.py +++ b/src/prime_rl/eval/resume.py @@ -19,7 +19,7 @@ import orjson import verifiers.v1 as vf -from prime_rl.configs.eval import EvalConfig +from prime_rl.configs.entrypoints.eval import EvalConfig from prime_rl.monitors.file.traces import get_trace_stream from prime_rl.monitors.file.traces.chunks import chunk_numbers, open_chunk from prime_rl.utils.logger import get_logger diff --git a/src/prime_rl/eval/runner.py b/src/prime_rl/eval/runner.py index 343f65eac69..4d88e24aec5 100644 --- a/src/prime_rl/eval/runner.py +++ b/src/prime_rl/eval/runner.py @@ -23,7 +23,8 @@ import verifiers.v1 as vf from prime_rl import monitors -from prime_rl.configs.eval import EvalConfig, SFTOnlineEvalConfig +from prime_rl.configs.components.online_eval import SFTOnlineEvalConfig +from prime_rl.configs.entrypoints.eval import EvalConfig from prime_rl.control.server import serve from prime_rl.env.heads import EpisodeHead, episode_head, recorded_head from prime_rl.eval.control import create_app diff --git a/src/prime_rl/inference/dynamo.py b/src/prime_rl/inference/dynamo.py index 6bfed63b715..d4005f58623 100644 --- a/src/prime_rl/inference/dynamo.py +++ b/src/prime_rl/inference/dynamo.py @@ -12,7 +12,7 @@ import httpx from pydantic import BaseModel, Field -from prime_rl.configs.shared import ClientConfig, PolicyClientConfig +from prime_rl.configs.blocks.client import ClientConfig, PolicyClientConfig from prime_rl.orchestrator.clients import ( ADMIN_TIMEOUT_S, ENGINE_ADMIN_LIMITS, diff --git a/src/prime_rl/inference/server.py b/src/prime_rl/inference/server.py index 586b9ec492d..b1b6b09dd63 100644 --- a/src/prime_rl/inference/server.py +++ b/src/prime_rl/inference/server.py @@ -1,11 +1,11 @@ import logging.config import os -from prime_rl.configs.inference import InferenceConfig, setup_dummy_load +from prime_rl.configs.components.engine import EngineConfig, setup_dummy_load from prime_rl.utils.pathing import is_checkpoint_step_dir -def setup_model_source(config: InferenceConfig) -> None: +def setup_model_source(config: EngineConfig) -> None: """A checkpoint step directory as ``model.name`` holds no HF weights: vLLM builds the model from its config.json and starts with placeholder weights, which the trainer's startup broadcast replaces.""" if not is_checkpoint_step_dir(config.vllm.model): @@ -19,7 +19,7 @@ def setup_model_source(config: InferenceConfig) -> None: setup_dummy_load(config, dummy=True) -def setup_vllm_env(config: InferenceConfig): +def setup_vllm_env(config: EngineConfig): """Set vLLM environment variables based on config. Must be called before importing vLLM.""" # spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes) diff --git a/src/prime_rl/inference/vllm/server.py b/src/prime_rl/inference/vllm/server.py index 44d8eb34f31..b659b6258dc 100644 --- a/src/prime_rl/inference/vllm/server.py +++ b/src/prime_rl/inference/vllm/server.py @@ -17,8 +17,8 @@ from vllm.logger import init_logger from vllm.utils.argparse_utils import FlexibleArgumentParser -from prime_rl.configs.inference import InferenceConfig -from prime_rl.configs.shared import ADMIN_TOKEN_HEADER +from prime_rl.configs.blocks.client import ADMIN_TOKEN_HEADER +from prime_rl.configs.components.engine import EngineConfig from prime_rl.inference.server import setup_model_source from prime_rl.utils.admin_token import admin_token_matches, digest_var, expected_admin_digest from prime_rl.utils.specdec import check_draft_swap, local_draft_dir @@ -123,7 +123,7 @@ async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: R prime-rl reloads a fixed-name adapter with fresh weights every step (the path changes per policy version; the name is constant — the model name every client sends. vLLM rejects an adapter named like a served base model, so with LoRA on - the base model is served as ``-base``; see ``InferenceConfig.to_namespace``.) + the base model is served as ``-base``; see ``EngineConfig.to_namespace``.) vLLM's native loader rejects a same-name reload unless ``load_inplace=True``, so we force it here — that makes the worker re-read the new weights during ``add_lora``, reusing the existing ``lora_int_id``. vLLM resets the stored @@ -264,7 +264,7 @@ def custom_run_api_server_worker_proc(listen_address, sock, args, client_config= # Adapted from vllm/entrypoints/cli/serve.py # Only difference we do some config translation (i.e. pass populated namespace # to `parse_args`) and additional arg validation -def server(config: InferenceConfig): +def server(config: EngineConfig): from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server from vllm.entrypoints.launchers.api_server.entry import run_server diff --git a/src/prime_rl/monitors/__init__.py b/src/prime_rl/monitors/__init__.py index 9baa26ee07c..d2db6fbffee 100644 --- a/src/prime_rl/monitors/__init__.py +++ b/src/prime_rl/monitors/__init__.py @@ -13,16 +13,12 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Literal -from prime_rl.configs.monitors import ( - FileMonitorConfig, - PrimeMonitorConfig, - WandbMonitorConfig, -) +from prime_rl.configs.base import BaseConfig +from prime_rl.configs.blocks.monitors import FileMonitorConfig, PrimeMonitorConfig, WandbMonitorConfig from prime_rl.monitors.base import Kind, Monitor from prime_rl.monitors.file import FileMonitor from prime_rl.monitors.prime import EVAL_ID_VAR, PrimeMonitor from prime_rl.monitors.wandb import WandbMonitor -from prime_rl.utils.config import BaseConfig from prime_rl.utils.logger import format_time, get_logger if TYPE_CHECKING: diff --git a/src/prime_rl/monitors/base.py b/src/prime_rl/monitors/base.py index e9729ec0a9d..1f25d44ca56 100644 --- a/src/prime_rl/monitors/base.py +++ b/src/prime_rl/monitors/base.py @@ -3,7 +3,7 @@ from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any, Literal -from prime_rl.utils.config import BaseConfig +from prime_rl.configs.base import BaseConfig from prime_rl.utils.logger import get_logger if TYPE_CHECKING: diff --git a/src/prime_rl/monitors/file/monitor.py b/src/prime_rl/monitors/file/monitor.py index accd52d4566..e3118ee5a49 100644 --- a/src/prime_rl/monitors/file/monitor.py +++ b/src/prime_rl/monitors/file/monitor.py @@ -13,7 +13,7 @@ from verifiers.v1.trace import EXCLUDE_FIELDS from verifiers.v1.types import decode_ndarray -from prime_rl.configs.monitors import FileMonitorConfig +from prime_rl.configs.blocks.monitors import FileMonitorConfig from prime_rl.monitors.base import Kind, Monitor from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream from prime_rl.monitors.file.traces.chunks import ChunkedJsonl diff --git a/src/prime_rl/monitors/prime.py b/src/prime_rl/monitors/prime.py index e03a3689211..3380498601e 100644 --- a/src/prime_rl/monitors/prime.py +++ b/src/prime_rl/monitors/prime.py @@ -13,14 +13,15 @@ import prime_runs as pr from prime_runs.config import Config -from prime_rl.configs.eval import EvalConfig, SFTOnlineEvalConfig -from prime_rl.configs.monitors import PrimeMonitorConfig -from prime_rl.configs.orchestrator import OrchestratorConfig -from prime_rl.configs.rl import RLConfig -from prime_rl.configs.supervised import SupervisedTrainerConfig -from prime_rl.configs.trainer import TrainerConfig +from prime_rl.configs.base import BaseConfig +from prime_rl.configs.blocks.monitors import PrimeMonitorConfig +from prime_rl.configs.components.online_eval import SFTOnlineEvalConfig +from prime_rl.configs.components.orchestrator import OrchestratorConfig +from prime_rl.configs.components.trainer import TrainerConfig +from prime_rl.configs.components.trainer.base import SupervisedTrainerSection +from prime_rl.configs.entrypoints.eval import EvalConfig +from prime_rl.configs.entrypoints.rl import RLConfig from prime_rl.monitors.base import Kind, Monitor -from prime_rl.utils.config import BaseConfig from prime_rl.utils.links import publish_link, register_links from prime_rl.utils.pathing import get_platform_run_path from prime_rl.utils.record import update_record @@ -51,7 +52,7 @@ def _base_url() -> str | None: def register( - config: RLConfig | OrchestratorConfig | SupervisedTrainerConfig | None, + config: RLConfig | OrchestratorConfig | SupervisedTrainerSection | None, name: str | None, mode: str, id: str | None = None, @@ -65,7 +66,7 @@ def register( # The RFT API requires a base model. init_kwargs = {"name": name, "model": "unknown"} else: - if isinstance(config, SupervisedTrainerConfig): + if isinstance(config, SupervisedTrainerSection): model = config.model.name # SFT and pretraining train on a dataset, not on environments, and have no rollouts. environments = [] @@ -80,13 +81,13 @@ def register( model = orchestrator.model.name environments = [env.env_id for env in orchestrator.train.source] training = pr.TrainingSpec( - max_steps=orchestrator.max_steps or 0, + max_steps=config.max_steps or 0, batch_size=orchestrator.batch_size, rollouts_per_example=max( (source.group_size for source in orchestrator.train.source), default=orchestrator.train.group_size ), seq_len=orchestrator.seq_len, - wandb_project=orchestrator.monitors.wandb.project if orchestrator.monitors.wandb else None, + wandb_project=config.monitors.wandb.project if config.monitors.wandb else None, ) init_kwargs = dict( name=name, @@ -111,7 +112,7 @@ def register( @contextmanager -def launch_run(config: RLConfig | SupervisedTrainerConfig, prime: PrimeMonitorConfig | None) -> Iterator[None]: +def launch_run(config: RLConfig | SupervisedTrainerSection, prime: PrimeMonitorConfig | None) -> Iterator[None]: """Register the launch's Prime run around starting its components, which attach to it: its id becomes ``$PRL_RUN_ID`` and ``$RUN_ID``. A launch that fails marks the run failed, and one that ends cleanly finishes it once every component exited - the diff --git a/src/prime_rl/monitors/wandb/monitor.py b/src/prime_rl/monitors/wandb/monitor.py index 081ed33b6ae..d5fffc064eb 100644 --- a/src/prime_rl/monitors/wandb/monitor.py +++ b/src/prime_rl/monitors/wandb/monitor.py @@ -12,10 +12,10 @@ from wandb.errors import CommError, UsageError from wandb.sdk.mailbox.mailbox_handle import ServerResponseError -from prime_rl.configs.monitors import WandbMonitorConfig +from prime_rl.configs.base import BaseConfig +from prime_rl.configs.blocks.monitors import WandbMonitorConfig from prime_rl.monitors.base import Monitor from prime_rl.monitors.wandb.overview import ensure_overview_view -from prime_rl.utils.config import BaseConfig from prime_rl.utils.links import publish_link, register_links from prime_rl.utils.logger import format_time diff --git a/src/prime_rl/orchestrator/algo/__init__.py b/src/prime_rl/orchestrator/algo/__init__.py index beb65edbe1d..3a05049dfbf 100644 --- a/src/prime_rl/orchestrator/algo/__init__.py +++ b/src/prime_rl/orchestrator/algo/__init__.py @@ -1,6 +1,6 @@ """Orchestrator-side algorithm runtime. -The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm +The config side (``prime_rl.configs.blocks.algorithm``) defines *what* an algorithm is — a bundle of sampling and the per-token training signal. This package turns the signal half into runtime objects (the sampling half is interpreted by :class:`~prime_rl.orchestrator.envs.TrainEnv`): @@ -41,7 +41,7 @@ class owns its scoring hooks from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm if TYPE_CHECKING: - from prime_rl.configs.algorithm import AlgoConfig + from prime_rl.configs.blocks.algorithm import AlgoConfig from prime_rl.orchestrator.clients import InferenceClient # Runtime dispatch is keyed on ``algo.type`` — it names the algorithm, and diff --git a/src/prime_rl/orchestrator/algo/base.py b/src/prime_rl/orchestrator/algo/base.py index e3a03a9ac54..72f59463b4d 100644 --- a/src/prime_rl/orchestrator/algo/base.py +++ b/src/prime_rl/orchestrator/algo/base.py @@ -7,7 +7,7 @@ import numpy as np import verifiers.v1 as vf -from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig +from prime_rl.configs.blocks.algorithm import AlgoConfig, FrozenModelConfig from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client if TYPE_CHECKING: diff --git a/src/prime_rl/orchestrator/algo/debug.py b/src/prime_rl/orchestrator/algo/debug.py index 3cd781d3c0a..9d74f91c446 100644 --- a/src/prime_rl/orchestrator/algo/debug.py +++ b/src/prime_rl/orchestrator/algo/debug.py @@ -2,7 +2,7 @@ from typing import TYPE_CHECKING -from prime_rl.configs.algorithm import DebugAlgoConfig +from prime_rl.configs.blocks.algorithm import DebugAlgoConfig from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces from prime_rl.orchestrator.algo.routing import assign_advantage diff --git a/src/prime_rl/orchestrator/algo/echo.py b/src/prime_rl/orchestrator/algo/echo.py index 0d166a8ed22..23a09f41278 100644 --- a/src/prime_rl/orchestrator/algo/echo.py +++ b/src/prime_rl/orchestrator/algo/echo.py @@ -5,7 +5,7 @@ import numpy as np -from prime_rl.configs.algorithm import EchoAlgoConfig +from prime_rl.configs.blocks.algorithm import EchoAlgoConfig from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm from prime_rl.orchestrator.trajectories import iter_trainable_branches from prime_rl.utils.utils import import_object diff --git a/src/prime_rl/orchestrator/algo/grpo.py b/src/prime_rl/orchestrator/algo/grpo.py index 0fd1848b756..9d89295db99 100644 --- a/src/prime_rl/orchestrator/algo/grpo.py +++ b/src/prime_rl/orchestrator/algo/grpo.py @@ -5,11 +5,8 @@ import verifiers.v1 as vf from verifiers.v1.trace import min_new_input_tokens -from prime_rl.configs.algorithm import ( - CostLengthPenaltyConfig, - GRPOAlgoConfig, - LinearSubagentLengthPenaltyConfig, -) +from prime_rl.configs.blocks.algorithm import GRPOAlgoConfig +from prime_rl.configs.blocks.length_penalty import CostLengthPenaltyConfig, LinearSubagentLengthPenaltyConfig from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces from prime_rl.orchestrator.algo.routing import assign_reward_advantage, assign_rl_weight diff --git a/src/prime_rl/orchestrator/algo/hierarchical_grpo.py b/src/prime_rl/orchestrator/algo/hierarchical_grpo.py index 1ec3e714f68..9323ed8b5bf 100644 --- a/src/prime_rl/orchestrator/algo/hierarchical_grpo.py +++ b/src/prime_rl/orchestrator/algo/hierarchical_grpo.py @@ -5,7 +5,7 @@ import verifiers.v1 as vf -from prime_rl.configs.algorithm import HierarchicalGRPOAlgoConfig +from prime_rl.configs.blocks.algorithm import HierarchicalGRPOAlgoConfig from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces from prime_rl.orchestrator.algo.routing import assign_reward_advantage diff --git a/src/prime_rl/orchestrator/algo/opd.py b/src/prime_rl/orchestrator/algo/opd.py index 19ed8cdbea8..4928d99e009 100644 --- a/src/prime_rl/orchestrator/algo/opd.py +++ b/src/prime_rl/orchestrator/algo/opd.py @@ -5,7 +5,7 @@ import numpy as np import verifiers.v1 as vf -from prime_rl.configs.algorithm import OPDAlgoConfig +from prime_rl.configs.blocks.algorithm import OPDAlgoConfig from prime_rl.orchestrator.algo.base import Algorithm from prime_rl.orchestrator.clients import ModelScorer, setup_client diff --git a/src/prime_rl/orchestrator/algo/opsd.py b/src/prime_rl/orchestrator/algo/opsd.py index 116bffc16b8..59dcdb7ab67 100644 --- a/src/prime_rl/orchestrator/algo/opsd.py +++ b/src/prime_rl/orchestrator/algo/opsd.py @@ -5,7 +5,7 @@ import numpy as np import verifiers.v1 as vf -from prime_rl.configs.algorithm import OPSDAlgoConfig +from prime_rl.configs.blocks.algorithm import OPSDAlgoConfig from prime_rl.orchestrator.algo.base import Algorithm from prime_rl.orchestrator.clients import ModelScorer from prime_rl.orchestrator.utils import episode_env_name diff --git a/src/prime_rl/orchestrator/algo/rae.py b/src/prime_rl/orchestrator/algo/rae.py index b51f3eebc30..40ad56ca938 100644 --- a/src/prime_rl/orchestrator/algo/rae.py +++ b/src/prime_rl/orchestrator/algo/rae.py @@ -3,7 +3,7 @@ from collections import defaultdict from typing import TYPE_CHECKING -from prime_rl.configs.algorithm import RAEAlgoConfig +from prime_rl.configs.blocks.algorithm import RAEAlgoConfig from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces from prime_rl.orchestrator.algo.routing import assign_reward_advantage diff --git a/src/prime_rl/orchestrator/algo/routing.py b/src/prime_rl/orchestrator/algo/routing.py index 7a932e40061..e4d87812d8f 100644 --- a/src/prime_rl/orchestrator/algo/routing.py +++ b/src/prime_rl/orchestrator/algo/routing.py @@ -7,7 +7,7 @@ import numpy as np import verifiers.v1 as vf -from prime_rl.configs.algorithm import ActionLossType +from prime_rl.configs.blocks.algorithm import ActionLossType from prime_rl.orchestrator.credit import ADVANTAGE_KEY, RL_WEIGHT_KEY, SHAPED_REWARD_KEY, advantage_values if TYPE_CHECKING: diff --git a/src/prime_rl/orchestrator/ckpt.py b/src/prime_rl/orchestrator/ckpt.py index 13ff189f7c3..588a426a6ec 100644 --- a/src/prime_rl/orchestrator/ckpt.py +++ b/src/prime_rl/orchestrator/ckpt.py @@ -35,8 +35,8 @@ import msgspec import torch -from prime_rl.configs.orchestrator import CheckpointConfig -from prime_rl.configs.shared import ckpt_output_dir +from prime_rl.configs.blocks.ckpt import ckpt_output_dir +from prime_rl.configs.components.orchestrator.ckpt import OrchestratorCheckpointConfig from prime_rl.env.heads import EpisodeHead from prime_rl.orchestrator.metrics import TrainEpisodes from prime_rl.orchestrator.train_sink import QueuedSample @@ -59,7 +59,7 @@ class CheckpointManager: - def __init__(self, output_dir: Path, config: CheckpointConfig) -> None: + def __init__(self, output_dir: Path, config: OrchestratorCheckpointConfig) -> None: self.config = config self.ckpt_dir = get_ckpt_dir(output_dir) self.snapshots = SnapshotLedger(self.ckpt_dir / SNAPSHOTS_FILE) @@ -508,7 +508,7 @@ def write(self) -> None: tmp.replace(self.path) -def setup_ckpt_manager(output_dir: Path, config: CheckpointConfig | None) -> CheckpointManager: +def setup_ckpt_manager(output_dir: Path, config: OrchestratorCheckpointConfig | None) -> CheckpointManager: """The checkpoint manager always exists: ``resume`` decides whether it loads, ``ckpt`` whether it saves (a resume without ``ckpt`` loads but saves nothing).""" - return CheckpointManager(ckpt_output_dir(output_dir, config), config or CheckpointConfig()) + return CheckpointManager(ckpt_output_dir(output_dir, config), config or OrchestratorCheckpointConfig()) diff --git a/src/prime_rl/orchestrator/clients.py b/src/prime_rl/orchestrator/clients.py index 100e37d5d80..d143b10b72b 100644 --- a/src/prime_rl/orchestrator/clients.py +++ b/src/prime_rl/orchestrator/clients.py @@ -33,8 +33,8 @@ resolve_headers, ) -from prime_rl.configs.algorithm import FrozenModelConfig -from prime_rl.configs.shared import ADMIN_TOKEN_HEADER, ClientConfig, PolicyClientConfig +from prime_rl.configs.blocks.algorithm import FrozenModelConfig +from prime_rl.configs.blocks.client import ADMIN_TOKEN_HEADER, ClientConfig, PolicyClientConfig from prime_rl.orchestrator.inference_metrics import resolve_client_roles from prime_rl.utils.logger import get_logger diff --git a/src/prime_rl/orchestrator/concurrency.py b/src/prime_rl/orchestrator/concurrency.py index a9c4d18324d..741598b1424 100644 --- a/src/prime_rl/orchestrator/concurrency.py +++ b/src/prime_rl/orchestrator/concurrency.py @@ -59,7 +59,7 @@ from collections.abc import Callable from dataclasses import dataclass, field -from prime_rl.configs.orchestrator import ConcurrencyConfig +from prime_rl.configs.components.orchestrator import ConcurrencyConfig from prime_rl.control.types import ConfigUpdate, Reconfigurable from prime_rl.orchestrator.trainer_capacity import TrainerCapacity from prime_rl.utils.logger import get_logger diff --git a/src/prime_rl/orchestrator/curriculum/base.py b/src/prime_rl/orchestrator/curriculum/base.py index 86c8a65ba16..a1020249e98 100644 --- a/src/prime_rl/orchestrator/curriculum/base.py +++ b/src/prime_rl/orchestrator/curriculum/base.py @@ -13,7 +13,7 @@ from prime_rl.utils.logger import get_logger if TYPE_CHECKING: - from prime_rl.configs.orchestrator import CurriculumConfig + from prime_rl.configs.components.orchestrator.curriculum import CurriculumConfig from prime_rl.env.heads import EpisodeHead @@ -25,7 +25,7 @@ def __init__( config: CurriculumConfig | None, tasks: Sequence[vf.Task] | Iterator[vf.Task], ) -> None: - from prime_rl.configs.orchestrator import ( + from prime_rl.configs.components.orchestrator.curriculum import ( AdvRangeGateConfig, CurriculumConfig, DifficultyPoolSamplerConfig, diff --git a/src/prime_rl/orchestrator/curriculum/gates/adv.py b/src/prime_rl/orchestrator/curriculum/gates/adv.py index 04c0ca02c5c..0c695837718 100644 --- a/src/prime_rl/orchestrator/curriculum/gates/adv.py +++ b/src/prime_rl/orchestrator/curriculum/gates/adv.py @@ -10,7 +10,7 @@ from prime_rl.orchestrator.curriculum.gates.base import AdmissionGate if TYPE_CHECKING: - from prime_rl.configs.orchestrator import AdvRangeGateConfig + from prime_rl.configs.components.orchestrator.curriculum import AdvRangeGateConfig from prime_rl.env.heads import EpisodeHead diff --git a/src/prime_rl/orchestrator/curriculum/samplers/pool.py b/src/prime_rl/orchestrator/curriculum/samplers/pool.py index 6f112d1b654..603c306ff98 100644 --- a/src/prime_rl/orchestrator/curriculum/samplers/pool.py +++ b/src/prime_rl/orchestrator/curriculum/samplers/pool.py @@ -13,7 +13,7 @@ from prime_rl.utils.logger import get_logger if TYPE_CHECKING: - from prime_rl.configs.orchestrator import DifficultyPoolSamplerConfig + from prime_rl.configs.components.orchestrator.curriculum import DifficultyPoolSamplerConfig from prime_rl.env.heads import EpisodeHead diff --git a/src/prime_rl/orchestrator/envs.py b/src/prime_rl/orchestrator/envs.py index 0237968db96..1e413b3777c 100644 --- a/src/prime_rl/orchestrator/envs.py +++ b/src/prime_rl/orchestrator/envs.py @@ -27,15 +27,15 @@ import verifiers.v1 as vf from renderers import RendererConfig -from prime_rl.configs.algorithm import FrozenModelConfig -from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig +from prime_rl.configs.blocks.algorithm import FrozenModelConfig +from prime_rl.configs.components.env_worker_pool import env_worker_pool_key +from prime_rl.configs.components.orchestrator.sources import EnvConfig, EvalSourceConfig, TrainSourceConfig from prime_rl.control.types import ConfigUpdate, Reconfigurable from prime_rl.env import EnvClient from prime_rl.env.heads import EpisodeHead from prime_rl.env.types import RecordRequest, RestoreRef, TrainRequest from prime_rl.orchestrator.algo import Algorithm, build_algorithm from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client -from prime_rl.utils.config import env_worker_pool_key from prime_rl.utils.logger import format_time, get_logger from prime_rl.utils.pathing import env_address_file diff --git a/src/prime_rl/orchestrator/orchestrator.py b/src/prime_rl/orchestrator/orchestrator.py index a661b02d0a5..f1ab0fcb8ad 100644 --- a/src/prime_rl/orchestrator/orchestrator.py +++ b/src/prime_rl/orchestrator/orchestrator.py @@ -42,8 +42,7 @@ from prime_rl.orchestrator.ckpt import CheckpointManager import prime_rl._compat # noqa: F401 from prime_rl import monitors -from prime_rl.configs.diff import ConfigChange, diff_config, merge_resumed_config -from prime_rl.configs.orchestrator import OrchestratorConfig +from prime_rl.configs.components.orchestrator import OrchestratorConfig from prime_rl.control.controller import Controller, validate_update from prime_rl.control.server import ControlServer from prime_rl.control.types import ConfigUpdate, InvalidConfigError, Reconfigurable @@ -103,6 +102,7 @@ from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel from prime_rl.utils.config import dump_resolved_config +from prime_rl.utils.diff import ConfigChange, diff_config, merge_resumed_config from prime_rl.utils.heartbeat import Heartbeat from prime_rl.utils.logger import format_time, get_logger, setup_logger from prime_rl.utils.pathing import ( diff --git a/src/prime_rl/orchestrator/train_sink.py b/src/prime_rl/orchestrator/train_sink.py index d9000b42c03..6f30367e5fd 100644 --- a/src/prime_rl/orchestrator/train_sink.py +++ b/src/prime_rl/orchestrator/train_sink.py @@ -21,7 +21,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING -from prime_rl.configs.orchestrator import OrchestratorConfig +from prime_rl.configs.components.orchestrator import OrchestratorConfig from prime_rl.control.types import ConfigUpdate, Reconfigurable from prime_rl.orchestrator.algo.base import iter_trainable_traces from prime_rl.orchestrator.credit import branch_token_advantages, token_advantages, trace_advantage, trace_rl_weight diff --git a/src/prime_rl/scripts/resume_cleanup.py b/src/prime_rl/scripts/resume_cleanup.py index e7ff3fb4ab9..983e0fc4643 100644 --- a/src/prime_rl/scripts/resume_cleanup.py +++ b/src/prime_rl/scripts/resume_cleanup.py @@ -5,7 +5,8 @@ from pathlib import Path from typing import Literal -from prime_rl.configs.shared import ResumeConfig +from prime_rl.configs.blocks.ckpt import ResumeConfig +from prime_rl.configs.components.online_eval import SFTOnlineEvalConfig from prime_rl.utils.pathing import clean_future_steps, get_ckpt_dir, resolve_latest_ckpt_step ResumeTarget = int | Literal["latest"] | None @@ -26,6 +27,14 @@ def resolve_resume_step( return resolve_latest_ckpt_step(ckpt_dir, orchestrator_ckpt_dir) +def resolve_online_eval_resume_step(config: SFTOnlineEvalConfig) -> int | None: + """The trainer step the process resumes at: ``resume_step``, else the step the trainer resumes from. The + trainer blocks in its startup broadcast until this process receives it, so it cannot add a checkpoint first.""" + if config.resume_step is not None: + return config.resume_step + return resolve_resume_step(config.resume, get_ckpt_dir(config.ckpt_output_dir or config.output_dir)) + + def prune_incomplete_checkpoints(ckpt_dir: Path) -> None: if not ckpt_dir.exists(): return diff --git a/src/prime_rl/templates/_launch_rank.sh.j2 b/src/prime_rl/templates/_launch_rank.sh.j2 index 195139007b8..3a007c50142 100644 --- a/src/prime_rl/templates/_launch_rank.sh.j2 +++ b/src/prime_rl/templates/_launch_rank.sh.j2 @@ -21,7 +21,7 @@ launch_inference_rank() { # rank on the node. Node-local /tmp also avoids inheriting an absent submit-node TMPDIR. local rpcbase="/tmp/vllm-rpc-$USER-$SLURM_JOB_ID-$port" mkdir -p "$rpcbase" - local -a cmd=(uv run inference @ "$CONFIG_PATH" + local -a cmd=(uv run engine @ "$CONFIG_PATH" --server.host 0.0.0.0 --server.port "$port" --vllm.data-parallel-size "$dp" --vllm.data-parallel-size-local 1 --vllm.api-server-count 1) [ -n "$rpc" ] && cmd+=(--vllm.data-parallel-rpc-port "$rpc") @@ -51,7 +51,6 @@ launch_inference_rank() { fi if [ -n "${ADMIN_TOKEN_ENV:-}" ]; then rank_env+=("$ADMIN_TOKEN_ENV") - cmd+=(--server.require-admin-token) fi env "${rank_env[@]}" "${cmd[@]}" 2>&1 | tee -a "$log" & INFERENCE_PORT_BY_PID[$!]="$port" diff --git a/src/prime_rl/templates/_launch_router.sh.j2 b/src/prime_rl/templates/_launch_router.sh.j2 index 8dbc3b60153..d35c77b70cc 100644 --- a/src/prime_rl/templates/_launch_router.sh.j2 +++ b/src/prime_rl/templates/_launch_router.sh.j2 @@ -5,9 +5,9 @@ all nodes for regular mode; for disaggregated mode all prefill nodes across replicas, then all decode nodes (matching the logical node order in endpoints.yaml). #} -# launch_router +# launch_router launch_router() { - local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" + local mode="$1" worker_args="$2" port="$3" log="$4" {%- if router.type == "llm-d" %} echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port" | tee "$log" export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH" @@ -71,20 +71,7 @@ LLMD_EOF {%- else %} local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)" echo "Starting $tag on $LOCAL_IP:$port" | tee "$log" - local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port" - --request-id-headers x-session-id - --request-timeout-secs {{ router.request_timeout_secs }} - --prometheus-port "$((port + 21000))" - --worker-startup-timeout-secs 4200 --worker-startup-check-interval 1) - if [ "$mode" = pd ]; then - cmd+=(--vllm-pd-disaggregation $worker_args --pd-turn-retries {{ router.pd_turn_retries }}) -{%- if pd_bidirectional %} - # Bidirectional KV transfer: keep each session's decode blocks and hand them to its next prefill (once). - cmd+=(--pd-bidirectional-kv --pd-bidirectional-ttl-secs {{ pd_bidirectional.effective_router_ttl_s }}) -{%- endif %} - else - cmd+=(--worker-urls $worker_args) - fi - "${cmd[@]}" >> "$log" 2>&1 & + # worker_args holds the engine URLs as router flags; router.json holds the rest. + uv run router @ "$CONFIG_DIR/router.json" $worker_args >> "$log" 2>&1 & {%- endif %} } diff --git a/src/prime_rl/templates/inference.sbatch.j2 b/src/prime_rl/templates/inference.sbatch.j2 index 63b8ece34f2..88cdfa5d0a0 100755 --- a/src/prime_rl/templates/inference.sbatch.j2 +++ b/src/prime_rl/templates/inference.sbatch.j2 @@ -89,20 +89,22 @@ export HOSTNAMES_STR="${HOSTNAMES[*]}" {% if is_disaggregated -%} # Single global router on node 0 fronts every per-rank endpoint. INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1" -ROUTER_ARGS="" -# External-LB: one --prefill/--decode endpoint per DP rank (PORT + k) on each node. +PREFILL_URLS="" +DECODE_URLS="" +# External-LB: one prefill/decode endpoint per DP rank (PORT + k) on each node. for ((p=0; p 1 %} @@ -115,6 +117,7 @@ for host in ${HOSTNAMES[@]}; do ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))" done done +ROUTER_ARGS="--worker-urls$ROUTER_ARGS" export INFER_URLS export ROUTER_ARGS {%- else %} @@ -240,7 +243,7 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH' export VLLM_NIXL_SIDE_CHANNEL_PORT=5600 export NIXL_NIC_AFFINITY={{ 1 if nixl_nic_affinity else 0 }} - # InferenceConfig.to_namespace() builds the kv_transfer_config (NIXL transfer + any KV + # EngineConfig.to_namespace() builds the kv_transfer_config (NIXL transfer + any KV # offload connector) from the per-node config. DECODE_COMPILE_CFG='{"cudagraph_mode":"FULL_DECODE_ONLY"}' @@ -289,13 +292,13 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH' ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}" fi - CONFIG_PATH="$CONFIG_DIR/inference-$ROLE.json" + CONFIG_PATH="$CONFIG_DIR/engine-$ROLE.json" echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \ | tee $LOG_DIR/inference/node_${INFER_NODE_RANK}.log # Start the single global router on node 0 (external LB across all per-rank endpoints) if [ "$INFER_NODE_RANK" -eq 0 ]; then - launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$LOG_DIR/inference/router.log" + launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "$LOG_DIR/inference/router.log" fi {%- if router.type == "llm-d" %} # pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT @@ -321,7 +324,7 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH' # External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP # slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP # group rooted on the role-replica head (HEAD_HOST); the router balances across the per-rank - # endpoints. The kv_transfer_config is built in InferenceConfig.to_namespace() from the config. + # endpoints. The kv_transfer_config is built in EngineConfig.to_namespace() from the config. if [ "$ROLE_RANK" -eq 0 ]; then DP_ADDR=$LOCAL_IP; else DP_ADDR=$HEAD_HOST; fi for k in $(seq 0 $((DP_PER_NODE - 1))); do GLOBAL_RANK=$((ROLE_RANK * DP_PER_NODE + k)) @@ -345,7 +348,7 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH' # Start the single global router on node 0 (balances across per-rank endpoints — no intra-node DP header) if [ "$INFER_NODE_RANK" -eq 0 ]; then - launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$LOG_DIR/inference/router.log" + launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "$LOG_DIR/inference/router.log" fi # External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local), @@ -368,8 +371,9 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH' {%- else %} echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" | tee $LOG_DIR/inference/node_${INFER_NODE_RANK}.log + # One node runs the router and its engine like a local launch. uv run inference \ - @ $CONFIG_PATH \ + @ $CONFIG_DIR/inference.json --slurm None --no-dry-run \ 2>&1 | tee -a $LOG_DIR/inference/node_${INFER_NODE_RANK}.log & {%- endif %} diff --git a/src/prime_rl/templates/multi_node_rl.sbatch.j2 b/src/prime_rl/templates/multi_node_rl.sbatch.j2 index 97fc71fc61b..5fa70a8f9ec 100644 --- a/src/prime_rl/templates/multi_node_rl.sbatch.j2 +++ b/src/prime_rl/templates/multi_node_rl.sbatch.j2 @@ -96,6 +96,8 @@ INFER_URLS="http://${INFER_HOSTS[0]}:${ROUTER_PORT}/v1" ADMIN_URLS="" ROUTER_ARGS="" {% if is_disaggregated -%} +PREFILL_URLS="" +DECODE_URLS="" # External-LB: one prefill/decode endpoint per DP rank (PORT + k) on each node. for ((r=0; r sidecar (DECODE_SIDECAR_PORT @@ -430,7 +434,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then # External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP # slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP # group rooted on the role-replica head (HEAD_HOST); the router balances across the per-rank - # endpoints. The kv_transfer_config is built in InferenceConfig.to_namespace() from the config. + # endpoints. The kv_transfer_config is built in EngineConfig.to_namespace() from the config. if [ "$ROLE_RANK" -eq 0 ]; then DP_ADDR=$LOCAL_IP; else DP_ADDR=$HEAD_HOST; fi for k in $(seq 0 $((INFERENCE_DP_LOCAL - 1))); do GLOBAL_RANK=$((START_RANK + k)) @@ -447,7 +451,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then {%- else -%} # Start the single global router on inference node 0 (external LB across all per-rank endpoints) if [ "$INFER_NODE_RANK" -eq 0 ]; then - launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$LOG_DIR/inference/router.log" + launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "$LOG_DIR/inference/router.log" fi # External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d), diff --git a/src/prime_rl/templates/multi_node_sft.sbatch.j2 b/src/prime_rl/templates/multi_node_sft.sbatch.j2 index 0e36cc3a5a8..13a11da9071 100644 --- a/src/prime_rl/templates/multi_node_sft.sbatch.j2 +++ b/src/prime_rl/templates/multi_node_sft.sbatch.j2 @@ -107,6 +107,7 @@ for host in ${INFER_HOSTS[@]}; do ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))" done done +ROUTER_ARGS="--worker-urls$ROUTER_ARGS" export INFER_URLS export ADMIN_URLS export ROUTER_ARGS @@ -195,7 +196,7 @@ python -m prime_rl.entrypoints.run_owner {{ entrypoint }} {{ run_config_path }} if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then INFER_NODE_RANK=$SLURM_PROCID LOCAL_IP=$(hostname -I | awk "{print \$1}") - CONFIG_PATH=$CONFIG_DIR/inference.json + CONFIG_PATH=$CONFIG_DIR/engine.json # Inference env vars: launcher defaults + [env_vars] + [inference.env_vars] {%- for key, value in inference_env_vars.items() %} @@ -228,12 +229,13 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then done if [ "$INFER_NODE_RANK" -eq 0 ]; then - launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$LOG_DIR/inference/router.log" + launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "$LOG_DIR/inference/router.log" {%- if eval_env_names %} mkdir -p $LOG_DIR/envs/eval {%- for name in eval_env_names %} uv run env-worker-pool @ $CONFIG_DIR/envs/eval/{{ name }}.json \ + --address-file $CONFIG_DIR/envs/eval/{{ name }}.address \ > $LOG_DIR/envs/eval/{{ name }}.log 2>&1 & {%- endfor %} {%- endif %} @@ -245,7 +247,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then {%- endfor %} ( {% if admin_token.guards and admin_token.by_process['online-eval'].sends %}{{ admin_token.by_process['online-eval'].sends }}="$ADMIN_TOKEN" {% endif %}{% if admin_token.guards and admin_token.by_process['online-eval'].checks %}{{ admin_token.by_process['online-eval'].checks }}_SHA256="$ADMIN_TOKEN_DIGEST" {% endif %}PRL_LOG_DIR=$LOG_DIR WANDB_SHARED_LABEL=online-eval uv run python -m prime_rl.eval.online \ - @ $CONFIG_DIR/eval.json \ + @ $CONFIG_DIR/online-eval.json \ --client.base-url $INFER_URLS \ --client.admin-base-url $ADMIN_URLS \ {%- if use_nccl_broadcast %} @@ -287,9 +289,7 @@ else --local-ranks-filter={{ ranks_filter }} \ -m prime_rl.trainer.{{ entrypoint }}.train \ @ $TRAIN_CONFIG_PATH \ -{%- if use_nccl_broadcast %} - --weight-broadcast.host 0.0.0.0 \ -{%- elif uses_modelexpress_server %} +{%- if uses_modelexpress_server %} --weight-broadcast.host $WEIGHT_BROADCAST_HOST \ {%- endif %} 2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log diff --git a/src/prime_rl/templates/single_node_rl.sbatch.j2 b/src/prime_rl/templates/single_node_rl.sbatch.j2 index cd20cd3fac8..89864a3f2fc 100644 --- a/src/prime_rl/templates/single_node_rl.sbatch.j2 +++ b/src/prime_rl/templates/single_node_rl.sbatch.j2 @@ -42,4 +42,4 @@ uv sync {{ sync_args }} {{ pre_run_command }} {% endif %} export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")} -uv run rl @ {{ config_path }} +uv run rl @ {{ config_path }} --slurm None --no-dry-run --no-clean diff --git a/src/prime_rl/templates/single_node_sft.sbatch.j2 b/src/prime_rl/templates/single_node_sft.sbatch.j2 index be83e3279a6..87d7a84e984 100644 --- a/src/prime_rl/templates/single_node_sft.sbatch.j2 +++ b/src/prime_rl/templates/single_node_sft.sbatch.j2 @@ -41,4 +41,4 @@ uv sync {{ sync_args }} # Pre-run command {{ pre_run_command }} {% endif %} -uv run {{ entrypoint }} @ {{ config_path }} +uv run {{ entrypoint }} @ {{ config_path }} --slurm None --no-dry-run --no-clean diff --git a/src/prime_rl/trainer/activation_checkpointing.py b/src/prime_rl/trainer/activation_checkpointing.py index b206ec58e02..258c4d1e52e 100644 --- a/src/prime_rl/trainer/activation_checkpointing.py +++ b/src/prime_rl/trainer/activation_checkpointing.py @@ -19,7 +19,7 @@ create_selective_checkpoint_contexts, ) -from prime_rl.configs.trainer import MODULE_TARGET_SEPARATOR, ActivationCheckpointConfig +from prime_rl.configs.components.trainer.model import MODULE_TARGET_SEPARATOR, ActivationCheckpointConfig # FSDP's replay-specific hooks emit a different number of profiler markers. SAC_IGNORED_OPS.update( diff --git a/src/prime_rl/trainer/ckpt.py b/src/prime_rl/trainer/ckpt.py index ab80518d238..f6abf2e8ce1 100644 --- a/src/prime_rl/trainer/ckpt.py +++ b/src/prime_rl/trainer/ckpt.py @@ -34,8 +34,9 @@ from torchdata.stateful_dataloader import StatefulDataLoader from transformers import AutoConfig, GenerationConfig, PretrainedConfig, PreTrainedTokenizerBase, ProcessorMixin -from prime_rl.configs.shared import ResumeConfig, ckpt_output_dir -from prime_rl.configs.trainer import CheckpointConfig, ModelConfig +from prime_rl.configs.blocks.ckpt import ResumeConfig, ckpt_output_dir +from prime_rl.configs.components.trainer.ckpt import TrainerCheckpointConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.ckpt_sync import METADATA_FILE, get_remote_steps, remove_remote_step from prime_rl.trainer.data import with_workers from prime_rl.trainer.lora import has_lora_layers @@ -137,7 +138,7 @@ def load_generation_config(model_name: str) -> GenerationConfig | None: def setup_model_files( - config: ModelConfig, tokenizer: PreTrainedTokenizerBase, processor: ProcessorMixin | None + config: TrainerModelConfig, tokenizer: PreTrainedTokenizerBase, processor: ProcessorMixin | None ) -> ModelFiles: generation_config = load_generation_config(config.name) model_config = AutoConfig.from_pretrained(config.name, trust_remote_code=config.trust_remote_code) @@ -556,7 +557,7 @@ class CheckpointManager: def __init__( self, output_dir: Path, - config: CheckpointConfig, + config: TrainerCheckpointConfig, model_files: ModelFiles, resume: ResumeConfig | None = None, ): @@ -929,14 +930,14 @@ def _start_sync(self) -> subprocess.Popen: def setup_ckpt_manager( output_dir: Path, - ckpt_config: CheckpointConfig | None, + ckpt_config: TrainerCheckpointConfig | None, model_files: ModelFiles, resume: ResumeConfig | None = None, ) -> CheckpointManager: """The checkpoint manager always exists: ``resume`` decides whether it loads, ``ckpt`` whether it saves (a resume without ``ckpt`` loads but saves nothing).""" return CheckpointManager( - ckpt_output_dir(output_dir, ckpt_config), ckpt_config or CheckpointConfig(), model_files, resume + ckpt_output_dir(output_dir, ckpt_config), ckpt_config or TrainerCheckpointConfig(), model_files, resume ) diff --git a/src/prime_rl/trainer/data.py b/src/prime_rl/trainer/data.py index aff22c819d4..045766e6b39 100644 --- a/src/prime_rl/trainer/data.py +++ b/src/prime_rl/trainer/data.py @@ -9,7 +9,7 @@ from torch.utils.data import IterableDataset, get_worker_info from torchdata.stateful_dataloader import StatefulDataLoader -from prime_rl.configs.supervised import BaseDataConfig +from prime_rl.configs.components.trainer.data import BaseDataConfig from prime_rl.utils.logger import get_logger diff --git a/src/prime_rl/trainer/lora.py b/src/prime_rl/trainer/lora.py index 24401aa1114..792ece6b2df 100644 --- a/src/prime_rl/trainer/lora.py +++ b/src/prime_rl/trainer/lora.py @@ -4,7 +4,7 @@ import torch import torch.nn as nn -from prime_rl.configs.trainer import LoRAConfig +from prime_rl.configs.components.trainer.model import LoRAConfig from prime_rl.trainer.models.layers.lora import ( LoRAGptOssGroupedExperts, LoRAGroupedExperts, diff --git a/src/prime_rl/trainer/model.py b/src/prime_rl/trainer/model.py index 8fd171571d0..1b1081d4374 100644 --- a/src/prime_rl/trainer/model.py +++ b/src/prime_rl/trainer/model.py @@ -30,14 +30,14 @@ from transformers import AutoConfig, AutoTokenizer, GenerationConfig, PretrainedConfig from transformers.tokenization_utils import PreTrainedTokenizer -from prime_rl.configs.trainer import ( +from prime_rl.configs.blocks.model import TokenizerConfig +from prime_rl.configs.components.trainer.model import ( MODULE_TARGET_SEPARATOR, ActivationCheckpointConfig, CompileConfig, FP8Config, - ModelConfig, MXFP8Config, - TokenizerConfig, + TrainerModelConfig, ) from prime_rl.trainer.activation_checkpointing import ( TokenChunkedCheckpointWrapper, @@ -331,7 +331,7 @@ def get_expert_load_stats(tokens_per_expert: Tensor, group: dist.ProcessGroup) - return {name: value.item() for name, value in compute_expert_load_stats(tokens_per_expert).items()} -def get_model(config: ModelConfig, dtype: torch.dtype = torch.bfloat16) -> nn.Module: +def get_model(config: TrainerModelConfig, dtype: torch.dtype = torch.bfloat16) -> nn.Module: logger = get_logger() logger.debug( f"Loading model config (name={config.name}, attn={config.attn}, trust_remote_code={config.trust_remote_code})" @@ -444,7 +444,7 @@ def get_model(config: ModelConfig, dtype: torch.dtype = torch.bfloat16) -> nn.Mo return model -def use_resumed_model_files(model: ModelConfig, tokenizer: TokenizerConfig, step_dir: Path) -> None: +def use_resumed_model_files(model: TrainerModelConfig, tokenizer: TokenizerConfig, step_dir: Path) -> None: """A run started from a checkpoint step directory resumes with the config.json and tokenizer of the step directory it resumes, which holds copies (``ModelFiles``), so the source may be gone by then. The source is recognized by its name, since it may no longer exist.""" @@ -455,7 +455,7 @@ def use_resumed_model_files(model: ModelConfig, tokenizer: TokenizerConfig, step model.name = str(step_dir) -def check_ckpt_dir(config: ModelConfig) -> None: +def check_ckpt_dir(config: TrainerModelConfig) -> None: """A checkpoint step directory supplies the architecture with its config.json.""" if is_checkpoint_step_dir(config.name) and not (Path(config.name) / "config.json").exists(): raise FileNotFoundError( @@ -504,7 +504,7 @@ def placement_fn(parameter: nn.Parameter) -> ShardPlacementResult | Shard | None return placement_fn -def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims): +def setup_fsdp(model: nn.Module, config: TrainerModelConfig, parallel_dims: ParallelDims): mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=DTYPE_MAP[config.reduce_dtype]) offload_policy: OffloadPolicy = OffloadPolicy() @@ -728,7 +728,7 @@ def floating_tensors() -> dict[str, Tensor]: ) -def load_dcp_from_hf(model: nn.Module, config: ModelConfig): +def load_dcp_from_hf(model: nn.Module, config: TrainerModelConfig): device = "cuda" model.to_empty(device=device) torch.distributed.barrier() @@ -953,7 +953,7 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig): ) -def apply_quantization(model: nn.Module, config: ModelConfig) -> None: +def apply_quantization(model: nn.Module, config: TrainerModelConfig) -> None: """Swap dense linear modules to the configured low-precision path. Routed-expert compute is configured independently by ``model.moe.compute``. @@ -979,7 +979,7 @@ def apply_quantization(model: nn.Module, config: ModelConfig) -> None: replace_linear_with_mxfp8_linear(model, recipe=quant.recipe, ignore_modules=ignore_modules) -def configure_trainable_parameters(model: nn.Module, config: ModelConfig) -> nn.Module | None: +def configure_trainable_parameters(model: nn.Module, config: TrainerModelConfig) -> nn.Module | None: """Apply LoRA and identify any vision encoder that must remain frozen.""" frozen_vision_encoder = None if config.vlm is not None and config.vlm.freeze_vision_encoder: @@ -1031,7 +1031,7 @@ def _validate_flash_attn_4_installed() -> None: ) -def resolve_auto_attn(config: ModelConfig) -> None: +def resolve_auto_attn(config: TrainerModelConfig) -> None: """Resolve ``attn='auto'`` to a concrete flash attention implementation based on GPU architecture. FA4 on datacenter Blackwell (SM10x/SM11x, e.g. B200, B300), FA3 on Hopper (SM90), FA2 @@ -1053,7 +1053,7 @@ def resolve_auto_attn(config: ModelConfig) -> None: def setup_model( - config: ModelConfig, + config: TrainerModelConfig, parallel_dims: ParallelDims, loading_from_checkpoint_later: bool = False, ) -> nn.Module: diff --git a/src/prime_rl/trainer/models/glm5_next/modeling_glm5_next.py b/src/prime_rl/trainer/models/glm5_next/modeling_glm5_next.py index 59d3e703c62..4f22eb1c29c 100644 --- a/src/prime_rl/trainer/models/glm5_next/modeling_glm5_next.py +++ b/src/prime_rl/trainer/models/glm5_next/modeling_glm5_next.py @@ -10,7 +10,7 @@ import torch from torch import Tensor, nn -from prime_rl.configs.trainer import DSABackend +from prime_rl.configs.components.trainer.model import DSABackend from prime_rl.trainer.models.base import PreTrainedModelPrimeRL, TextModelOutput from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection from prime_rl.trainer.models.glm5_next.configuration_glm5_next import Glm5NextConfig, Glm5NextTextConfig diff --git a/src/prime_rl/trainer/models/glm5_next/sparse_attention.py b/src/prime_rl/trainer/models/glm5_next/sparse_attention.py index 6a6cba5c33a..f426f757553 100644 --- a/src/prime_rl/trainer/models/glm5_next/sparse_attention.py +++ b/src/prime_rl/trainer/models/glm5_next/sparse_attention.py @@ -4,7 +4,7 @@ import torch.nn.functional as F from torch import nn -from prime_rl.configs.trainer import DSABackend +from prime_rl.configs.components.trainer.model import DSABackend from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer from prime_rl.trainer.models.layers.norms import LayerNorm, RMSNorm, RMSNormConfig from prime_rl.utils.cp import CPContext, gather_for_cp diff --git a/src/prime_rl/trainer/models/glm_moe_dsa/sparse_mla_attention.py b/src/prime_rl/trainer/models/glm_moe_dsa/sparse_mla_attention.py index 67ceadf1471..8e5e3eb97bb 100644 --- a/src/prime_rl/trainer/models/glm_moe_dsa/sparse_mla_attention.py +++ b/src/prime_rl/trainer/models/glm_moe_dsa/sparse_mla_attention.py @@ -4,7 +4,7 @@ import torch.distributed as dist from torch import nn -from prime_rl.configs.trainer import DSABackend +from prime_rl.configs.components.trainer.model import DSABackend from prime_rl.trainer.models.kernels import cudnn_flashmla_error from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer from prime_rl.trainer.models.layers.attn import quadratic_attention_flops diff --git a/src/prime_rl/trainer/models/kernels/sparse_mla_bwd.py b/src/prime_rl/trainer/models/kernels/sparse_mla_bwd.py index 21cc480bf70..5962adbadb6 100644 --- a/src/prime_rl/trainer/models/kernels/sparse_mla_bwd.py +++ b/src/prime_rl/trainer/models/kernels/sparse_mla_bwd.py @@ -19,7 +19,7 @@ import torch from tilelang import language as T -from prime_rl.configs.trainer import DSABackend +from prime_rl.configs.components.trainer.model import DSABackend @tilelang.jit(out_idx=[-1]) diff --git a/src/prime_rl/trainer/models/kernels/sparse_mla_fwd.py b/src/prime_rl/trainer/models/kernels/sparse_mla_fwd.py index 5945bc65b73..032a263e688 100644 --- a/src/prime_rl/trainer/models/kernels/sparse_mla_fwd.py +++ b/src/prime_rl/trainer/models/kernels/sparse_mla_fwd.py @@ -19,7 +19,7 @@ import torch from tilelang import language as T -from prime_rl.configs.trainer import DSABackend +from prime_rl.configs.components.trainer.model import DSABackend from prime_rl.trainer.models.kernels.sparse_mla_bwd import ( flat_kv_indices, sparse_mla_backward, diff --git a/src/prime_rl/trainer/models/layers/llep_mega_moe.py b/src/prime_rl/trainer/models/layers/llep_mega_moe.py index b213bb84a0d..12a082e156e 100644 --- a/src/prime_rl/trainer/models/layers/llep_mega_moe.py +++ b/src/prime_rl/trainer/models/layers/llep_mega_moe.py @@ -13,7 +13,7 @@ import torch from torch.distributed import ProcessGroup -from prime_rl.configs.trainer import LLEPConfig +from prime_rl.configs.components.trainer.moe import LLEPConfig from prime_rl.trainer.models.kernels.mega_moe_mxfp8 import mx_cast, pack_ue8m0_k_major from prime_rl.trainer.models.layers.expert_compute import to_local from prime_rl.trainer.models.layers.mega_moe import ( diff --git a/src/prime_rl/trainer/models/layers/mxfp8_linear.py b/src/prime_rl/trainer/models/layers/mxfp8_linear.py index 8e74335b434..6db91aabbd1 100644 --- a/src/prime_rl/trainer/models/layers/mxfp8_linear.py +++ b/src/prime_rl/trainer/models/layers/mxfp8_linear.py @@ -8,7 +8,7 @@ from torchao.prototype.mx_formats import ScaleCalculationMode from torchao.quantization.quantize_.common import KernelPreference -from prime_rl.configs.trainer import MXFP8Recipe +from prime_rl.configs.components.trainer.moe import MXFP8Recipe from prime_rl.utils.logger import get_logger diff --git a/src/prime_rl/trainer/moe_runtime.py b/src/prime_rl/trainer/moe_runtime.py index 554c50d2511..d5c0e346bf8 100644 --- a/src/prime_rl/trainer/moe_runtime.py +++ b/src/prime_rl/trainer/moe_runtime.py @@ -5,12 +5,12 @@ from torch.distributed import ProcessGroup from torch.distributed.tensor.parallel import parallelize_module -from prime_rl.configs.trainer import ( +from prime_rl.configs.components.trainer.model import TrainerModelConfig +from prime_rl.configs.components.trainer.moe import ( BF16MoEComputeConfig, DeepEPMoEDispatchConfig, DeepGemmFP8MoEComputeConfig, MegaMoeMoEDispatchConfig, - ModelConfig, MoERuntimeConfig, MXFP8MoEComputeConfig, NVFP4MoEComputeConfig, @@ -42,14 +42,14 @@ from prime_rl.utils.logger import get_logger -def setup_moe_comm_env(config: ModelConfig) -> None: +def setup_moe_comm_env(config: TrainerModelConfig) -> None: """Environment the MoE dispatch needs before torch distributed creates NCCL communicators.""" dispatch = config.moe.dispatch if isinstance(dispatch, MegaMoeMoEDispatchConfig): default_nccl_max_ctas(dispatch.num_reserved_sms, num_concurrent_nccl_kernels(config.dp_replicate)) -def _resolve_expert_compute(config: ModelConfig) -> ExpertCompute: +def _resolve_expert_compute(config: TrainerModelConfig) -> ExpertCompute: compute = config.moe.compute if isinstance(compute, BF16MoEComputeConfig): if compute.backend == "sonicmoe": @@ -111,7 +111,7 @@ def _resolve_mega_moe_compute( return MegaMoEExpertCompute(**kwargs, precision=dispatch.precision, four_over_six=dispatch.four_over_six) -def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims) -> None: +def configure_moe_runtime(model: nn.Module, config: TrainerModelConfig, parallel_dims: ParallelDims) -> None: moe_layers = [module for module in model.modules() if isinstance(module, MoE)] if not moe_layers: if config.moe != MoERuntimeConfig(): diff --git a/src/prime_rl/trainer/optim/__init__.py b/src/prime_rl/trainer/optim/__init__.py index 0f83ffdc988..0c0f8d7cf34 100644 --- a/src/prime_rl/trainer/optim/__init__.py +++ b/src/prime_rl/trainer/optim/__init__.py @@ -2,7 +2,8 @@ from torch import nn from torch.optim import AdamW, Optimizer -from prime_rl.configs.trainer import OffloadMode, OptimizerConfig +from prime_rl.configs.components.trainer.model import OffloadMode +from prime_rl.configs.components.trainer.optim import OptimizerConfig from prime_rl.trainer.models.fusions import get_model_packed_parameters from prime_rl.trainer.models.layers.ngram import NGramTable from prime_rl.trainer.optim.base import OffloadOptimizer as OffloadOptimizer diff --git a/src/prime_rl/trainer/parallel_dims.py b/src/prime_rl/trainer/parallel_dims.py index 2292501b192..b1da174cc91 100644 --- a/src/prime_rl/trainer/parallel_dims.py +++ b/src/prime_rl/trainer/parallel_dims.py @@ -25,7 +25,7 @@ from torch._utils import _get_available_device_type from torch.distributed.device_mesh import DeviceMesh, init_device_mesh -from prime_rl.configs.trainer import ModelConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.utils.logger import format_time, get_logger device_type = _get_available_device_type() or "cuda" @@ -267,7 +267,7 @@ def logger(self): return get_logger() -def _num_experts(config: ModelConfig) -> int | None: +def _num_experts(config: TrainerModelConfig) -> int | None: """Return the routed expert count from the HuggingFace config, or None for non-MoE models.""" from transformers import AutoConfig @@ -288,7 +288,7 @@ def auto_ep(fsdp_island_size: int, num_experts: int, cp: int) -> int: ) -def resolve_ep(config: ModelConfig) -> None: +def resolve_ep(config: TrainerModelConfig) -> None: """Resolve ``ep="auto"`` in-place to a concrete integer: ``auto_ep`` for MoE models, 1 otherwise.""" if config.ep != "auto": return @@ -318,7 +318,7 @@ def resolve_ep(config: ModelConfig) -> None: ) -def get_parallel_dims(config: ModelConfig) -> ParallelDims: +def get_parallel_dims(config: TrainerModelConfig) -> ParallelDims: assert isinstance(config.ep, int), ( f"config.ep must be resolved to an int before get_parallel_dims; got {config.ep!r}. " "Call resolve_ep(config) first." diff --git a/src/prime_rl/trainer/pretrain/data.py b/src/prime_rl/trainer/pretrain/data.py index 4baaeb93306..02bce80360d 100644 --- a/src/prime_rl/trainer/pretrain/data.py +++ b/src/prime_rl/trainer/pretrain/data.py @@ -16,7 +16,7 @@ import torch from transformers.tokenization_utils import PreTrainedTokenizer -from prime_rl.configs.pretrain import PretrainDataConfig +from prime_rl.configs.components.trainer.data import PretrainDataConfig from prime_rl.trainer.data import SKIP_DATALOADER, StatefulIterableDataset, due, mixture_changed from prime_rl.utils.bin_packing import fill_rows from prime_rl.utils.distributed import all_gather_bytes diff --git a/src/prime_rl/trainer/pretrain/train.py b/src/prime_rl/trainer/pretrain/train.py index 06e7375438f..4e3697c5ad3 100644 --- a/src/prime_rl/trainer/pretrain/train.py +++ b/src/prime_rl/trainer/pretrain/train.py @@ -1,4 +1,4 @@ -from prime_rl.configs.pretrain import PretrainConfig +from prime_rl.configs.components.trainer.pretrain import PretrainTrainerConfig from prime_rl.trainer.train import train from prime_rl.utils.config import cli from prime_rl.utils.process import set_proc_title @@ -6,7 +6,7 @@ def main(): set_proc_title("PretrainTrainer") - train(cli(PretrainConfig)) + train(cli(PretrainTrainerConfig)) if __name__ == "__main__": diff --git a/src/prime_rl/trainer/rl/data.py b/src/prime_rl/trainer/rl/data.py index ca153397238..7789db587a6 100644 --- a/src/prime_rl/trainer/rl/data.py +++ b/src/prime_rl/trainer/rl/data.py @@ -12,8 +12,8 @@ from jaxtyping import Bool, Float, Int from torch import Tensor -from prime_rl.configs.shared import ZMQTransportConfig -from prime_rl.configs.trainer import FakeDataLoaderConfig +from prime_rl.configs.blocks.transport import ZMQTransportConfig +from prime_rl.configs.components.trainer.data import FakeDataLoaderConfig from prime_rl.trainer.rl.planner import plan_digest, prepare_batch from prime_rl.trainer.world import get_world from prime_rl.transports.batch import ( diff --git a/src/prime_rl/trainer/rl/loss.py b/src/prime_rl/trainer/rl/loss.py index 984a32f1b0c..9376504848a 100644 --- a/src/prime_rl/trainer/rl/loss.py +++ b/src/prime_rl/trainer/rl/loss.py @@ -6,12 +6,7 @@ from jaxtyping import Bool, Float, Int, jaxtyped from torch import Tensor -from prime_rl.configs.trainer import ( - CustomLossConfig, - IcePopLossConfig, - IPOLossConfig, - LossConfig, -) +from prime_rl.configs.components.trainer.loss import CustomLossConfig, IcePopLossConfig, IPOLossConfig, LossConfig from prime_rl.trainer.models.layers.lm_head import TokenSupport, support_replay_mask from prime_rl.utils.utils import import_object diff --git a/src/prime_rl/trainer/rl/train.py b/src/prime_rl/trainer/rl/train.py index 245d275a9ce..0139c0a2c81 100644 --- a/src/prime_rl/trainer/rl/train.py +++ b/src/prime_rl/trainer/rl/train.py @@ -21,7 +21,8 @@ from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager, setup_model_files from prime_rl.trainer.optim import setup_optimizer from prime_rl.trainer.scheduler import setup_scheduler -from prime_rl.configs.trainer import TrainerConfig, rl_micro_batch_multiple +from prime_rl.configs.components.trainer import TrainerConfig +from prime_rl.configs.components.trainer.model import rl_micro_batch_multiple from prime_rl.trainer.rl.data import ( DataLoader, FakeDataLoader, @@ -98,7 +99,7 @@ from prime_rl.control.server import ControlServer from prime_rl.utils.process import set_proc_title from prime_rl.utils.worker_pool import WorkerPool -from prime_rl.configs.shared import ckpt_output_dir +from prime_rl.configs.blocks.ckpt import ckpt_output_dir from prime_rl.utils.pathing import ( get_ckpt_dir, get_step_path, diff --git a/src/prime_rl/trainer/rl/warmup.py b/src/prime_rl/trainer/rl/warmup.py index 56da5befb12..aca5d1af41f 100644 --- a/src/prime_rl/trainer/rl/warmup.py +++ b/src/prime_rl/trainer/rl/warmup.py @@ -4,7 +4,8 @@ import torch from torch import Tensor, nn -from prime_rl.configs.trainer import TrainerConfig, rl_micro_batch_multiple +from prime_rl.configs.components.trainer import TrainerConfig +from prime_rl.configs.components.trainer.model import rl_micro_batch_multiple from prime_rl.trainer.model import iter_moe_blocks from prime_rl.trainer.optim import OptimizerLike from prime_rl.trainer.rl.data import TensorMicroBatch diff --git a/src/prime_rl/trainer/scheduler.py b/src/prime_rl/trainer/scheduler.py index c897ac7fe47..3d41416df77 100644 --- a/src/prime_rl/trainer/scheduler.py +++ b/src/prime_rl/trainer/scheduler.py @@ -6,7 +6,7 @@ from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR -from prime_rl.configs.trainer import SchedulerConfig +from prime_rl.configs.components.trainer.optim import SchedulerConfig from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike diff --git a/src/prime_rl/trainer/sft/data.py b/src/prime_rl/trainer/sft/data.py index 2ac13676756..c8ba15851a6 100644 --- a/src/prime_rl/trainer/sft/data.py +++ b/src/prime_rl/trainer/sft/data.py @@ -13,7 +13,7 @@ from torchdata.stateful_dataloader import StatefulDataLoader from transformers.tokenization_utils import PreTrainedTokenizer -from prime_rl.configs.sft import LossMaskConfig, SFTColumnsConfig, SFTDataConfig +from prime_rl.configs.components.trainer.data import LossMaskConfig, SFTColumnsConfig, SFTDataConfig from prime_rl.trainer.data import ( Sample, StatefulIterableDataset, diff --git a/src/prime_rl/trainer/sft/train.py b/src/prime_rl/trainer/sft/train.py index 883e15c904b..82132f4f0a8 100644 --- a/src/prime_rl/trainer/sft/train.py +++ b/src/prime_rl/trainer/sft/train.py @@ -1,4 +1,4 @@ -from prime_rl.configs.sft import SFTConfig +from prime_rl.configs.components.trainer.sft import SFTTrainerConfig from prime_rl.trainer.train import train from prime_rl.utils.config import cli from prime_rl.utils.process import set_proc_title @@ -6,7 +6,7 @@ def main(): set_proc_title("SFTTrainer") - train(cli(SFTConfig)) + train(cli(SFTTrainerConfig)) if __name__ == "__main__": diff --git a/src/prime_rl/trainer/train.py b/src/prime_rl/trainer/train.py index 3ab524e25da..f80d8d28db2 100644 --- a/src/prime_rl/trainer/train.py +++ b/src/prime_rl/trainer/train.py @@ -14,16 +14,16 @@ import torch from torch.profiler import profile, ProfilerActivity from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager, setup_model_files -from prime_rl.configs.shared import ckpt_output_dir +from prime_rl.configs.blocks.ckpt import ckpt_output_dir from prime_rl.utils.pathing import ( get_ckpt_dir, get_step_path, is_checkpoint_step_dir, resolve_latest_ckpt_step, ) -from prime_rl.configs.pretrain import PretrainConfig -from prime_rl.configs.sft import SFTConfig -from prime_rl.configs.trainer import CheckpointConfig +from prime_rl.configs.components.trainer.pretrain import PretrainTrainerConfig +from prime_rl.configs.components.trainer.sft import SFTTrainerConfig +from prime_rl.configs.components.trainer.ckpt import TrainerCheckpointConfig from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender from prime_rl.utils.cp import setup_context_parallel, setup_cp_params, shard_for_cp, validate_cp_seq_lens from prime_rl.trainer.lora import get_lora_state @@ -82,7 +82,7 @@ @clean_exit -def train(config: SFTConfig | PretrainConfig): +def train(config: SFTTrainerConfig | PretrainTrainerConfig): # Setup world and logger world = get_world() logger = setup_logger( @@ -203,7 +203,7 @@ def train(config: SFTConfig | PretrainConfig): logger.info(f"Initializing data ({config.data})") multimodal = config.model.vlm is not None dp_rank, dp_size = parallel_dims.data_parallel - if isinstance(config, PretrainConfig): + if isinstance(config, PretrainTrainerConfig): rows = dp_size * config.data.num_workers * config.data.micro_batch_size assert config.data.batch_size % rows == 0, ( f"batch_size ({config.data.batch_size}) must be divisible by data-parallel size x num_workers x " @@ -264,11 +264,11 @@ def setup_dataset() -> TokenDataset: dataloader = setup_dataloader(dataset, config.data, config.model.cp) val_raw_datasets = None - if config.val is not None and isinstance(config, SFTConfig): + if config.val is not None and isinstance(config, SFTTrainerConfig): logger.info(f"Loading validation dataset ({config.val.data})") val_raw_datasets = load_sft_dataset(config.val.data) validation = None - if config.val is not None and isinstance(config, PretrainConfig): + if config.val is not None and isinstance(config, PretrainTrainerConfig): validation = Validation(config.val, tokenizer, parallel_dims, config.run_dir) # Optionally, resume training from a checkpoint @@ -276,7 +276,7 @@ def setup_dataset() -> TokenDataset: if checkpoint_step is not None: resume_dir = config.resume.dir if config.resume else None - skip = config.ckpt or CheckpointConfig() + skip = config.ckpt or TrainerCheckpointConfig() ckpt_manager.load( checkpoint_step, model, diff --git a/src/prime_rl/trainer/utils.py b/src/prime_rl/trainer/utils.py index 73b27a2d479..02ac373df65 100644 --- a/src/prime_rl/trainer/utils.py +++ b/src/prime_rl/trainer/utils.py @@ -21,7 +21,7 @@ from torch.distributed.tensor import DTensor from transformers.tokenization_utils import PreTrainedTokenizer -from prime_rl.configs.trainer import ModelConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.control.controller import Controller from prime_rl.control.types import StepActionType from prime_rl.trainer.world import get_world @@ -262,7 +262,7 @@ def configure_cpu_optimizer_threads() -> None: ) -def setup_cpu_offload(config: ModelConfig) -> None: +def setup_cpu_offload(config: TrainerModelConfig) -> None: """NUMA-bind ranks that copy optimizer state, gradients or activations to host memory.""" if config.offload != "none" or config.ac_offloading is not None: bind_process_to_gpu_numa_node() diff --git a/src/prime_rl/trainer/val.py b/src/prime_rl/trainer/val.py index 7a6656afc1b..5f1f3d0938a 100644 --- a/src/prime_rl/trainer/val.py +++ b/src/prime_rl/trainer/val.py @@ -17,7 +17,7 @@ from torch import nn from transformers.tokenization_utils import PreTrainedTokenizer -from prime_rl.configs.supervised import DocumentsValSetConfig, ValConfig +from prime_rl.configs.components.trainer.data import DocumentsValSetConfig, ValConfig from prime_rl.trainer.model import forward from prime_rl.trainer.models.layers.fp32_linear import fp32_output_mm from prime_rl.trainer.models.layers.lm_head import IGNORE_INDEX diff --git a/src/prime_rl/trainer/vlm.py b/src/prime_rl/trainer/vlm.py index a51e0845d7e..5765e43babf 100644 --- a/src/prime_rl/trainer/vlm.py +++ b/src/prime_rl/trainer/vlm.py @@ -7,7 +7,7 @@ import torch.nn as nn from PIL import Image -from prime_rl.configs.trainer import ModelConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.utils.logger import get_logger @@ -32,7 +32,7 @@ def load_image(data_url: str) -> Image.Image: return image.convert("RGB") -def setup_processor(config: ModelConfig): +def setup_processor(config: TrainerModelConfig): """Load an ``AutoProcessor`` for VLM models. Returns ``None`` for text-only models.""" from transformers import AutoProcessor diff --git a/src/prime_rl/transports/batch/zmq.py b/src/prime_rl/transports/batch/zmq.py index fd8a6a4d493..45ed0d59230 100644 --- a/src/prime_rl/transports/batch/zmq.py +++ b/src/prime_rl/transports/batch/zmq.py @@ -8,7 +8,7 @@ import zmq import zmq.asyncio -from prime_rl.configs.shared import ZMQTransportConfig +from prime_rl.configs.blocks.transport import ZMQTransportConfig from prime_rl.transports.batch.log import BatchLog from prime_rl.transports.batch.types import StepBatch from prime_rl.utils.logger import get_logger diff --git a/src/prime_rl/transports/payload.py b/src/prime_rl/transports/payload.py index 98592f6eee3..eaac5fd27e6 100644 --- a/src/prime_rl/transports/payload.py +++ b/src/prime_rl/transports/payload.py @@ -53,7 +53,7 @@ import numpy as np import verifiers.v1 as vf -from prime_rl.configs.algorithm import ActionLossType +from prime_rl.configs.blocks.algorithm import ActionLossType from prime_rl.orchestrator.algo.base import iter_trainable_traces from prime_rl.orchestrator.algo.routing import stamp_loss_routing from prime_rl.orchestrator.trajectories import BranchSample, trace_to_samples diff --git a/src/prime_rl/transports/weights/__init__.py b/src/prime_rl/transports/weights/__init__.py index 527dbc71780..8c4e9bbb364 100644 --- a/src/prime_rl/transports/weights/__init__.py +++ b/src/prime_rl/transports/weights/__init__.py @@ -2,8 +2,8 @@ import torch -from prime_rl.configs.shared import WeightBroadcastConfig -from prime_rl.configs.trainer import LoRAConfig +from prime_rl.configs.blocks.weight_broadcast import WeightBroadcastConfig +from prime_rl.configs.components.trainer.model import LoRAConfig from prime_rl.orchestrator.clients import AdminPlane from prime_rl.transports.weights.base import ( WeightReceiver, diff --git a/src/prime_rl/transports/weights/base.py b/src/prime_rl/transports/weights/base.py index 74ddbbe93b8..0da9157b120 100644 --- a/src/prime_rl/transports/weights/base.py +++ b/src/prime_rl/transports/weights/base.py @@ -9,7 +9,7 @@ import torch.nn as nn -from prime_rl.configs.shared import WeightBroadcastConfig +from prime_rl.configs.blocks.weight_broadcast import WeightBroadcastConfig from prime_rl.orchestrator.clients import AdminPlane from prime_rl.trainer.world import get_world, wait_for_master from prime_rl.utils.logger import get_logger diff --git a/src/prime_rl/transports/weights/filesystem.py b/src/prime_rl/transports/weights/filesystem.py index 0ed2ea07ca0..a324a0d3ef4 100644 --- a/src/prime_rl/transports/weights/filesystem.py +++ b/src/prime_rl/transports/weights/filesystem.py @@ -5,8 +5,8 @@ import torch.nn as nn from torch.distributed.tensor import DTensor -from prime_rl.configs.shared import FileSystemWeightBroadcastConfig -from prime_rl.configs.trainer import LoRAConfig +from prime_rl.configs.blocks.weight_broadcast import FileSystemWeightBroadcastConfig +from prime_rl.configs.components.trainer.model import LoRAConfig from prime_rl.orchestrator.clients import load_lora_adapter from prime_rl.trainer.lora import get_lora_state, save_lora_config from prime_rl.transports.weights.base import ( diff --git a/src/prime_rl/transports/weights/modelexpress.py b/src/prime_rl/transports/weights/modelexpress.py index d9fe3bc9ebb..65e76e938c5 100644 --- a/src/prime_rl/transports/weights/modelexpress.py +++ b/src/prime_rl/transports/weights/modelexpress.py @@ -23,7 +23,7 @@ ) from torch import nn -from prime_rl.configs.shared import ModelExpressWeightBroadcastConfig +from prime_rl.configs.blocks.weight_broadcast import ModelExpressWeightBroadcastConfig from prime_rl.transports.weights.base import ( WeightReceiver, WeightSender, diff --git a/src/prime_rl/transports/weights/nccl.py b/src/prime_rl/transports/weights/nccl.py index 71cb84abe83..8eba0deae8f 100644 --- a/src/prime_rl/transports/weights/nccl.py +++ b/src/prime_rl/transports/weights/nccl.py @@ -9,7 +9,7 @@ from torch.distributed.tensor import DTensor, Replicate, Shard from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator -from prime_rl.configs.shared import NCCLWeightBroadcastConfig +from prime_rl.configs.blocks.weight_broadcast import NCCLWeightBroadcastConfig from prime_rl.trainer.models import PreTrainedModelPrimeRL from prime_rl.trainer.utils import get_world from prime_rl.trainer.vlm import get_layer_prefix diff --git a/src/prime_rl/utils/act_offloading.py b/src/prime_rl/utils/act_offloading.py index 0e618fdbea4..788e748d1fa 100644 --- a/src/prime_rl/utils/act_offloading.py +++ b/src/prime_rl/utils/act_offloading.py @@ -8,7 +8,7 @@ from torch.distributed.tensor import DTensor from torch.multiprocessing.reductions import StorageWeakRef -from prime_rl.configs.trainer import ActivationOffloadingConfig +from prime_rl.configs.components.trainer.model import ActivationOffloadingConfig from .logger import get_logger diff --git a/src/prime_rl/utils/cp.py b/src/prime_rl/utils/cp.py index f18076704df..f091c5eeeca 100644 --- a/src/prime_rl/utils/cp.py +++ b/src/prime_rl/utils/cp.py @@ -11,7 +11,7 @@ from prime_rl.utils.logger import get_logger if TYPE_CHECKING: - from prime_rl.configs.trainer import ModelConfig + from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.parallel_dims import ParallelDims @@ -28,7 +28,7 @@ def cp_enabled(self) -> bool: return self.cp_world_size > 1 -def setup_context_parallel(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims) -> None: +def setup_context_parallel(model: nn.Module, config: TrainerModelConfig, parallel_dims: ParallelDims) -> None: # The trainer leaves multimodal inputs unsharded; the VLM shards them after building their positions. if config.vlm is not None and not hasattr(model.model, "cp_context"): raise ValueError(f"{type(model).__name__} does not shard multimodal inputs for context parallelism; set cp=1") diff --git a/src/prime_rl/utils/heartbeat.py b/src/prime_rl/utils/heartbeat.py index 8ea32eb5afe..403b567018c 100644 --- a/src/prime_rl/utils/heartbeat.py +++ b/src/prime_rl/utils/heartbeat.py @@ -3,7 +3,7 @@ import requests -from prime_rl.configs.shared import HeartbeatConfig +from prime_rl.configs.blocks.run import HeartbeatConfig from prime_rl.utils.logger import get_logger diff --git a/src/prime_rl/utils/hf.py b/src/prime_rl/utils/hf.py index afe8b612681..c2c093df96a 100644 --- a/src/prime_rl/utils/hf.py +++ b/src/prime_rl/utils/hf.py @@ -5,8 +5,7 @@ from huggingface_hub import snapshot_download -from prime_rl.configs.sft import SFTDataConfig -from prime_rl.configs.supervised import BaseDataConfig +from prime_rl.configs.components.trainer.data import BaseDataConfig, SFTDataConfig from prime_rl.utils.logger import format_time, get_logger from prime_rl.utils.pathing import has_step_dir_name diff --git a/src/prime_rl/utils/pathing.py b/src/prime_rl/utils/pathing.py index de502897baa..8b23dfe26dc 100644 --- a/src/prime_rl/utils/pathing.py +++ b/src/prime_rl/utils/pathing.py @@ -11,10 +11,8 @@ from pydantic import BaseModel -from prime_rl.configs.env_worker_pool import env_worker_pool_config -from prime_rl.configs.orchestrator import EnvConfig -from prime_rl.configs.shared import LogConfig -from prime_rl.utils.config import BaseConfig, dump_resolved_config +from prime_rl.configs.base import BaseConfig +from prime_rl.utils.config import dump_resolved_config from prime_rl.utils.logger import get_logger @@ -240,29 +238,31 @@ def env_address_file(config_dir: Path, split: str, name: str, replica: int | Non return config_dir / "envs" / split / f"{stem}.address" -def write_env_worker_pool_config( - config_dir: Path, split: str, source: EnvConfig, log: LogConfig, output_dir: Path, store_dir: Path | None = None -) -> Path: - """Write the ``EnvWorkerPoolConfig`` of a launcher-managed source - (``envs//.json``) and return its path. The source's env and serve - blocks carry over; its other knobs (sampling, algo, name, ...) stay client-side. The - broker publishes the OS-assigned port it binds to the address file next to it. - ``output_dir`` is the run directory: the pool keeps checkpoint files only there. With - ``store_dir``, the pool keeps its training arrays in a rollout store under it.""" - env_dir = config_dir / "envs" / split - env_dir.mkdir(parents=True, exist_ok=True) - pool_config = env_worker_pool_config( - source, - log, - output_dir.absolute(), - address_file=env_address_file(config_dir, split, source.resolved_name), - store_dir=store_dir, - ) - path = env_dir / f"{source.resolved_name}.json" - path.write_text(json.dumps(pool_config, indent=2)) +def write_config(path: Path, config: BaseModel) -> Path: + """Write a resolved config as JSON.""" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(dump_resolved_config(config), indent=2)) return path +def write_component_configs(config_dir: Path, components: dict[str, BaseModel]) -> None: + """Write each component config to ``.json``.""" + for name, component in components.items(): + write_config(config_dir / f"{name}.json", component) + + +def env_worker_pool_command(config_dir: Path, split: str, name: str) -> list[str]: + """The command that starts the env worker pool of ``envs//.json`` in ``config_dir``. The pool + publishes the OS-assigned port it binds to the address file next to its config.""" + return [ + "env-worker-pool", + "@", + (config_dir / "envs" / split / f"{name}.json").as_posix(), + "--address-file", + env_address_file(config_dir, split, name).as_posix(), + ] + + def get_launcher_dir(output_dir: Path) -> Path: return output_dir / "launcher" diff --git a/tests/unit/control/test_app.py b/tests/unit/control/test_app.py index f2c85535579..71dc5b78b0d 100644 --- a/tests/unit/control/test_app.py +++ b/tests/unit/control/test_app.py @@ -3,7 +3,7 @@ import pytest from fastapi.testclient import TestClient -from prime_rl.configs.orchestrator import OrchestratorConfig +from prime_rl.configs.components.orchestrator import OrchestratorConfig from prime_rl.control.app import create_app from prime_rl.control.controller import Controller, validate_update from prime_rl.control.server import require_admin_token diff --git a/tests/unit/env/test_env_pool.py b/tests/unit/env/test_env_pool.py index 994b5b1e6ac..526797c18f8 100644 --- a/tests/unit/env/test_env_pool.py +++ b/tests/unit/env/test_env_pool.py @@ -56,7 +56,7 @@ async def test_broadcast_completes_when_a_worker_exits() -> None: import zmq - from prime_rl.configs.env_worker_pool import StaticPoolConfig + from prime_rl.configs.components.env_worker_pool import StaticPoolConfig from prime_rl.env.pool import EnvWorkerPool pool = EnvWorkerPool(StaticPoolConfig(num_workers=2), "tcp://127.0.0.1:0", {}, None, None) diff --git a/tests/unit/env/test_sample_server.py b/tests/unit/env/test_sample_server.py index 108965b23d5..8dd478c9ea7 100644 --- a/tests/unit/env/test_sample_server.py +++ b/tests/unit/env/test_sample_server.py @@ -11,8 +11,8 @@ import psutil import pytest -from prime_rl.configs.env_worker_pool import EnvWorkerPoolConfig, ScoringConfig -from prime_rl.entrypoints.env_worker_pool import bind_address, start_sample_server, stop_sample_server +from prime_rl.components.env_worker_pool import bind_address, start_sample_server, stop_sample_server +from prime_rl.configs.components.env_worker_pool import EnvWorkerPoolConfig, ScoringConfig from prime_rl.env.sample_server import SampleServer from prime_rl.env.types import SampleToScore from prime_rl.transports.batch.types import SampleBody @@ -86,7 +86,7 @@ def test_a_pool_whose_sample_server_crashes_exits_with_an_error(tmp_path): "--output-dir", str(tmp_path), ] - pool = subprocess.Popen([sys.executable, "-m", "prime_rl.entrypoints.env_worker_pool", *args]) + pool = subprocess.Popen([sys.executable, "-m", "prime_rl.components.env_worker_pool", *args]) try: deadline = time.monotonic() + 120 while not address_file.exists(): diff --git a/tests/unit/eval/test_control.py b/tests/unit/eval/test_control.py index 030c5d79a1b..e414ac1ec5d 100644 --- a/tests/unit/eval/test_control.py +++ b/tests/unit/eval/test_control.py @@ -1,7 +1,7 @@ import pytest from fastapi.testclient import TestClient -from prime_rl.configs.orchestrator import ConcurrencyConfig +from prime_rl.configs.components.orchestrator import ConcurrencyConfig from prime_rl.eval.control import create_app from prime_rl.orchestrator.concurrency import LOAD_WINDOW_POLLS, ConcurrencyController, EngineLoadSample diff --git a/tests/unit/eval/test_resume.py b/tests/unit/eval/test_resume.py index d6935750beb..8d3326c0597 100644 --- a/tests/unit/eval/test_resume.py +++ b/tests/unit/eval/test_resume.py @@ -7,7 +7,7 @@ from pydantic import ValidationError from verifiers.v1.utils.eval import plan_rollouts -from prime_rl.configs.eval import EvalConfig +from prime_rl.configs.entrypoints.eval import EvalConfig from prime_rl.eval import resume from prime_rl.monitors.file.traces import get_trace_stream from prime_rl.monitors.file.traces.chunks import ChunkedJsonl diff --git a/tests/unit/inference/test_dynamo.py b/tests/unit/inference/test_dynamo.py index b05541600c5..9cfa00b844c 100644 --- a/tests/unit/inference/test_dynamo.py +++ b/tests/unit/inference/test_dynamo.py @@ -4,7 +4,7 @@ import httpx import pytest -from prime_rl.configs.shared import PolicyClientConfig +from prime_rl.configs.blocks.client import PolicyClientConfig from prime_rl.inference.dynamo import ( DynamoAdminPlane, DynamoDiscoveryPending, diff --git a/tests/unit/inference/test_flashinfer_autotune_cache.py b/tests/unit/inference/test_flashinfer_autotune_cache.py index 7fd54974cc3..67aa0ec7643 100644 --- a/tests/unit/inference/test_flashinfer_autotune_cache.py +++ b/tests/unit/inference/test_flashinfer_autotune_cache.py @@ -4,7 +4,7 @@ from flashinfer.autotuner.autotuner import AutoTuner from vllm.model_executor.warmup import flashinfer_autotune_cache -from prime_rl.configs.inference import InferenceConfig +from prime_rl.configs.entrypoints.inference import InferenceConfig from prime_rl.entrypoints.inference import write_slurm_script from prime_rl.inference.patches import monkey_patch_flashinfer_autotune_cache_per_environment @@ -54,7 +54,7 @@ def test_autotune_files_are_kept_per_environment(tmp_path, monkeypatch): def test_slurm_inference_nodes_keep_autotune_files_per_node_on_shared_storage(tmp_path): config = InferenceConfig(slurm={}, output_dir=tmp_path) script_path = tmp_path / "inference.sbatch" - write_slurm_script(config, tmp_path / "inference.json", tmp_path / "logs", script_path) + write_slurm_script(config, tmp_path / "engine.json", tmp_path / "logs", script_path) [line] = [line for line in script_path.read_text().splitlines() if "VLLM_FLASHINFER_AUTOTUNE_CACHE_DIR=" in line] def cache_dir(env: dict[str, str]) -> str: diff --git a/tests/unit/inference/test_model_source.py b/tests/unit/inference/test_model_source.py index 64a29f949cc..a2023f6dd48 100644 --- a/tests/unit/inference/test_model_source.py +++ b/tests/unit/inference/test_model_source.py @@ -1,7 +1,7 @@ import pytest from transformers import Qwen3Config -from prime_rl.configs.inference import InferenceConfig +from prime_rl.configs.components.engine import EngineConfig from prime_rl.inference.server import setup_model_source @@ -14,15 +14,15 @@ def step_dir(tmp_path): def test_a_checkpoint_step_dir_starts_inference_from_placeholder_weights(step_dir): - config = InferenceConfig(vllm={"model": str(step_dir)}) + config = EngineConfig(vllm={"model": str(step_dir)}) setup_model_source(config) assert config.vllm.load_format == "dummy" - explicit = InferenceConfig(vllm={"model": str(step_dir), "load_format": "auto"}) + explicit = EngineConfig(vllm={"model": str(step_dir), "load_format": "auto"}) setup_model_source(explicit) assert explicit.vllm.load_format == "auto" - hf = InferenceConfig(vllm={"model": "Qwen/Qwen3-0.6B"}) + hf = EngineConfig(vllm={"model": "Qwen/Qwen3-0.6B"}) setup_model_source(hf) assert getattr(hf.vllm, "load_format", None) is None @@ -36,4 +36,4 @@ def test_a_checkpoint_step_dir_starts_inference_from_placeholder_weights(step_di ) def test_a_checkpoint_step_dir_rejects_what_needs_hf_weights(step_dir, vllm: dict, match: str): with pytest.raises(ValueError, match=match): - setup_model_source(InferenceConfig(vllm={"model": str(step_dir), **vllm})) + setup_model_source(EngineConfig(vllm={"model": str(step_dir), **vllm})) diff --git a/tests/unit/inference/test_nixl_bidirectional_scheduler.py b/tests/unit/inference/test_nixl_bidirectional_scheduler.py index 6cc4eb38d8c..9f4160318d3 100644 --- a/tests/unit/inference/test_nixl_bidirectional_scheduler.py +++ b/tests/unit/inference/test_nixl_bidirectional_scheduler.py @@ -22,7 +22,7 @@ from vllm.v1.request import Request, RequestStatus from vllm.v1.structured_output import StructuredOutputManager -from prime_rl.configs.inference import InferenceConfig +from prime_rl.configs.entrypoints.inference import InferenceConfig from prime_rl.inference.patches import monkey_patch_nixl_bidirectional_single_pull BLOCK_SIZE = 16 @@ -32,7 +32,7 @@ def _prefill_kv_transfer_config() -> dict: """The prefill engine's kv_transfer_config as prime-rl builds it for bidirectional P/D (NIXL only).""" config = InferenceConfig(deployment={"type": "disaggregated", "bidirectional_kv_transfer": {}}, slurm={}) - return config.for_pd_role("prefill").build_kv_transfer_config() + return config.engine_config(role="prefill").build_kv_transfer_config() def _scheduler(kv_transfer: dict) -> Scheduler: @@ -124,8 +124,8 @@ def single_pull_patch(monkeypatch): def test_prefill_role_recomputes_failed_loads(): config = InferenceConfig(deployment={"type": "disaggregated", "bidirectional_kv_transfer": {}}, slurm={}) - prefill = config.for_pd_role("prefill").build_kv_transfer_config() - decode = config.for_pd_role("decode").build_kv_transfer_config() + prefill = config.engine_config(role="prefill").build_kv_transfer_config() + decode = config.engine_config(role="decode").build_kv_transfer_config() assert prefill["kv_load_failure_policy"] == "recompute" assert "kv_load_failure_policy" not in decode # With a second connector the policy sits on the top-level MultiConnector, where the scheduler reads it. @@ -133,16 +133,16 @@ def test_prefill_role_recomputes_failed_loads(): config = InferenceConfig( deployment={"type": "disaggregated", "bidirectional_kv_transfer": {}}, slurm={}, kv_cache_offload=mooncake ) - prefill = config.for_pd_role("prefill").build_kv_transfer_config() + prefill = config.engine_config(role="prefill").build_kv_transfer_config() assert prefill["kv_connector"] == "MultiConnector" and prefill["kv_load_failure_policy"] == "recompute" assert KVTransferConfig(**prefill).kv_load_failure_policy == "recompute" # An explicit setting wins, and one-way P/D keeps vLLM's default. config = InferenceConfig( deployment={"type": "disaggregated", "bidirectional_kv_transfer": {}}, slurm={}, kv_load_failure_policy="fail" ) - assert config.for_pd_role("prefill").build_kv_transfer_config()["kv_load_failure_policy"] == "fail" + assert config.engine_config(role="prefill").build_kv_transfer_config()["kv_load_failure_policy"] == "fail" config = InferenceConfig(deployment={"type": "disaggregated"}, slurm={}) - assert "kv_load_failure_policy" not in config.for_pd_role("prefill").build_kv_transfer_config() + assert "kv_load_failure_policy" not in config.engine_config(role="prefill").build_kv_transfer_config() def test_declined_decode_read_prefills_locally(single_pull_patch): diff --git a/tests/unit/monitors/test_annotation_format.py b/tests/unit/monitors/test_annotation_format.py index 3d5fa498d0e..7631121d273 100644 --- a/tests/unit/monitors/test_annotation_format.py +++ b/tests/unit/monitors/test_annotation_format.py @@ -9,7 +9,7 @@ import numpy as np import orjson -from prime_rl.configs.monitors import FileMonitorConfig +from prime_rl.configs.blocks.monitors import FileMonitorConfig from prime_rl.dashboard.server import trace_updates from prime_rl.monitors.file.monitor import FileMonitor from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path diff --git a/tests/unit/monitors/test_file_monitor_write_options.py b/tests/unit/monitors/test_file_monitor_write_options.py index 22e533c98c6..497991ee80b 100644 --- a/tests/unit/monitors/test_file_monitor_write_options.py +++ b/tests/unit/monitors/test_file_monitor_write_options.py @@ -9,7 +9,7 @@ import orjson import pytest -from prime_rl.configs.monitors import FileMonitorConfig +from prime_rl.configs.blocks.monitors import FileMonitorConfig from prime_rl.env.heads import EpisodeHead, recorded_head from prime_rl.monitors.file.monitor import FileMonitor, in_trace_sample from prime_rl.monitors.file.traces import get_annotations_dir, get_trace_stream diff --git a/tests/unit/monitors/test_monitor_load.py b/tests/unit/monitors/test_monitor_load.py index d14398bdda6..85d658fc09b 100644 --- a/tests/unit/monitors/test_monitor_load.py +++ b/tests/unit/monitors/test_monitor_load.py @@ -25,7 +25,7 @@ from verifiers.v1.types import AssistantMessage, Usage, UserMessage from prime_rl import monitors -from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig, WandbMonitorConfig +from prime_rl.configs.blocks.monitors import FileMonitorConfig, PrimeMonitorConfig, WandbMonitorConfig from prime_rl.env.heads import EpisodeHead, EpisodeRecord, recorded_head from prime_rl.monitors.file.monitor import FileMonitor from prime_rl.monitors.file.traces import get_trace_stream diff --git a/tests/unit/orchestrator/test_advantage.py b/tests/unit/orchestrator/test_advantage.py index 330d953909c..30c3ec443b3 100644 --- a/tests/unit/orchestrator/test_advantage.py +++ b/tests/unit/orchestrator/test_advantage.py @@ -4,16 +4,18 @@ import pytest import verifiers.v1 as vf -from prime_rl.configs.algorithm import ( - CostLengthPenaltyConfig, +from prime_rl.configs.blocks.algorithm import ( DebugAlgoConfig, GRPOAlgoConfig, HierarchicalGRPOAlgoConfig, - LinearLengthPenaltyConfig, - LinearSubagentLengthPenaltyConfig, MaxRLAlgoConfig, RAEAlgoConfig, ) +from prime_rl.configs.blocks.length_penalty import ( + CostLengthPenaltyConfig, + LinearLengthPenaltyConfig, + LinearSubagentLengthPenaltyConfig, +) from prime_rl.env.heads import EpisodeHead, episode_head from prime_rl.orchestrator.algo import DebugAlgorithm, HierarchicalGRPOAlgorithm, RAEAlgorithm from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm, length_penalty_tokens diff --git a/tests/unit/orchestrator/test_algorithms.py b/tests/unit/orchestrator/test_algorithms.py index a374dca4ee1..ceef4e7cb89 100644 --- a/tests/unit/orchestrator/test_algorithms.py +++ b/tests/unit/orchestrator/test_algorithms.py @@ -7,7 +7,7 @@ from verifiers.v1.graph import MessageNode from verifiers.v1.types import AssistantMessage, ToolMessage, UserMessage -from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig +from prime_rl.configs.blocks.algorithm import AlgoConfig, FrozenModelConfig from prime_rl.orchestrator.algo import ( EchoAlgorithm, assign_advantage, diff --git a/tests/unit/orchestrator/test_clients.py b/tests/unit/orchestrator/test_clients.py index 8fff664f849..e5a43f622c0 100644 --- a/tests/unit/orchestrator/test_clients.py +++ b/tests/unit/orchestrator/test_clients.py @@ -6,7 +6,7 @@ import pytest from verifiers.v1.configs.client import EvalClientConfig -from prime_rl.configs.shared import ADMIN_TOKEN_HEADER, ClientConfig, VLLMClientConfig +from prime_rl.configs.blocks.client import ADMIN_TOKEN_HEADER, ClientConfig, VLLMClientConfig from prime_rl.orchestrator.clients import ( AdminPlane, _is_retryable_lora_error, diff --git a/tests/unit/orchestrator/test_concurrency.py b/tests/unit/orchestrator/test_concurrency.py index f61fd121a42..916682e8608 100644 --- a/tests/unit/orchestrator/test_concurrency.py +++ b/tests/unit/orchestrator/test_concurrency.py @@ -3,7 +3,7 @@ import pytest -from prime_rl.configs.orchestrator import ConcurrencyConfig +from prime_rl.configs.components.orchestrator import ConcurrencyConfig from prime_rl.orchestrator import concurrency from prime_rl.orchestrator.concurrency import ( DWELL_SECONDS, diff --git a/tests/unit/orchestrator/test_config_update.py b/tests/unit/orchestrator/test_config_update.py index 000cbccde14..8b5d8fcfc6a 100644 --- a/tests/unit/orchestrator/test_config_update.py +++ b/tests/unit/orchestrator/test_config_update.py @@ -2,9 +2,9 @@ import pytest -from prime_rl.configs.diff import merge_resumed_config -from prime_rl.configs.orchestrator import CheckpointConfig, ConcurrencyConfig, OrchestratorConfig -from prime_rl.configs.rl import RLConfig +from prime_rl.configs.components.orchestrator import ConcurrencyConfig, OrchestratorConfig +from prime_rl.configs.components.orchestrator.ckpt import OrchestratorCheckpointConfig +from prime_rl.configs.entrypoints.rl import RLConfig from prime_rl.control.controller import validate_update from prime_rl.control.types import ConfigUpdate, InvalidConfigError from prime_rl.orchestrator.ckpt import CheckpointManager @@ -12,6 +12,7 @@ from prime_rl.orchestrator.eval_source import EvalSource from prime_rl.orchestrator.types import Progress from prime_rl.utils.config import cli, dump_resolved_config +from prime_rl.utils.diff import merge_resumed_config @pytest.fixture @@ -109,7 +110,7 @@ def test_example_config_frozen_change_that_fails_validation_is_reported_frozen(e def test_checkpoint_keeps_config_state(tmp_path): - manager = CheckpointManager(tmp_path, CheckpointConfig()) + manager = CheckpointManager(tmp_path, OrchestratorCheckpointConfig()) config_state = {"base": {"batch_size": 64}, "applied": {"batch_size": 128}, "revision": 2} train_source = SimpleNamespace(state_dict=lambda: {"rng": None, "envs": {}}) diff --git a/tests/unit/orchestrator/test_curriculum.py b/tests/unit/orchestrator/test_curriculum.py index 6c703cb0f2c..1ef045de5da 100644 --- a/tests/unit/orchestrator/test_curriculum.py +++ b/tests/unit/orchestrator/test_curriculum.py @@ -7,7 +7,7 @@ import pytest import verifiers.v1 as vf -from prime_rl.configs.orchestrator import ( +from prime_rl.configs.components.orchestrator.curriculum import ( AdvRangeGateConfig, CurriculumConfig, DifficultyPoolConfig, diff --git a/tests/unit/orchestrator/test_env_addresses.py b/tests/unit/orchestrator/test_env_addresses.py index fdf9cb8c4cf..5f03354dcc3 100644 --- a/tests/unit/orchestrator/test_env_addresses.py +++ b/tests/unit/orchestrator/test_env_addresses.py @@ -18,7 +18,9 @@ def test_without_peer_addresses_the_sources_keep_their_own(monkeypatch): def test_peer_addresses_fill_only_the_sources_without_one(monkeypatch): monkeypatch.setenv( "PRL_ENV_ADDRESSES", - json.dumps({"train/reverse-text": "tcp://run-env-0-headless:5000", "train/remote": "tcp://elsewhere:5000"}), + json.dumps( + {"envs/train/reverse-text": "tcp://run-env-0-headless:5000", "envs/train/remote": "tcp://elsewhere:5000"} + ), ) assert with_peer_addresses(ADDRESSES) == { @@ -29,7 +31,7 @@ def test_peer_addresses_fill_only_the_sources_without_one(monkeypatch): def test_a_peer_address_for_no_source_is_refused(monkeypatch): - monkeypatch.setenv("PRL_ENV_ADDRESSES", json.dumps({"train/typo": "tcp://x:5000"})) + monkeypatch.setenv("PRL_ENV_ADDRESSES", json.dumps({"envs/train/typo": "tcp://x:5000"})) - with pytest.raises(ValueError, match="train/typo"): + with pytest.raises(ValueError, match="envs/train/typo"): with_peer_addresses(ADDRESSES) diff --git a/tests/unit/orchestrator/test_episode_records.py b/tests/unit/orchestrator/test_episode_records.py index b6769c61140..cc278a73e68 100644 --- a/tests/unit/orchestrator/test_episode_records.py +++ b/tests/unit/orchestrator/test_episode_records.py @@ -12,7 +12,7 @@ from verifiers.v1.delta import DeltaStreamer from prime_rl import monitors -from prime_rl.configs.monitors import FileMonitorConfig +from prime_rl.configs.blocks.monitors import FileMonitorConfig from prime_rl.env.encoding import pack, unpack from prime_rl.env.heads import EpisodeHead, recorded_head from prime_rl.env.worker import stamp_dispatch diff --git a/tests/unit/orchestrator/test_rollout_ckpt.py b/tests/unit/orchestrator/test_rollout_ckpt.py index 55e36b2face..3cbbb64e4b9 100644 --- a/tests/unit/orchestrator/test_rollout_ckpt.py +++ b/tests/unit/orchestrator/test_rollout_ckpt.py @@ -13,8 +13,10 @@ import pytest import verifiers.v1 as vf -from prime_rl.configs.algorithm import GRPOAlgoConfig -from prime_rl.configs.orchestrator import CheckpointConfig, CurriculumConfig, OrchestratorConfig +from prime_rl.configs.blocks.algorithm import GRPOAlgoConfig +from prime_rl.configs.components.orchestrator import OrchestratorConfig +from prime_rl.configs.components.orchestrator.ckpt import OrchestratorCheckpointConfig +from prime_rl.configs.components.orchestrator.curriculum import CurriculumConfig from prime_rl.env.heads import EpisodeHead, recorded_head from prime_rl.env.types import RestoreRef from prime_rl.orchestrator import orchestrator as orchestrator_module @@ -652,7 +654,7 @@ def test_a_checkpoint_with_rollouts_continues_its_open_groups_instead_of_rerunni work = open_work(episodes=episodes, open_groups=dict(source.open_groups)) def checkpoint(output_dir, rollouts: bool) -> CheckpointManager: - manager = CheckpointManager(output_dir, CheckpointConfig(rollouts=rollouts)) + manager = CheckpointManager(output_dir, OrchestratorCheckpointConfig(rollouts=rollouts)) ckpt_path = manager.get_ckpt_path(6) (ckpt_path / "rollouts" / ARRAYS_DIR).mkdir(parents=True) (ckpt_path / "rollouts" / ARRAYS_DIR / "blob").write_bytes(b"arrays") @@ -678,7 +680,7 @@ def checkpoint(output_dir, rollouts: bool) -> CheckpointManager: assert (manager.ckpt_dir / RESUMED_DIR / "t1.restore").read_bytes() == b"point" # A fork of the checkpoint leaves the snapshots to the run that took them. - fork = CheckpointManager(tmp_path / "fork", CheckpointConfig(rollouts=True)) + fork = CheckpointManager(tmp_path / "fork", OrchestratorCheckpointConfig(rollouts=True)) source_path = checkpoint(tmp_path / "other", rollouts=True).get_ckpt_path(6) forked = fork.load(Progress(), TrainSource([train_env("a")]), step=6, path=source_path) assert owned_snapshots(forked) == [] @@ -696,7 +698,7 @@ async def run(): s = sink(group_size={"open": 2}.get) await s.add(episode([trace()], group="open")) source = TrainSource([train_env("a")]) - manager = CheckpointManager(tmp_path, CheckpointConfig(rollouts=True)) + manager = CheckpointManager(tmp_path, OrchestratorCheckpointConfig(rollouts=True)) work = open_work(sink=s.state_dict()) state = build_state(Progress(step=7), source, {}) pid = manager.fork_writer(state, work, step=6, freeze=False) diff --git a/tests/unit/orchestrator/test_train_sink.py b/tests/unit/orchestrator/test_train_sink.py index 1997d25fe0a..d8ffa4ec91f 100644 --- a/tests/unit/orchestrator/test_train_sink.py +++ b/tests/unit/orchestrator/test_train_sink.py @@ -10,8 +10,8 @@ from verifiers.v1.trace import ModelCall from verifiers.v1.types import AssistantMessage, Tool, ToolMessage, Usage, UserMessage, WeightVersionSpan -from prime_rl.configs.algorithm import GRPOAlgoConfig -from prime_rl.configs.orchestrator import OrchestratorConfig +from prime_rl.configs.blocks.algorithm import GRPOAlgoConfig +from prime_rl.configs.components.orchestrator import OrchestratorConfig from prime_rl.control.types import ConfigUpdate from prime_rl.env.heads import EpisodeHead, TraceHead, episode_head from prime_rl.orchestrator.algo.base import Algorithm diff --git a/tests/unit/orchestrator/test_train_sink_payloads.py b/tests/unit/orchestrator/test_train_sink_payloads.py index 816944a7dcf..a05cc95120b 100644 --- a/tests/unit/orchestrator/test_train_sink_payloads.py +++ b/tests/unit/orchestrator/test_train_sink_payloads.py @@ -8,8 +8,8 @@ import numpy as np import verifiers.v1 as vf -from prime_rl.configs.algorithm import GRPOAlgoConfig -from prime_rl.configs.orchestrator import OrchestratorConfig +from prime_rl.configs.blocks.algorithm import GRPOAlgoConfig +from prime_rl.configs.components.orchestrator import OrchestratorConfig from prime_rl.orchestrator.algo.base import Algorithm from prime_rl.orchestrator.dispatcher import Dispatcher from prime_rl.orchestrator.train_sink import TrainSink diff --git a/tests/unit/test_config_diff.py b/tests/unit/test_config_diff.py index 74ed2735ede..90cbf6ed5b9 100644 --- a/tests/unit/test_config_diff.py +++ b/tests/unit/test_config_diff.py @@ -3,9 +3,9 @@ import pytest from pydantic import BaseModel -from prime_rl.configs.diff import Frozen, Live, diff_config, frozen_raw_changes, merge_resumed_config -from prime_rl.configs.orchestrator import OrchestratorConfig -from prime_rl.configs.shared import ResumeConfig +from prime_rl.configs.blocks.ckpt import ResumeConfig +from prime_rl.configs.components.orchestrator import OrchestratorConfig +from prime_rl.utils.diff import Frozen, Live, diff_config, frozen_raw_changes, merge_resumed_config class Leaf(BaseModel): diff --git a/tests/unit/test_configs.py b/tests/unit/test_configs.py index 78fcddab409..bb55b52b26a 100644 --- a/tests/unit/test_configs.py +++ b/tests/unit/test_configs.py @@ -1,7 +1,10 @@ +import ast +import copy import importlib import json import re import sys +import tomllib from pathlib import Path from typing import Annotated, Literal, get_args @@ -12,32 +15,36 @@ from pydantic_config import ConfigFileError from renderers import custom_renderer_config -from prime_rl.configs.algorithm import ( +from prime_rl.configs.base import BaseConfig, ComponentConfig, EntrypointConfig +from prime_rl.configs.blocks.algorithm import GRPOAlgoConfig +from prime_rl.configs.blocks.length_penalty import ( CostLengthPenaltyConfig, - GRPOAlgoConfig, LinearLengthPenaltyConfig, LinearSubagentLengthPenaltyConfig, ) -from prime_rl.configs.env_worker_pool import EnvWorkerPoolConfig -from prime_rl.configs.eval import EvalConfig, SFTOnlineEvalConfig -from prime_rl.configs.inference import InferenceConfig -from prime_rl.configs.orchestrator import ( +from prime_rl.configs.components.engine import EngineConfig, EngineSection +from prime_rl.configs.components.env_worker_pool import EnvWorkerPoolConfig +from prime_rl.configs.components.online_eval import SFTOnlineEvalConfig +from prime_rl.configs.components.orchestrator import OrchestratorConfig, OrchestratorModelConfig, OrchestratorSection +from prime_rl.configs.components.orchestrator.sources import ( EvalSourcesConfig, - OrchestratorConfig, RLOnlineEvalConfig, ScheduledEvalConfig, TrainConfig, TrainSourceConfig, ) -from prime_rl.configs.orchestrator import ( - ModelConfig as OrchestratorModelConfig, -) -from prime_rl.configs.pretrain import PretrainConfig, PretrainDataConfig -from prime_rl.configs.rl import RLConfig -from prime_rl.configs.sft import SFTConfig, SFTDataConfig -from prime_rl.configs.trainer import ModelConfig as TrainerModelConfig -from prime_rl.configs.trainer import TrainerConfig -from prime_rl.utils.config import MODES, BaseConfig, check_mode, cli, dump_resolved_config +from prime_rl.configs.components.router import RouterConfig +from prime_rl.configs.components.trainer import TrainerConfig, TrainerSection +from prime_rl.configs.components.trainer.data import PretrainDataConfig, SFTDataConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig +from prime_rl.configs.components.trainer.pretrain import PretrainTrainerConfig, PretrainTrainerSection +from prime_rl.configs.components.trainer.sft import SFTTrainerConfig, SFTTrainerSection +from prime_rl.configs.entrypoints.eval import EvalConfig +from prime_rl.configs.entrypoints.inference import InferenceConfig, InferenceSection, ServingSection +from prime_rl.configs.entrypoints.pretrain import PretrainConfig +from prime_rl.configs.entrypoints.rl import RLConfig +from prime_rl.configs.entrypoints.sft import SFTConfig +from prime_rl.utils.config import MODES, check_mode, cli, dump_resolved_config # All config config classes CONFIG_CLASSES = [ @@ -46,6 +53,7 @@ SFTConfig, PretrainConfig, OrchestratorConfig, + OrchestratorSection, InferenceConfig, EnvWorkerPoolConfig, EvalConfig, @@ -63,7 +71,7 @@ def get_config_files() -> list[Path]: return [path for root in roots for path in root.rglob("*.toml")] -ENTRYPOINT_CONFIGS = { +SCRIPT_CONFIGS = { "rl": RLConfig, "trainer": TrainerConfig, "sft": SFTConfig, @@ -72,6 +80,8 @@ def get_config_files() -> list[Path]: "inference": InferenceConfig, "env-worker-pool": EnvWorkerPoolConfig, "eval": EvalConfig, + "router": RouterConfig, + "engine": EngineConfig, } # A launch command in a config's comments, e.g. `# uv run rl @ base.toml @ overlay.toml --max-steps 5`. @@ -125,11 +135,111 @@ def test_load_configs(config_file: Path): ) def test_launch_commands(entrypoint: str, stack: list[Path]): """Tests that each launch command documented in a config file parses with its entrypoint's config class.""" - assert entrypoint in ENTRYPOINT_CONFIGS, f"Unknown entrypoint `{entrypoint}`" + assert entrypoint in SCRIPT_CONFIGS, f"Unknown entrypoint `{entrypoint}`" missing = [path for path in stack if not path.is_file()] assert not missing, f"Launch command references missing files: {missing}" args = [arg for path in stack for arg in ("@", path.as_posix())] - cli(ENTRYPOINT_CONFIGS[entrypoint], args=args) + cli(SCRIPT_CONFIGS[entrypoint], args=args) + + +CONFIGS_DIR = Path("packages/prime-rl-configs/src/prime_rl/configs") +MAX_MODULE_LINES = 450 +# RLConfig alone wires every rl component and spans most of this module. +LONG_MODULES = {"entrypoints/rl.py"} +# A layer may import only the layers listed for it. +LAYER_IMPORTS = { + "base": (), + "blocks": ("blocks",), + "components": ("blocks", "components"), + "entrypoints": ("blocks", "components", "entrypoints"), +} + + +def configs_modules() -> dict[str, Path]: + """Module name of every file in prime_rl.configs, keyed to its path.""" + return { + ".".join(("prime_rl", "configs", *path.relative_to(CONFIGS_DIR).with_suffix("").parts)).removesuffix( + ".__init__" + ): path + for path in sorted(CONFIGS_DIR.rglob("*.py")) + } + + +def test_config_layout(): + """Each public script parses an entrypoint config and each component script a component config, each kept in + its own package.""" + scripts = tomllib.loads(Path("pyproject.toml").read_text())["project"]["scripts"] + assert scripts.keys() - SCRIPT_CONFIGS.keys() == {"launch", "dashboard"} + for script, config_cls in SCRIPT_CONFIGS.items(): + module = scripts[script].split(":")[0] + kind = "entrypoints" if issubclass(config_cls, EntrypointConfig) else "components" + assert issubclass(config_cls, (EntrypointConfig, ComponentConfig)), f"{config_cls.__name__} has no marker" + assert module.startswith(f"prime_rl.{kind}."), f"`{script}` runs {module}, not from prime_rl.{kind}" + assert config_cls.__module__.startswith(f"prime_rl.configs.{kind}."), config_cls.__module__ + source = Path("src", *module.split(".")).with_suffix(".py").read_text() + assert f"cli({config_cls.__name__})" in source, f"`{script}` does not parse {config_cls.__name__}" + + +def undocumented(cls: ast.ClassDef) -> list[str]: + """The class (as ````) and the fields of ``cls`` that have no docstring. A ``type: Literal[...]`` + discriminator needs none: the class docstring describes the variant.""" + missing = [] if ast.get_docstring(cls) else [""] + for statement, following in zip(cls.body, [*cls.body[1:], None]): + if not isinstance(statement, ast.AnnAssign) or not isinstance(statement.target, ast.Name): + continue + name, annotation = statement.target.id, ast.unparse(statement.annotation) + if name.startswith("_") or name == "model_config" or annotation.startswith("ClassVar"): + continue + if name == "type" and annotation.startswith("Literal"): + continue + documented = isinstance(following, ast.Expr) and isinstance(following.value, ast.Constant) + if not (documented and isinstance(following.value.value, str)): + missing.append(name) + return missing + + +def test_config_package_follows_its_rules(): + """Enforce the rules in packages/prime-rl-configs/README.md#package-layout.""" + owners: dict[str, str] = {} + components_per_entry: dict[str, list[str]] = {} + for name, path in configs_modules().items(): + relative = path.relative_to(CONFIGS_DIR) + layer = relative.parts[0].removesuffix(".py") + if layer == "__init__": + continue + assert layer in LAYER_IMPORTS, f"{relative} is outside base, blocks, components and entrypoints" + + source = path.read_text() + lines = source.count("\n") + assert lines <= MAX_MODULE_LINES or relative.as_posix() in LONG_MODULES, ( + f"{relative} has {lines} lines; split it along its TOML sub-tables" + ) + allowed = tuple(f"prime_rl.configs.{target}" for target in LAYER_IMPORTS[layer]) + tree = ast.parse(source) + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and (node.module or "").startswith("prime_rl.configs."): + assert node.module.startswith(allowed) or node.module == "prime_rl.configs.base", ( + f"{relative} ({layer}) imports {node.module}" + ) + + module = importlib.import_module(name) + classes = {cls for cls in vars(module).values() if isinstance(cls, type) and cls.__module__ == name} + config_names = {cls.__name__ for cls in classes if issubclass(cls, BaseModel)} + for node in ast.walk(tree): + if isinstance(node, ast.ClassDef) and node.name in config_names: + assert undocumented(node) == [], f"{relative}: {node.name} lacks docstrings for {undocumented(node)}" + for cls in classes: + assert cls.__name__ not in owners, f"{cls.__name__} is defined in {owners[cls.__name__]} and {name}" + owners[cls.__name__] = name + component_configs = [cls.__name__ for cls in classes if issubclass(cls, ComponentConfig)] + if layer == "components": + assert len(component_configs) <= 1, f"{relative} defines {component_configs}" + components_per_entry.setdefault(relative.parts[1].removesuffix(".py"), []).extend(component_configs) + elif layer != "base": + assert not component_configs, f"{relative} defines {component_configs} outside components/" + del components_per_entry["__init__"] + empty = sorted(entry for entry, component_configs in components_per_entry.items() if not component_configs) + assert not empty, f"components/ entries without a component config: {empty}" class NestedConfig(BaseConfig): @@ -178,7 +288,7 @@ def test_defaults(): def test_rl_launcher_config_roundtrip(tmp_path): - from prime_rl.entrypoints.rl import write_config + from prime_rl.utils.pathing import write_config config = cli( RLConfig, @@ -196,10 +306,10 @@ def test_rl_launcher_config_roundtrip(tmp_path): "4", ], ) - write_config(config, tmp_path, exclude={"slurm", "dry_run", "clean"}) + write_config(tmp_path / "rl.json", config) reloaded = cli(RLConfig, args=["@", str(tmp_path / "rl.json")]) assert reloaded.run_dir == config.run_dir - assert reloaded.trainer.weight_broadcast == config.trainer.weight_broadcast + assert reloaded.trainer_config().weight_broadcast == config.trainer_config().weight_broadcast assert reloaded.orchestrator.train.source[0].sampling.logprobs == 4 assert reloaded.inference.enable_return_sampling_mask assert reloaded.orchestrator.train.source[0].sampling.top_k is None @@ -208,7 +318,7 @@ def test_rl_launcher_config_roundtrip(tmp_path): def test_pretrain_config_roundtrip(tmp_path): """A minimal pretrain TOML gets the pretraining defaults and survives the launcher's resolved config, which `uv run sft` rejects.""" - from prime_rl.entrypoints.launcher import write_config + from prime_rl.utils.pathing import write_config write_toml(tmp_path / "pretrain.toml", {"data": {"source": [{"name": "web", "path": str(tmp_path / "tokens")}]}}) config = cli(PretrainConfig, args=["@", str(tmp_path / "pretrain.toml"), "--output-dir", str(tmp_path)]) @@ -216,7 +326,7 @@ def test_pretrain_config_roundtrip(tmp_path): assert (config.optim.type, config.optim.lr, config.optim.weight_decay) == ("adamw", 1e-3, 0.01) assert (config.scheduler.type, config.scheduler.warmup_steps, config.scheduler.decay_steps) == ("linear", 10, 0) - write_config(config, tmp_path / "pretrain.json") + write_config(tmp_path / "pretrain.json", config) assert cli(PretrainConfig, args=["@", str(tmp_path / "pretrain.json")]) == config assert not can_parse(SFTConfig, ["@", str(tmp_path / "pretrain.json")]) @@ -955,8 +1065,8 @@ def test_single_node_auto_inference_ports_follow_server_port(): assert config.inference is not None assert config.inference.vllm.data_parallel_size == 2 - assert config.trainer.weight_broadcast.inference_world_size == 2 - assert config.orchestrator.weight_broadcast.inference_world_size == 2 + assert config.trainer_config().weight_broadcast.inference_world_size == 2 + assert config.orchestrator_config().weight_broadcast.inference_world_size == 2 assert config.inference.backend_port == 8101 assert config.orchestrator.model.client.admin_base_url == ["http://localhost:8101/v1"] @@ -1014,8 +1124,6 @@ def test_sft_launcher_gives_the_admin_token_to_online_evals_and_its_digest_to_ch @pytest.mark.parametrize("transport", ["nccl", "modelexpress"]) def test_sft_online_evals_size_the_in_memory_transfer_group(transport): - from prime_rl.entrypoints.launcher import build_online_eval_config - config = SFTConfig.model_validate( { "weight_broadcast": {"type": transport}, @@ -1025,9 +1133,9 @@ def test_sft_online_evals_size_the_in_memory_transfer_group(transport): } ) - assert config.weight_broadcast.inference_world_size == 2 - assert config.inference.weight_broadcast.type == transport - assert build_online_eval_config(config).weight_broadcast == config.weight_broadcast + assert config.trainer_config().weight_broadcast.inference_world_size == 2 + assert config.engine_configs()["engine"].weight_broadcast.type == transport + assert config.online_eval_config().weight_broadcast == config.trainer_config().weight_broadcast config = SFTConfig.model_validate( { @@ -1040,7 +1148,23 @@ def test_sft_online_evals_size_the_in_memory_transfer_group(transport): } ) - assert config.weight_broadcast.inference_world_size == 16 + assert config.trainer_config().weight_broadcast.inference_world_size == 16 + assert config.online_eval_config().weight_broadcast.inference_world_size == 16 + + +@pytest.mark.parametrize( + "weight_broadcast", + [ + {"type": "nccl", "host": "trainer"}, + {"type": "nccl", "inference_world_size": 2}, + {"type": "modelexpress", "inference_world_size": 2}, + ], +) +def test_weight_broadcast_section_rejects_the_fields_the_launcher_fills(weight_broadcast): + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + rl_config(weight_broadcast=weight_broadcast) + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + SFTConfig.model_validate({"weight_broadcast": weight_broadcast, "eval": SFT_ONLINE_EVAL, "inference": {}}) @pytest.mark.parametrize("launch", [True, False]) @@ -1083,32 +1207,12 @@ def test_single_node_nccl_resolved_json_roundtrips(tmp_path): } ) path = tmp_path / "rl.json" - path.write_text(json.dumps(dump_resolved_config(config, exclude={"slurm", "dry_run", "clean"}))) + path.write_text(json.dumps(dump_resolved_config(config))) reloaded = cli(RLConfig, args=["@", str(path)]) - assert reloaded.trainer.weight_broadcast.inference_world_size == 2 + assert reloaded.trainer_config().weight_broadcast.inference_world_size == 2 assert reloaded == config -@pytest.mark.parametrize( - "overrides, match", - [ - ({"orchestrator": {"weight_broadcast": {"type": "filesystem"}}}, "orchestrator.weight_broadcast"), - ({"trainer": {"weight_broadcast": {"type": "nccl", "timeout": 60}}}, "trainer.weight_broadcast"), - ], -) -def test_rl_rejects_conflicting_launcher_owned_fields(overrides, match): - data = { - "trainer": {}, - "orchestrator": {}, - "inference": {"vllm": {"tensor_parallel_size": 1}}, - "deployment": {"type": "single_node", "gpus_per_node": 4, "num_train_gpus": 2, "num_infer_gpus": 2}, - } - for key, value in overrides.items(): - data[key] = value - with pytest.raises(ValidationError, match=match): - RLConfig.model_validate(data) - - def test_rl_nccl_broadcast_needs_two_gpus(): with pytest.raises(ValidationError, match="at least 2 GPUs"): RLConfig.model_validate( @@ -1172,8 +1276,8 @@ def test_modelexpress_under_pd_transfers_to_every_prefill_and_decode_gpu(): } ) - assert config.trainer.weight_broadcast.inference_world_size == 16 - assert config.orchestrator.weight_broadcast.inference_world_size == 16 + assert config.trainer_config().weight_broadcast.inference_world_size == 16 + assert config.orchestrator_config().weight_broadcast.inference_world_size == 16 assert config.orchestrator.inference_metrics_roles == ["prefill"] * 8 + ["decode"] * 8 @@ -1324,16 +1428,34 @@ def test_shared_and_sub_model_name_conflict_raises(): ) -def test_shared_and_sub_max_steps_conflict_raises(): - """Top-level scalar shared fields also participate in the mutex check.""" - with pytest.raises(ValidationError, match=r"max_steps.*orchestrator.max_steps"): - RLConfig.model_validate( - { - "max_steps": 100, - "trainer": {}, - "orchestrator": {"renderer": {"name": "default"}, "max_steps": 200}, - } - ) +@pytest.mark.parametrize("component", ["trainer", "orchestrator"]) +@pytest.mark.parametrize( + "field", [{"max_steps": 10}, {"resume": {}}, {"ckpt": {}}, {"monitors": {}}, {"rollout_transport": {}}] +) +def test_run_level_fields_are_set_once_for_the_run(component, field): + """The trainer and the orchestrator always share these, so ``rl`` takes them only at the top level.""" + sections = {"trainer": {}, "orchestrator": {"renderer": {"name": "default"}}} + sections[component] = {**sections[component], **field} + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + RLConfig.model_validate(sections) + + +def test_run_level_fields_reach_trainer_and_orchestrator(): + config = RLConfig.model_validate( + { + "max_steps": 7, + "resume": {"step": 3}, + "rollout_transport": {"port": 6000}, + "monitors": {"wandb": {"project": "p", "entity": "e", "group": "g", "tags": ["a"]}}, + "trainer": {}, + "orchestrator": {"renderer": {"name": "default"}}, + } + ) + for component in (config.trainer_config(), config.orchestrator_config()): + assert component.max_steps == 7 + assert component.resume.step == 3 + assert component.rollout_transport.port == 6000 + assert component.monitors == config.monitors def test_trainer_chat_template_cascades_to_inference(): @@ -1356,82 +1478,29 @@ def test_trainer_chat_template_cascades_to_inference(): assert config.inference.vllm.chat_template == "TPL" -def test_shared_wandb_fields_propagate_to_subconfigs(): - """Every ``SharedWandbConfig`` leaf (project, entity, name, group, tags, - offline) propagates to both trainer.monitors.wandb and - orchestrator.monitors.wandb. Regression for a miss in the inline propagator.""" +def test_rl_monitors_disable_and_name_both_components(): + """CLI ``--no-monitors.wandb`` lands as the string "None" and turns the monitor off for both components.""" config = RLConfig.model_validate( { - "model": {"name": "Qwen/Qwen3-0.6B"}, - "monitors": { - "wandb": { - "project": "shared-proj", - "entity": "shared-entity", - "name": "shared-name", - "group": "shared-group", - "tags": ["a", "b"], - "offline": False, - } - }, + "monitors": {"wandb": "None", "file": "None", "prime": {"name": "shared-prime"}}, "trainer": {}, "orchestrator": {"renderer": {"name": "default"}}, } ) - for component in (config.trainer.monitors.wandb, config.orchestrator.monitors.wandb): - assert component is not None - assert component.project == "shared-proj" - assert component.entity == "shared-entity" - assert component.name == "shared-name" - assert component.group == "shared-group" - assert component.tags == ["a", "b"] - assert component.offline is False + for component in (config.trainer_config(), config.orchestrator_config()): + assert component.monitors.wandb is None and component.monitors.file is None + assert component.monitors.prime.name == "shared-prime" -def test_shared_monitor_disable_and_prime_propagate(): - """CLI ``--no-monitors.wandb`` / ``--no-monitors.file`` (which land as the string - "None") propagate the disable to both sub-configs, whose monitors default to - enabled; a shared ``[monitors.prime]`` reaches both.""" +def test_an_explicit_wandb_name_also_names_the_prime_run(): config = RLConfig.model_validate( { - "model": {"name": "Qwen/Qwen3-0.6B"}, - "monitors": {"wandb": "None", "file": "None", "prime": {"name": "shared-prime"}}, + "monitors": {"wandb": {"name": "w"}, "prime": {}}, "trainer": {}, "orchestrator": {"renderer": {"name": "default"}}, } ) - assert config.trainer.monitors.wandb is None and config.trainer.monitors.file is None - assert config.orchestrator.monitors.wandb is None and config.orchestrator.monitors.file is None - assert config.trainer.monitors.prime.name == config.orchestrator.monitors.prime.name == "shared-prime" - - -@pytest.mark.parametrize( - "monitor,trainer,orchestrator", - [("wandb", {"wandb": {"project": "p"}}, {}), ("prime", {"prime": {}}, {})], -) -def test_monitor_on_in_one_component_only_is_rejected(monitor, trainer, orchestrator): - """The components log to one run per monitor, so a monitor is on in all or none.""" - with pytest.raises(ValueError, match=rf"monitors.{monitor} must match across components"): - RLConfig.model_validate( - { - "model": {"name": "Qwen/Qwen3-0.6B"}, - "trainer": {"monitors": trainer}, - "orchestrator": {"renderer": {"name": "default"}, "monitors": orchestrator}, - } - ) - - -def test_empty_shared_ckpt_block_does_not_conflict_with_subconfig_ckpt(): - """An empty shared [ckpt] block is a presence-only signal, not a field - setting — it should not conflict with a non-empty [trainer.ckpt].""" - config = RLConfig.model_validate( - { - "ckpt": {}, # empty block, no field set - "trainer": {"ckpt": {"interval": 50}}, - "orchestrator": {"renderer": {"name": "default"}, "ckpt": {"interval": 50}}, - } - ) - assert config.trainer.ckpt is not None - assert config.trainer.ckpt.interval == 50 + assert config.orchestrator_config().monitors.prime.name == "w" def test_shared_and_subconfig_disjoint_fields_coexist(): @@ -1466,12 +1535,11 @@ def test_run_dir_propagates_through_cli(tmp_path): shared_out = tmp_path / "shared" config = cli(RLConfig, args=["@", str(toml_path), "--output-dir", str(shared_out), "--run.name", "my-exp"]) assert config.run_dir == shared_out / "my-exp" - assert config.trainer.output_dir == shared_out / "my-exp" - assert config.orchestrator.output_dir == shared_out / "my-exp" + assert config.trainer_config().output_dir == shared_out / "my-exp" + assert config.orchestrator_config().output_dir == shared_out / "my-exp" # Unset monitor names inherit run.name assert config.monitors.wandb is not None and config.monitors.wandb.name == "my-exp" - assert config.trainer.monitors.wandb is not None and config.trainer.monitors.wandb.name == "my-exp" - assert config.orchestrator.monitors.wandb is not None and config.orchestrator.monitors.wandb.name == "my-exp" + assert config.trainer_config().monitors.wandb.name == config.orchestrator_config().monitors.wandb.name == "my-exp" def test_orchestrator_renderer_auto_rejects_unmapped_model(): @@ -1611,8 +1679,8 @@ def test_pd_role_connectors(): mooncake = {"type": "mooncake", "cpu": {"num_bytes": 1000}} deployment = {"type": "disaggregated", "decode_kv_cache_offload": {**mooncake, "cpu": {"num_bytes": 0}}} config = InferenceConfig(deployment=deployment, slurm={}, kv_cache_offload=mooncake) - prefill = config.for_pd_role("prefill").build_kv_transfer_config()["kv_connector_extra_config"]["connectors"] - decode = config.for_pd_role("decode").build_kv_transfer_config()["kv_connector_extra_config"]["connectors"] + prefill = config.engine_config(role="prefill").build_kv_transfer_config()["kv_connector_extra_config"]["connectors"] + decode = config.engine_config(role="decode").build_kv_transfer_config()["kv_connector_extra_config"]["connectors"] assert [c["kv_connector"] for c in prefill] == ["NixlConnector", "MooncakeStoreConnector"] assert [c["kv_connector"] for c in decode] == ["NixlConnector", "MooncakeStoreConnector"] # The store lookup runs off the scheduler thread. @@ -1625,9 +1693,14 @@ def test_pd_role_connectors(): config = InferenceConfig( deployment=deployment, slurm={}, kv_cache_offload=mooncake, hisparse={"host_pool_gib": 160} ) - decode = config.for_pd_role("decode").build_kv_transfer_config()["kv_connector_extra_config"]["connectors"] + decode = config.engine_config(role="decode").build_kv_transfer_config()["kv_connector_extra_config"]["connectors"] assert [c["kv_connector"] for c in decode] == ["NixlConnector", "HiSparseConnector"] - assert config.for_pd_role("prefill").hisparse is None + assert config.engine_config(role="prefill").hisparse is None + + native = {"type": "native", "cpu": {"num_bytes": 1000}} + config = InferenceConfig(deployment=deployment, slurm={}, kv_cache_offload=native, hisparse={"host_pool_gib": 160}) + assert config.engine_config(role="prefill").kv_cache_offload.type == "native" + assert config.engine_config(role="decode").kv_cache_offload is None with pytest.raises(ValidationError, match="native KV cache offload"): InferenceConfig( @@ -1641,7 +1714,7 @@ def test_pd_bidirectional_kv_transfer(): assert config.deployment.bidirectional_kv_transfer.effective_router_ttl_s == 570 for role in ("prefill", "decode"): - connector = config.for_pd_role(role).build_kv_transfer_config() + connector = config.engine_config(role=role).build_kv_transfer_config() assert connector["kv_connector"] == "NixlConnector" assert connector["kv_connector_extra_config"] == { "num_threads": 1, @@ -1650,7 +1723,7 @@ def test_pd_bidirectional_kv_transfer(): } # The per-role engine configs drop `deployment`; bidirectional transfer survives through the persisted TTL. - role = InferenceConfig(**dump_resolved_config(config.for_pd_role("decode"), exclude={"deployment", "slurm"})) + role = EngineConfig(**dump_resolved_config(config.engine_config(role="decode"))) assert role.build_kv_transfer_config()["kv_connector_extra_config"]["decoder_kv_blocks_ttl"] == 600 with pytest.raises(ValidationError, match="shorter than decode_blocks_ttl_s"): @@ -1665,7 +1738,7 @@ def test_pd_bidirectional_kv_transfer(): # One-way P/D is unchanged: no bidirectional flags. config = InferenceConfig(deployment={"type": "disaggregated"}, slurm={}) - decode = config.for_pd_role("decode").build_kv_transfer_config() + decode = config.engine_config(role="decode").build_kv_transfer_config() assert decode["kv_connector_extra_config"] == {"num_threads": 1} @@ -1680,7 +1753,7 @@ def test_pd_spill_to_store_runs_the_store_connector_in_capacity_only_mode(): assert config.deployment.bidirectional_kv_transfer.effective_router_ttl_s == 3600 for role in ("prefill", "decode"): - role_config = InferenceConfig(**dump_resolved_config(config.for_pd_role(role), exclude={"deployment", "slurm"})) + role_config = EngineConfig(**dump_resolved_config(config.engine_config(role=role))) nixl, mooncake = role_config.build_kv_transfer_config()["kv_connector_extra_config"]["connectors"] assert nixl["kv_connector_extra_config"] == { "num_threads": 1, @@ -1714,13 +1787,15 @@ def test_pd_spill_to_store_runs_the_store_connector_in_capacity_only_mode(): kv_cache_offload=store, slurm={}, ) - mooncake = plain.for_pd_role("decode").build_kv_transfer_config()["kv_connector_extra_config"]["connectors"][1] + mooncake = plain.engine_config(role="decode").build_kv_transfer_config()["kv_connector_extra_config"]["connectors"][ + 1 + ] assert mooncake["kv_role"] == "kv_both" and mooncake["kv_connector_extra_config"]["save_decode_cache"] is True assert "enable_lookup" not in mooncake["kv_connector_extra_config"] -def test_for_pd_role_bakes_self_contained_role_vllm_and_env(): - from prime_rl.utils.config import dump_pd_components +def test_pd_role_engines_bake_in_their_role_vllm_and_env(): + from prime_rl.configs.base import dump_components deployment = { "type": "disaggregated", @@ -1737,12 +1812,11 @@ def test_for_pd_role_bakes_self_contained_role_vllm_and_env(): env_vars={"COMMON_VAR": "1"}, ) - components = dump_pd_components(config) - prefill = InferenceConfig(**components["prefill"]) - decode = InferenceConfig(**components["decode"]) + components = dump_components(config) + prefill = EngineConfig(**components["engine-prefill"]) + decode = EngineConfig(**components["engine-decode"]) assert prefill.server.port == 8100 - assert prefill.router is None assert prefill.vllm.data_parallel_size == 8 assert prefill.vllm.data_parallel_size_local == 8 assert prefill.vllm.api_server_count == 8 @@ -1755,7 +1829,6 @@ def test_for_pd_role_bakes_self_contained_role_vllm_and_env(): } assert decode.server.port == 8200 - assert decode.router is None assert decode.to_namespace().all2all_backend == "deepep_low_latency" assert decode.to_namespace().compilation_config == {"cudagraph_mode": "FULL_DECODE_ONLY"} assert decode.to_namespace().max_num_seqs == 64 @@ -1765,11 +1838,11 @@ def test_for_pd_role_bakes_self_contained_role_vllm_and_env(): deployment={**deployment, "prefill_vllm_overrides": {"all2all_backend": "flashinfer_nvlink_one_sided"}}, slurm={}, ) - assert "VLLM_USE_BREAKABLE_CUDAGRAPH" not in custom.for_pd_role("prefill").env_vars + assert "VLLM_USE_BREAKABLE_CUDAGRAPH" not in custom.engine_config(role="prefill").env_vars -def test_dump_rl_components_preserves_router_and_disaggregated_deployment(): - from prime_rl.utils.config import dump_rl_components +def test_rl_components_carry_the_router_and_one_engine_per_pd_role(): + from prime_rl.configs.base import dump_components config = RLConfig( trainer={}, @@ -1782,23 +1855,27 @@ def test_dump_rl_components_preserves_router_and_disaggregated_deployment(): }, slurm={}, ) - components = dump_rl_components(config) - assert components["inference"]["router"]["policy"] == "consistent_hash" - assert components["inference"]["router"]["request_timeout_secs"] == 600 - assert components["inference"]["deployment"]["type"] == "disaggregated" + components = dump_components(config) + assert components["router"]["router"]["policy"] == "consistent_hash" + assert components["router"]["router"]["request_timeout_secs"] == 600 + assert {"engine-prefill", "engine-decode"} <= components.keys() and "engine" not in components + assert components["engine-prefill"]["pd_kv_transfer"] == {"bidirectional": None} + # The launcher hands each engine the run's admin token, so none may serve its admin routes open. + assert components["engine-prefill"]["server"]["require_admin_token"] + assert components["engine-decode"]["server"]["require_admin_token"] def test_default_moe_backend_env_applies_only_when_unset(monkeypatch): monkeypatch.delenv("PRL_DEFAULT_MOE_BACKEND", raising=False) - assert not hasattr(InferenceConfig().to_namespace(), "moe_backend") + assert not hasattr(EngineConfig().to_namespace(), "moe_backend") monkeypatch.setenv("PRL_DEFAULT_MOE_BACKEND", "triton") - assert InferenceConfig().to_namespace().moe_backend == "triton" - assert InferenceConfig(vllm={"moe_backend": "flashinfer_trtllm"}).to_namespace().moe_backend == "flashinfer_trtllm" + assert EngineConfig().to_namespace().moe_backend == "triton" + assert EngineConfig(vllm={"moe_backend": "flashinfer_trtllm"}).to_namespace().moe_backend == "flashinfer_trtllm" -def test_for_pd_role_sets_multi_node_dp_sizes(): - from prime_rl.utils.config import dump_pd_components +def test_pd_role_engines_set_multi_node_dp_sizes(): + from prime_rl.configs.base import dump_components config = InferenceConfig( deployment={ @@ -1811,9 +1888,9 @@ def test_for_pd_role_sets_multi_node_dp_sizes(): slurm={}, vllm={"tensor_parallel_size": 1}, ) - components = dump_pd_components(config) - prefill = InferenceConfig(**components["prefill"]) - decode = InferenceConfig(**components["decode"]) + components = dump_components(config) + prefill = EngineConfig(**components["engine-prefill"]) + decode = EngineConfig(**components["engine-decode"]) assert (prefill.vllm.data_parallel_size, prefill.vllm.data_parallel_size_local, prefill.vllm.api_server_count) == ( 16, @@ -1828,7 +1905,7 @@ def test_for_pd_role_sets_multi_node_dp_sizes(): def test_served_eval_accepts_uniform_per_rank_roles_for_internal_dp(): - from prime_rl.configs.eval import ServedEvalConfig + from prime_rl.configs.components.online_eval import ServedEvalConfig source = [{"env": {"taskset": {"id": "harbor"}}}] cfg = ServedEvalConfig( @@ -2029,7 +2106,7 @@ def test_inference_loads_dummy_weights_for_a_scratch_init( "inference": {"vllm": vllm}, } ) - namespace = config.inference.to_namespace() + namespace = config.engine_configs()["engine"].to_namespace() assert getattr(namespace, "load_format", None) == load_format draft_load_config = {"load_format": "auto"} if load_format == "dummy" else None assert namespace.speculative_config.get("draft_load_config") == draft_load_config @@ -2115,7 +2192,7 @@ def rl(vllm, env_vars=None): @pytest.mark.parametrize("rollouts", [False, True]) -def test_shared_ckpt_rollouts_reaches_the_orchestrator(rollouts): +def test_ckpt_rollouts_reaches_the_orchestrator(rollouts): config = RLConfig.model_validate( { "ckpt": {"interval": 5, "rollouts": rollouts}, @@ -2123,18 +2200,18 @@ def test_shared_ckpt_rollouts_reaches_the_orchestrator(rollouts): "orchestrator": {"renderer": {"name": "default"}}, } ) - assert config.orchestrator.ckpt.rollouts is rollouts - assert config.orchestrator.ckpt.interval == config.trainer.ckpt.interval == 5 + assert config.orchestrator_config().ckpt.rollouts is rollouts + assert config.orchestrator_config().ckpt.interval == config.trainer_config().ckpt.interval == 5 assert RLConfig.model_validate_json(config.model_dump_json()) == config def test_ckpt_rollouts_is_off_by_default(): config = RLConfig.model_validate({"ckpt": {}, "trainer": {}, "orchestrator": {"renderer": {"name": "default"}}}) - assert config.orchestrator.ckpt.rollouts is False - assert config.orchestrator.ckpt.rollouts_save_timeout == 120 + assert config.orchestrator_config().ckpt.rollouts is False + assert config.orchestrator_config().ckpt.rollouts_save_timeout == 120 -def test_shared_ckpt_rollouts_save_timeout_reaches_the_orchestrator(): +def test_ckpt_rollouts_save_timeout_reaches_the_orchestrator(): config = RLConfig.model_validate( { "ckpt": {"rollouts": True, "rollouts_save_timeout": 900}, @@ -2142,7 +2219,7 @@ def test_shared_ckpt_rollouts_save_timeout_reaches_the_orchestrator(): "orchestrator": {"renderer": {"name": "default"}}, } ) - assert config.orchestrator.ckpt.rollouts_save_timeout == 900 + assert config.orchestrator_config().ckpt.rollouts_save_timeout == 900 assert RLConfig.model_validate_json(config.model_dump_json()) == config with pytest.raises(ValueError): RLConfig.model_validate( @@ -2150,29 +2227,23 @@ def test_shared_ckpt_rollouts_save_timeout_reaches_the_orchestrator(): ) -def test_shared_ckpt_reaches_trainer_and_orchestrator(): +def test_ckpt_splits_into_the_trainer_and_orchestrator_fields(): config = RLConfig.model_validate( { - "ckpt": {"output_dir": "/ckpts", "keep_last": 3, "keep_interval": 100}, + "ckpt": {"output_dir": "/ckpts", "keep_last": 3, "keep_interval": 100, "skip_optimizer": True}, "trainer": {}, "orchestrator": {"renderer": {"name": "default"}}, } ) - for ckpt in (config.trainer.ckpt, config.orchestrator.ckpt): + trainer, orchestrator = config.trainer_config().ckpt, config.orchestrator_config().ckpt + for ckpt in (trainer, orchestrator): assert (ckpt.output_dir, ckpt.keep_last, ckpt.keep_interval) == (Path("/ckpts"), 3, 100) - - -@pytest.mark.parametrize("leaf", [("output_dir", "/ckpts"), ("keep_last", 3), ("keep_interval", 100)]) -def test_trainer_and_orchestrator_share_one_ckpt_dir_and_policy(leaf): - name, value = leaf - with pytest.raises(ValueError, match=f"ckpt.{name}"): - RLConfig.model_validate( - {"ckpt": {}, "trainer": {"ckpt": {name: value}}, "orchestrator": {"renderer": {"name": "default"}}} - ) + assert trainer.skip_optimizer and not hasattr(orchestrator, "skip_optimizer") + assert not hasattr(trainer, "rollouts") def test_env_worker_pool_uses_ckpt_output_dir_as_save_root(tmp_path): - from prime_rl.entrypoints.rl import write_subconfigs + from prime_rl.entrypoints.rl import write_configs ckpt_dir = tmp_path / "external_ckpts" config = RLConfig.model_validate( @@ -2187,7 +2258,7 @@ def test_env_worker_pool_uses_ckpt_output_dir_as_save_root(tmp_path): } ) cfg_dir = tmp_path / "configs" - write_subconfigs(config, cfg_dir) + write_configs(config, cfg_dir) pool_configs = list((cfg_dir / "envs" / "train").glob("*.json")) assert pool_configs data = json.loads(pool_configs[0].read_text()) @@ -2218,28 +2289,46 @@ def _rl_config_with_env_sources(tmp_path) -> RLConfig: ) -def test_env_worker_pool_components_are_the_launchers_pools_without_address_files(tmp_path): - from prime_rl.entrypoints.rl import write_subconfigs - from prime_rl.utils.config import dump_env_worker_pool_components +def test_rl_launcher_writes_exactly_the_components(tmp_path): + from prime_rl.configs.base import dump_components + from prime_rl.entrypoints.rl import write_configs + from prime_rl.utils.pathing import env_worker_pool_command config = _rl_config_with_env_sources(tmp_path) cfg_dir = tmp_path / "configs" - write_subconfigs(config, cfg_dir) - - components = dump_env_worker_pool_components(config) + write_configs(config, cfg_dir) + components = dump_components(config) # The externally served source gets no pool. - assert sorted(components) == ["eval/harbor", "train/harbor"] - for key, component in components.items(): - split, name = key.split("/") - written = json.loads((cfg_dir / "envs" / split / f"{name}.json").read_text()) - assert written.pop("address_file").endswith(f"envs/{split}/{name}.address") - assert written == component - EnvWorkerPoolConfig.model_validate(component) + assert sorted(name for name in components if name.startswith("envs/")) == ["envs/eval/harbor", "envs/train/harbor"] + for name, component in components.items(): + assert json.loads((cfg_dir / f"{name}.json").read_text()) == component + # The pool publishes its address next to its config, which the orchestrator reads from the same attempt. + assert env_worker_pool_command(cfg_dir, "train", "harbor")[-2:] == [ + "--address-file", + (cfg_dir / "envs" / "train" / "harbor.address").as_posix(), + ] + + +def test_sft_launcher_writes_exactly_the_components(tmp_path): + from prime_rl.configs.base import dump_components + from prime_rl.entrypoints.launcher import write_configs + + config = SFTConfig.model_validate( + {"eval": SFT_ONLINE_EVAL, "inference": {}, "resume": {"step": 5}, "output_dir": tmp_path} + ) + write_configs(config, tmp_path / "configs", "sft") + + components = dump_components(config) + assert {"trainer", "online-eval", "engine"} <= components.keys() + for name, component in components.items(): + assert json.loads((tmp_path / "configs" / f"{name}.json").read_text()) == component + assert components["online-eval"]["resume"] == {"step": 5, "dir": None} + assert components["engine"]["server"]["require_admin_token"] def test_env_worker_pool_config_keeps_paths_as_given_and_adds_only_what_is_set(tmp_path): - from prime_rl.configs.env_worker_pool import env_worker_pool_config + from prime_rl.configs.components.env_worker_pool import env_worker_pool_config config = _rl_config_with_env_sources(tmp_path) source = config.orchestrator.train.source[0] @@ -2247,9 +2336,9 @@ def test_env_worker_pool_config_keeps_paths_as_given_and_adds_only_what_is_set(t bare = env_worker_pool_config(source, config.orchestrator.log, Path("outputs/run")) stored = env_worker_pool_config(source, config.orchestrator.log, Path("outputs/run"), store_dir=Path("/tmp/store")) - assert bare["output_dir"] == "outputs/run" - assert "address_file" not in bare and "store_dir" not in bare - assert stored["store_dir"] == "/tmp/store" + assert bare.output_dir == Path("outputs/run") + assert bare.address_file is None and bare.store_dir is None + assert stored.store_dir == Path("/tmp/store") def _dynamo_orchestrator(sampling: dict, dynamo: bool = True) -> dict: @@ -2286,3 +2375,289 @@ def test_dynamo_rejects_score_centering_at_launch(): "orchestrator": _dynamo_orchestrator({}), } ) + + +RL_MINIMAL = {"trainer": {}, "orchestrator": {"renderer": {"name": "default"}}} + + +def rl_config(**data) -> RLConfig: + merged = copy.deepcopy({**RL_MINIMAL, **data}) + merged["orchestrator"] = {**copy.deepcopy(RL_MINIMAL["orchestrator"]), **merged.get("orchestrator", {})} + return RLConfig.model_validate(merged) + + +def test_rl_keeps_a_larger_max_lora_rank_and_rejects_a_smaller_one(): + lora = {"model": {"lora": {"rank": 16}}} + assert rl_config(trainer=lora, inference={}).inference.vllm.max_lora_rank == 16 + assert rl_config(trainer=lora, inference={"vllm": {"max_lora_rank": 64}}).inference.vllm.max_lora_rank == 64 + with pytest.raises(ValidationError, match="below the trainer's LoRA rank"): + rl_config(trainer=lora, inference={"vllm": {"max_lora_rank": 8}}) + + +def test_rl_fills_inference_gpus_with_data_parallelism_unless_the_size_is_explicit(): + deployment = {"num_train_gpus": 1, "num_infer_gpus": 2} + assert rl_config(deployment=deployment, inference={}).inference.vllm.data_parallel_size == 2 + with pytest.raises(ValidationError, match="does not match the 2 inference GPUs"): + rl_config(deployment=deployment, inference={"vllm": {"data_parallel_size": 1}}) + + +SFT_INFERENCE_RUN = {"eval": SFT_ONLINE_EVAL, "deployment": {"num_train_gpus": 1, "num_infer_gpus": 1}} + + +@pytest.mark.parametrize( + ("entrypoint", "data"), + [ + (RLConfig, {**RL_MINIMAL, "orchestrator": {**RL_MINIMAL["orchestrator"], "env_worker_pool_replicas": 2}}), + (RLConfig, {**RL_MINIMAL, "trainer": {"output_dir": "x"}}), + (RLConfig, {**RL_MINIMAL, "trainer": {"weight_broadcast": {"type": "nccl"}}}), + (RLConfig, {**RL_MINIMAL, "orchestrator": {**RL_MINIMAL["orchestrator"], "output_dir": "x"}}), + (RLConfig, {**RL_MINIMAL, "orchestrator": {**RL_MINIMAL["orchestrator"], "weight_broadcast": {}}}), + (RLConfig, {**RL_MINIMAL, "inference": {"weight_broadcast": {"type": "nccl"}}}), + (RLConfig, {**RL_MINIMAL, "inference": {"slurm": {}}}), + (RLConfig, {**RL_MINIMAL, "inference": {"dry_run": True}}), + (RLConfig, {**RL_MINIMAL, "inference": {"pd_kv_transfer": {}}}), + (SFTConfig, {**SFT_INFERENCE_RUN, "inference": {"weight_broadcast": {"type": "nccl"}}}), + (SFTConfig, {**SFT_INFERENCE_RUN, "inference": {"deployment": {"type": "single_node"}}}), + (SFTConfig, {**SFT_INFERENCE_RUN, "inference": {"slurm": {}}}), + (SFTConfig, {**SFT_INFERENCE_RUN, "inference": {"dry_run": True}}), + ], +) +def test_entrypoints_reject_component_fields_their_launcher_fills(entrypoint, data): + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + entrypoint.model_validate(data) + + +RL_RUN_FIELDS = {"max_steps", "resume", "ckpt", "monitors", "rollout_transport"} + + +@pytest.mark.parametrize( + ("config_cls", "section_cls", "added"), + [ + ( + EngineConfig, + EngineSection, + {"weight_broadcast", "pd_kv_transfer"}, + ), + (InferenceConfig, InferenceSection, {"weight_broadcast", "slurm", "output_dir", "dry_run"}), + (InferenceSection, ServingSection, {"deployment"}), + ( + OrchestratorConfig, + OrchestratorSection, + {"env_worker_pool_replicas", "output_dir", "weight_broadcast", *RL_RUN_FIELDS}, + ), + (TrainerConfig, TrainerSection, {"output_dir", "weight_broadcast", *RL_RUN_FIELDS}), + (SFTTrainerConfig, SFTTrainerSection, set()), + (PretrainTrainerConfig, PretrainTrainerSection, set()), + (SFTConfig, SFTTrainerSection, {"inference", "deployment", "slurm", "dashboard", "dry_run", "clean", "mode"}), + ], +) +def test_component_configs_extend_their_public_sections(config_cls, section_cls, added): + """A component config inherits every field of its section, so the two cannot drift apart.""" + assert issubclass(config_cls, section_cls) + assert config_cls.model_fields.keys() - section_cls.model_fields.keys() == added + + +def _nested_models(annotation) -> set[type]: + if isinstance(annotation, type) and issubclass(annotation, BaseModel): + return {annotation} + return {model for arg in get_args(annotation) for model in _nested_models(arg)} + + +@pytest.mark.parametrize("entrypoint", [RLConfig, SFTConfig, PretrainConfig, EvalConfig, InferenceConfig]) +def test_entrypoints_nest_no_component_configs(entrypoint): + """An entrypoint nests sections; a launcher builds the component configs from them.""" + seen, todo = set(), [entrypoint] + while todo: + model = todo.pop() + for name, field in model.model_fields.items(): + for nested in _nested_models(field.annotation) - seen: + assert not issubclass(nested, ComponentConfig), f"{model.__name__}.{name} is a {nested.__name__}" + seen.add(nested) + todo.append(nested) + + +def test_rl_trainer_alone_binds_the_nccl_rendezvous_on_multi_node(): + config = rl_config( + deployment={"type": "multi_node", "num_train_nodes": 1, "num_infer_nodes": 2}, + inference={}, + slurm={}, + weight_broadcast={"type": "nccl"}, + ) + assert config.trainer_config().weight_broadcast.host == "0.0.0.0" + assert config.orchestrator_config().weight_broadcast.host == "localhost" + assert config.trainer_config().weight_broadcast.inference_world_size == 16 + + +def test_sft_inference_takes_its_deployment_from_the_run(): + """The sft launcher starts inference on the run's inference nodes, so llm-d works only on multi-node runs.""" + inference = {"router": {"type": "llm-d"}} + multi_node = {"type": "multi_node", "num_train_nodes": 1, "num_infer_nodes": 2} + config = SFTConfig.model_validate( + {**SFT_INFERENCE_RUN, "inference": inference, "slurm": {}, "deployment": multi_node} + ) + assert config.placement()["engine"].nodes == 2 + assert "router" not in config.components() + with pytest.raises(ValidationError, match="llm-d router backend requires"): + SFTConfig.model_validate({**SFT_INFERENCE_RUN, "inference": inference}) + + +def test_rl_validates_the_component_configs_it_builds(): + with pytest.raises(ValidationError, match="retain needs ckpt.interval"): + rl_config(rollout_transport={"retain": True}) + + +def test_rl_fills_env_worker_pool_replicas_per_inference_node(): + assert rl_config().orchestrator_config().env_worker_pool_replicas is None + config = rl_config( + deployment={"type": "multi_node", "num_train_nodes": 1, "num_infer_nodes": 2}, + inference={}, + slurm={}, + ) + assert config.orchestrator_config().env_worker_pool_replicas == 2 + + from prime_rl.configs.base import dump_components + + components = dump_components(config) + assert components["orchestrator"]["env_worker_pool_replicas"] == 2 + assert components["engine"]["weight_broadcast"]["type"] == config.weight_broadcast.type + + +@pytest.mark.parametrize("transport", ["filesystem", "nccl"]) +def test_launchers_give_inference_the_shared_weight_transport(transport): + rl = rl_config(weight_broadcast={"type": transport}, inference={}) + assert rl.engine_configs()["engine"].weight_broadcast.type == transport + sft = SFTConfig.model_validate({**SFT_INFERENCE_RUN, "weight_broadcast": {"type": transport}, "inference": {}}) + assert sft.engine_configs()["engine"].weight_broadcast.type == transport + + +def test_built_inference_keeps_which_fields_the_user_set(): + """The prefill engine defaults kv_load_failure_policy only when the user left it unset.""" + config = rl_config(inference={"kv_load_failure_policy": "fail"}) + built = config.engine_configs()["engine"] + assert "kv_load_failure_policy" in built.model_fields_set + assert "hisparse" not in built.model_fields_set + + +def test_backend_port_follows_the_server_port_unless_set(): + assert InferenceConfig(server={"port": 9000}).backend_port == 9100 + assert InferenceConfig(server={"port": 9000}, router=None).backend_port == 9100 + assert InferenceConfig(server={"port": 9000}, backend_port=9500).backend_port == 9500 + + +@pytest.mark.parametrize("field", ["model", "max_steps", "output_dir", "broadcasts_dir", "log", "monitors"]) +def test_sft_eval_block_has_no_fields_the_launcher_fills(field): + with pytest.raises(ValidationError, match=field): + SFTConfig.model_validate( + { + "eval": {**SFT_ONLINE_EVAL, field: SFTOnlineEvalConfig.model_fields[field].default}, + "inference": {}, + "deployment": {"num_train_gpus": 1, "num_infer_gpus": 1}, + } + ) + + +@pytest.mark.parametrize( + "config_cls, field, accepted", + [ + (OrchestratorConfig, "interval", True), + (EvalConfig, "interval", True), + (SFTConfig, "log_data", True), + (TrainerConfig, "interval", False), + (TrainerConfig, "log_data", False), + (SFTConfig, "interval", False), + (EngineConfig, "interval", False), + (EnvWorkerPoolConfig, "log_data", False), + ], +) +def test_log_blocks_hold_only_the_fields_their_process_reads(config_cls, field, accepted): + assert (field in config_cls.model_fields["log"].annotation.model_fields) is accepted + + +def test_rl_rejects_offline_wandb(): + with pytest.raises(ValidationError, match="offline"): + rl_config(monitors={"wandb": {"offline": True}}) + + +MULTI_NODE_RL = {"type": "multi_node", "num_train_nodes": 1, "num_infer_nodes": 2, "gpus_per_node": 8} +PD_INFERENCE = {"deployment": {"type": "disaggregated", "num_prefill_replicas": 1, "num_decode_replicas": 1}} + + +RL_EVAL = {"eval": {"source": [{"name": "reverse-text", "env": {"taskset": {"id": "reverse-text"}}}]}} +PRETRAIN_DATA = {"data": {"source": [{"name": "a", "path": "a"}]}} +MODELEXPRESS = {"type": "modelexpress", "port": 9000} +ENTRYPOINTS = { + "rl": lambda: rl_config(), + "rl-inference-eval": lambda: rl_config(inference={}, orchestrator=RL_EVAL), + "rl-multi-node": lambda: rl_config(deployment=MULTI_NODE_RL, inference={}, slurm={}), + "rl-multi-node-pd": lambda: rl_config(deployment=MULTI_NODE_RL, inference=PD_INFERENCE, slurm={}), + "rl-modelexpress": lambda: rl_config(inference={}, weight_broadcast=MODELEXPRESS), + "rl-multi-node-modelexpress": lambda: rl_config( + deployment=MULTI_NODE_RL, inference={}, slurm={}, weight_broadcast=MODELEXPRESS + ), + "sft": lambda: SFTConfig(), + "sft-online-eval": lambda: SFTConfig.model_validate({**SFT_INFERENCE_RUN, "inference": {}}), + "sft-online-eval-modelexpress": lambda: SFTConfig.model_validate( + {**SFT_INFERENCE_RUN, "inference": {}, "weight_broadcast": MODELEXPRESS} + ), + "pretrain": lambda: PretrainConfig.model_validate(PRETRAIN_DATA), + "inference": lambda: InferenceConfig(), + "inference-pd": lambda: InferenceConfig(deployment=PD_INFERENCE["deployment"], slurm={}), + "eval": lambda: EvalConfig.model_validate(SFT_ONLINE_EVAL), +} + + +@pytest.mark.parametrize("build", ENTRYPOINTS.values(), ids=ENTRYPOINTS.keys()) +def test_entrypoints_place_every_component_they_launch(build): + config = build() + assert config.components().keys() == config.placement().keys() + + +@pytest.mark.parametrize("build", ENTRYPOINTS.values(), ids=ENTRYPOINTS.keys()) +def test_component_dumps_parse_back_into_their_configs(build): + """A component process reads its JSON with ``extra="forbid"``, so each dump must validate as its own class.""" + from prime_rl.configs.base import dump_components + + config = build() + components = config.components() + for name, data in dump_components(config).items(): + cls = type(components[name]) + assert issubclass(cls, ComponentConfig), name + assert cls.model_validate(json.loads(json.dumps(data))) == components[name], name + + +@pytest.mark.parametrize("transport", ["nccl", "modelexpress"]) +def test_sft_in_memory_weight_broadcast_requires_inference(transport): + with pytest.raises(ValidationError, match="requires launcher-managed inference"): + SFTConfig.model_validate({"weight_broadcast": {"type": transport}}) + + +def test_engine_behind_a_router_listens_on_the_backend_port(): + config = InferenceConfig(server={"port": 9000}) + assert config.engine_config().server.port == 9100 + assert config.router_config().port == 9000 + assert config.router_config().worker_urls == ["http://localhost:9100"] + assert InferenceConfig(server={"port": 9000}, router=None).engine_config().server.port == 9000 + + +def test_modelexpress_server_reads_its_own_config_not_the_trainers(tmp_path): + """The server is a component: its builder gives it the broadcast's port, and the trainer's JSON is not its + config. A SLURM job that uses an external server starts none.""" + from prime_rl.configs.base import dump_components + from prime_rl.configs.components.modelexpress_server import ModelExpressServerConfig + + config = ENTRYPOINTS["rl-modelexpress"]() + dumps = dump_components(config) + parsed = cli(ModelExpressServerConfig, args=["@", write_json(tmp_path / "mx.json", dumps["modelexpress-server"])]) + assert parsed.port == 9000 + with pytest.raises(ConfigFileError, match="--optim\\n Extra inputs are not permitted"): + cli(ModelExpressServerConfig, args=["@", write_json(tmp_path / "trainer.json", dumps["trainer"])]) + + external = rl_config( + deployment=MULTI_NODE_RL, inference={}, slurm={"launch_modelexpress": False}, weight_broadcast=MODELEXPRESS + ) + assert "modelexpress-server" not in external.components() + + +def write_json(path, data) -> str: + path.write_text(json.dumps(data)) + return path.as_posix() diff --git a/tests/unit/test_dashboard_artifacts.py b/tests/unit/test_dashboard_artifacts.py index 799abdb96b5..86aa1571169 100644 --- a/tests/unit/test_dashboard_artifacts.py +++ b/tests/unit/test_dashboard_artifacts.py @@ -4,7 +4,7 @@ from pydantic import create_model from verifiers.v1.delta import EpisodeAssembly -from prime_rl.configs.trainer import TrainerConfig +from prime_rl.configs.components.trainer import TrainerConfig from prime_rl.dashboard import server from prime_rl.monitors.file.traces.live import LiveFolds from prime_rl.utils.config import cli, dump_resolved_config diff --git a/tests/unit/test_modelexpress_server.py b/tests/unit/test_modelexpress_server.py index cfc83534b1f..473c01b2db6 100644 --- a/tests/unit/test_modelexpress_server.py +++ b/tests/unit/test_modelexpress_server.py @@ -1,4 +1,3 @@ -import json import os import signal import socket @@ -7,31 +6,11 @@ import time from pathlib import Path -from prime_rl.configs.modelexpress_server import ModelExpressServerConfig +from prime_rl.configs.components.modelexpress_server import ModelExpressServerConfig from prime_rl.entrypoints.modelexpress_server import serve_modelexpress -from prime_rl.utils.config import cli from prime_rl.utils.process import wait_for_port -def test_modelexpress_server_config_reads_trainer_json(tmp_path: Path): - trainer_json = tmp_path / "trainer.json" - trainer_json.write_text( - json.dumps( - { - "output_dir": "/volume/run", - "weight_broadcast": {"type": "modelexpress", "port": 9000}, - } - ) - ) - cfg = cli( - ModelExpressServerConfig, - args=["@", trainer_json.as_posix(), "--log-dir", (tmp_path / "state").as_posix()], - ) - assert cfg.resolved_port == 9000 - assert cfg.log_dir == tmp_path / "state" - assert ModelExpressServerConfig().resolved_port == 8001 - - def test_wait_for_port_returns_once_listening(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv: srv.bind(("127.0.0.1", 0)) @@ -48,7 +27,7 @@ def _fake_start(processes, port, log_dir, base_env): ) monkeypatch.setattr("prime_rl.entrypoints.modelexpress_server.start_modelexpress", _fake_start) - cfg = ModelExpressServerConfig(log_dir=tmp_path / "term") + cfg = ModelExpressServerConfig(port=8001, log_dir=tmp_path / "term") def _send_term(): time.sleep(0.2) @@ -64,4 +43,4 @@ def _fake_crash(processes, port, log_dir, base_env): processes.start("modelexpress", [sys.executable, "-c", "import sys; sys.exit(0)"], base_env, log_dir / "m.log") monkeypatch.setattr("prime_rl.entrypoints.modelexpress_server.start_modelexpress", _fake_crash) - assert serve_modelexpress(ModelExpressServerConfig(log_dir=tmp_path / "crash")) == 1 + assert serve_modelexpress(ModelExpressServerConfig(port=8001, log_dir=tmp_path / "crash")) == 1 diff --git a/tests/unit/test_parsers.py b/tests/unit/test_parsers.py index ecde00f8b09..fd0da88550a 100644 --- a/tests/unit/test_parsers.py +++ b/tests/unit/test_parsers.py @@ -1,6 +1,7 @@ import pytest -from prime_rl.configs.inference import InferenceConfig +from prime_rl.configs.components.engine import EngineConfig +from prime_rl.configs.entrypoints.inference import InferenceConfig from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser # (model_name, expected_tool_call_parser, expected_reasoning_parser) @@ -137,7 +138,7 @@ def test_inference_config_none_disables_parser(): def test_to_namespace_resolves_parsers(): - config = InferenceConfig(vllm={"model": "deepseek-ai/DeepSeek-V3.2"}) + config = EngineConfig(vllm={"model": "deepseek-ai/DeepSeek-V3.2"}) ns = config.to_namespace() assert ns.tool_call_parser == "deepseek_v32" assert ns.reasoning_parser == "deepseek_r1" @@ -147,7 +148,7 @@ def test_to_namespace_resolves_parsers(): def test_to_namespace_none_strips_parser_attrs_from_namespace(): """vLLM doesn't accept None for these — they must be removed, not passed through.""" - config = InferenceConfig( + config = EngineConfig( vllm={"model": "Qwen/Qwen3-4B", "tool_call_parser": None, "reasoning_parser": None}, ) ns = config.to_namespace() @@ -157,7 +158,7 @@ def test_to_namespace_none_strips_parser_attrs_from_namespace(): def test_to_namespace_unknown_model_disables_auto_tool_choice(): - config = InferenceConfig(vllm={"model": "some/unknown-model"}) + config = EngineConfig(vllm={"model": "some/unknown-model"}) ns = config.to_namespace() assert not hasattr(ns, "tool_call_parser") assert ns.enable_auto_tool_choice is False @@ -166,7 +167,7 @@ def test_to_namespace_unknown_model_disables_auto_tool_choice(): def test_to_namespace_passes_through_unknown_args(): """Untyped [inference.vllm] keys land on the namespace verbatim, with CLI-style string values JSON-coerced.""" - config = InferenceConfig( + config = EngineConfig( vllm={"model": "Qwen/Qwen3-4B", "max_num_seqs": "256", "kv-cache-dtype": "fp8"}, ) ns = config.to_namespace() diff --git a/tests/unit/test_pd_launch.py b/tests/unit/test_pd_launch.py index 693556987a6..2bbb652445a 100644 --- a/tests/unit/test_pd_launch.py +++ b/tests/unit/test_pd_launch.py @@ -1,13 +1,15 @@ -import json from pathlib import Path import pytest -from prime_rl.configs.inference import InferenceConfig -from prime_rl.configs.router import RouterEntrypointConfig -from prime_rl.entrypoints.inference import apply_multi_node_dp_env, write_slurm_script -from prime_rl.entrypoints.router import router_command +from prime_rl.components.engine import apply_multi_node_dp_env +from prime_rl.components.router import router_command +from prime_rl.configs.components.engine import EngineConfig +from prime_rl.configs.components.router import RouterConfig +from prime_rl.configs.entrypoints.inference import InferenceConfig +from prime_rl.entrypoints.inference import write_slurm_script from prime_rl.utils.config import cli +from prime_rl.utils.pathing import write_component_configs BREAKABLE_OFF = "export VLLM_USE_BREAKABLE_CUDAGRAPH=0" @@ -16,7 +18,7 @@ def _script(tmp_path: Path, prefill_vllm_overrides: dict) -> str: deployment = {"type": "disaggregated", "prefill_vllm_overrides": prefill_vllm_overrides} config = InferenceConfig(deployment=deployment, slurm={}, output_dir=tmp_path) script_path = tmp_path / "inference.sbatch" - write_slurm_script(config, tmp_path / "inference.json", tmp_path / "logs", script_path) + write_slurm_script(config, tmp_path / "engine.json", tmp_path / "logs", script_path) return script_path.read_text() @@ -28,35 +30,51 @@ def test_prefill_keeps_breakable_cudagraphs_unless_it_runs_deepep_high_throughpu assert BREAKABLE_OFF not in _script(tmp_path, {"all2all_backend": "flashinfer_nvlink_one_sided"}) +@pytest.mark.parametrize( + "deployment", + [ + {"type": "multi_node", "num_nodes": 2}, + {"type": "disaggregated", "bidirectional_kv_transfer": {"decode_blocks_ttl_s": 480}}, + ], +) +def test_slurm_ranks_serve_the_engine_configs_the_entrypoint_builds(tmp_path: Path, deployment: dict): + """SLURM ranks run ``engine @ engine[-].json``. Each file must parse back to the engine that + ``InferenceConfig.engine_config`` builds.""" + config = InferenceConfig( + deployment=deployment, + slurm={}, + output_dir=tmp_path, + kv_cache_offload={"type": "native", "cpu": {"num_bytes": 2**30}}, + ) + write_component_configs(tmp_path, config.components()) + engines = config.engine_configs() + assert sorted(path.stem for path in tmp_path.glob("engine*.json")) == sorted(engines) + for name, built in engines.items(): + parsed = cli(EngineConfig, args=["@", (tmp_path / f"{name}.json").as_posix()]) + assert parsed.model_dump() == built.model_dump() + assert vars(parsed.to_namespace()) == vars(built.to_namespace()) + + +@pytest.mark.parametrize("config_cls", [EngineConfig, InferenceConfig]) +def test_unknown_keys_fail(config_cls: type): + with pytest.raises(ValueError, match="backend_prot"): + config_cls(backend_prot=8100) + + def test_router_entrypoint_builds_pd_and_colocated_commands(tmp_path: Path): - pd_config = tmp_path / "inference-pd.json" - pd_config.write_text( - json.dumps( - { - "vllm": {"tensor_parallel_size": 1, "data_parallel_size": 8, "data_parallel_size_local": 8}, - "router": { - "type": "vllm-router", - "policy": "consistent_hash", - "request_timeout_secs": 900, - "pd_turn_retries": 3, - }, - "deployment": { - "type": "disaggregated", - "bidirectional_kv_transfer": {"decode_blocks_ttl_s": 480}, - }, - "use_pd_kv_transfer": True, - } - ) + inference = InferenceConfig( + vllm={"tensor_parallel_size": 1}, + router={"type": "vllm-router", "policy": "consistent_hash", "request_timeout_secs": 900, "pd_turn_retries": 3}, + deployment={"type": "disaggregated", "bidirectional_kv_transfer": {"decode_blocks_ttl_s": 480}}, + slurm={}, ) + router_json = tmp_path / "router.json" + write_component_configs(tmp_path, {"router": inference.router_config()}) parsed = cli( - RouterEntrypointConfig, + RouterConfig, args=[ "@", - pd_config.as_posix(), - "--server.host", - "0.0.0.0", - "--server.port", - "8000", + router_json.as_posix(), "--prefill-urls", "http://p0:8100", "http://p1:8100", @@ -80,6 +98,8 @@ def test_router_entrypoint_builds_pd_and_colocated_commands(tmp_path: Path): "4200", "--worker-startup-check-interval", "1", + "--prometheus-port", + "29000", "--vllm-pd-disaggregation", "--prefill", "http://p0:8100", @@ -87,8 +107,6 @@ def test_router_entrypoint_builds_pd_and_colocated_commands(tmp_path: Path): "http://p1:8100", "--decode", "http://d0:8200", - "--intra-node-data-parallel-size", - "8", "--pd-turn-retries", "3", "--pd-bidirectional-kv", @@ -96,25 +114,16 @@ def test_router_entrypoint_builds_pd_and_colocated_commands(tmp_path: Path): "450", ] - dp1 = RouterEntrypointConfig( - router=None, - vllm={"tensor_parallel_size": 8, "data_parallel_size": 1, "data_parallel_size_local": 1}, - prefill_urls=["http://p0:8100"], - decode_urls=["http://d0:8200"], - ) - cmd = router_command(dp1) - assert "--intra-node-data-parallel-size" not in cmd + local = InferenceConfig(vllm={"data_parallel_size": 2}).router_config() + cmd = router_command(local) + assert cmd[cmd.index("--intra-node-data-parallel-size") + 1] == "2" + assert cmd[cmd.index("--worker-urls") + 1 :] == ["http://localhost:8100"] assert cmd[cmd.index("--policy") + 1] == "sticky_least_loaded" assert cmd[cmd.index("--request-timeout-secs") + 1] == "14400" - with pytest.raises(ValueError, match="llm-d"): - router_command( - RouterEntrypointConfig( - router={"type": "llm-d"}, - prefill_urls=["http://p0:8100"], - decode_urls=["http://d0:8200"], - ) - ) + llmd = InferenceConfig(router={"type": "llm-d"}, deployment={"type": "multi_node"}, slurm={}) + assert llmd.router_config() is None + assert "router" not in llmd.components() def test_apply_multi_node_dp_env_sets_hybrid_lb_rank_and_head(monkeypatch): @@ -122,17 +131,17 @@ def test_apply_multi_node_dp_env_sets_hybrid_lb_rank_and_head(monkeypatch): monkeypatch.setenv("PRL_DP_HEAD_HOST", "run-decode-0-0.run.ns.svc.cluster.local") monkeypatch.setenv("PRL_DP_NODE_RANK", "0") - head_cfg = InferenceConfig(vllm={"data_parallel_size": 32, "data_parallel_size_local": 8, "api_server_count": 8}) + head_cfg = EngineConfig(vllm={"data_parallel_size": 32, "data_parallel_size_local": 8, "api_server_count": 8}) apply_multi_node_dp_env(head_cfg) assert head_cfg.to_namespace().data_parallel_start_rank == 0 assert head_cfg.to_namespace().data_parallel_address == "10.0.0.7" monkeypatch.setenv("PRL_DP_NODE_RANK", "3") - peer_cfg = InferenceConfig(vllm={"data_parallel_size": 32, "data_parallel_size_local": 8, "api_server_count": 8}) + peer_cfg = EngineConfig(vllm={"data_parallel_size": 32, "data_parallel_size_local": 8, "api_server_count": 8}) apply_multi_node_dp_env(peer_cfg) assert peer_cfg.to_namespace().data_parallel_start_rank == 24 assert peer_cfg.to_namespace().data_parallel_address == "run-decode-0-0.run.ns.svc.cluster.local" - single_node = InferenceConfig(vllm={"data_parallel_size": 8, "data_parallel_size_local": 8, "api_server_count": 8}) + single_node = EngineConfig(vllm={"data_parallel_size": 8, "data_parallel_size_local": 8, "api_server_count": 8}) apply_multi_node_dp_env(single_node) assert not hasattr(single_node.to_namespace(), "data_parallel_start_rank") diff --git a/tests/unit/test_resume_cleanup.py b/tests/unit/test_resume_cleanup.py index 324473fa8f6..bcff25721f6 100644 --- a/tests/unit/test_resume_cleanup.py +++ b/tests/unit/test_resume_cleanup.py @@ -1,7 +1,7 @@ import json from pathlib import Path -from prime_rl.scripts.resume_cleanup import main, run_resume_cleanup +from prime_rl.scripts.resume_cleanup import main, resolve_online_eval_resume_step, run_resume_cleanup from prime_rl.utils.pathing import get_batch_dir, get_broadcast_dir, get_ckpt_dir @@ -78,3 +78,27 @@ def test_resume_cleanup_rl_flag_skips_step_missing_orchestrator_half(tmp_path: P def test_resume_cleanup_honors_explicit_step_via_cli(tmp_path: Path): run_dir = tmp_path / "run" assert main(["--run-dir", run_dir.as_posix(), "--resume-step", "42"]) == 42 + + +def test_online_eval_resumes_where_the_trainer_does(tmp_path: Path): + from prime_rl.configs.entrypoints.sft import SFTConfig + + def online_eval(resume: dict | None, **overlay): + sft = SFTConfig.model_validate( + { + "eval": {"source": [{"env": {"taskset": {"id": "reverse-text"}}}]}, + "inference": {}, + "resume": resume, + "ckpt": {"output_dir": str(tmp_path / "ckpts")}, + "output_dir": str(tmp_path), + } + ) + return sft.online_eval_config().model_copy(update=overlay) + + _touch_ckpt(tmp_path / "ckpts", 4, complete=True) + _touch_ckpt(tmp_path / "ckpts", 6, complete=False) + assert resolve_online_eval_resume_step(online_eval(None)) is None + assert resolve_online_eval_resume_step(online_eval({})) == 4 + assert resolve_online_eval_resume_step(online_eval({"step": 2})) == 2 + # An external launcher's resume_step (eval-resume.json) takes precedence. + assert resolve_online_eval_resume_step(online_eval({}, resume_step=3)) == 3 diff --git a/tests/unit/test_router_launch.py b/tests/unit/test_router_launch.py index 90de35e939e..37a003a1a18 100644 --- a/tests/unit/test_router_launch.py +++ b/tests/unit/test_router_launch.py @@ -2,21 +2,70 @@ from jinja2 import Environment, FileSystemLoader -from prime_rl.configs.inference import VllmRouterConfig +from prime_rl.components.router import router_command +from prime_rl.configs.components.router import RouterConfig, VllmRouterConfig +from prime_rl.configs.entrypoints.rl import RLConfig +from prime_rl.utils.config import cli TEMPLATES = Path(__file__).parents[2] / "src" / "prime_rl" / "templates" def _render(router: VllmRouterConfig) -> str: env = Environment(loader=FileSystemLoader(TEMPLATES), keep_trailing_newline=True) - return env.get_template("_launch_router.sh.j2").render(router=router, pd_bidirectional=None) + return env.get_template("_launch_router.sh.j2").render(router=router) + + +def test_multi_node_launchers_start_the_router_from_its_config(): + assert 'uv run router @ "$CONFIG_DIR/router.json" $worker_args' in _render(VllmRouterConfig()) def test_pd_router_retries_turns_on_connection_errors(): - script = _render(VllmRouterConfig()) - pd_line = next(line for line in script.splitlines() if "--vllm-pd-disaggregation" in line) - assert "--pd-turn-retries 2" in pd_line - assert "--pd-turn-retries 0" in _render(VllmRouterConfig(pd_turn_retries=0)) + pd = RouterConfig(prefill_urls=["http://p:1"], decode_urls=["http://d:1"]) + command = router_command(pd) + assert command[command.index("--pd-turn-retries") + 1] == "2" + pd.router.pd_turn_retries = 0 + command = router_command(pd) + assert command[command.index("--pd-turn-retries") + 1] == "0" # The regular (non-P/D) router does not take the flag. - regular_line = next(line for line in script.splitlines() if "--worker-urls" in line) - assert "--pd-turn-retries" not in regular_line + assert "--pd-turn-retries" not in router_command(RouterConfig(worker_urls=["http://w:1"])) + + +def test_multi_node_router_takes_only_the_engine_urls_at_start(tmp_path, monkeypatch): + config = RLConfig.model_validate( + { + "trainer": {}, + "orchestrator": {"train": {"source": [{"env": {"taskset": {"id": "reverse-text"}}}]}}, + "deployment": {"type": "multi_node", "num_train_nodes": 1, "num_infer_nodes": 2}, + "inference": { + "deployment": { + "type": "disaggregated", + "bidirectional_kv_transfer": {"decode_blocks_ttl_s": 300}, + }, + "router": {"type": "vllm-router", "policy": "consistent_hash"}, + }, + "slurm": {}, + } + ) + path = tmp_path / "router.json" + path.write_text(config.router_config().model_dump_json()) + flags = ["--prefill-urls", "http://p:8100", "http://p:8101", "--decode-urls", "http://d:8200"] + monkeypatch.setattr("sys.argv", ["router", "@", str(path), *flags]) + command = router_command(cli(RouterConfig)) + + assert command[command.index("--vllm-pd-disaggregation") :] == [ + "--vllm-pd-disaggregation", + "--prefill", + "http://p:8100", + "--prefill", + "http://p:8101", + "--decode", + "http://d:8200", + "--pd-turn-retries", + "2", + "--pd-bidirectional-kv", + "--pd-bidirectional-ttl-secs", + "270", + ] + for flag, value in [("--host", "0.0.0.0"), ("--port", "8000"), ("--policy", "consistent_hash")]: + assert command[command.index(flag) + 1] == value + assert command[command.index("--prometheus-port") + 1] == "29000" diff --git a/tests/unit/train/models/qwen3_5/test_model.py b/tests/unit/train/models/qwen3_5/test_model.py index a68ffb9d1d9..2f5cf213ad5 100644 --- a/tests/unit/train/models/qwen3_5/test_model.py +++ b/tests/unit/train/models/qwen3_5/test_model.py @@ -3,7 +3,7 @@ import pytest import torch -from prime_rl.configs.trainer import ModelConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.model import resolve_auto_attn from prime_rl.trainer.models import get_custom_causal_lm_cls, get_custom_vlm_cls from prime_rl.trainer.models.fusions import apply_model_fusions @@ -72,7 +72,7 @@ def get_vlm_config(text_config) -> Qwen3_5Config: def get_model(config, device="cuda", attn="auto"): - runtime_config = ModelConfig(attn=attn) + runtime_config = TrainerModelConfig(attn=attn) resolve_auto_attn(runtime_config) with torch.device(device): model = get_custom_causal_lm_cls(config).from_config( diff --git a/tests/unit/train/models/qwen3_5/test_vlm.py b/tests/unit/train/models/qwen3_5/test_vlm.py index c6ad2dea6e7..578f0f95dbb 100644 --- a/tests/unit/train/models/qwen3_5/test_vlm.py +++ b/tests/unit/train/models/qwen3_5/test_vlm.py @@ -1,7 +1,7 @@ import pytest import torch -from prime_rl.configs.trainer import ModelConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.model import resolve_auto_attn from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head from prime_rl.trainer.models.qwen3_5 import ( @@ -55,7 +55,7 @@ def get_vlm_config(): def get_model(config, device="cuda"): - runtime_config = ModelConfig() + runtime_config = TrainerModelConfig() resolve_auto_attn(runtime_config) with torch.device(device): model = Qwen3_5ForCausalLM.from_config(config, attn_implementation=runtime_config.attn, dtype=torch.bfloat16) diff --git a/tests/unit/train/models/qwen3_8_flash_next/test_vlm.py b/tests/unit/train/models/qwen3_8_flash_next/test_vlm.py index 027b7dcb41c..75af0d29bbc 100644 --- a/tests/unit/train/models/qwen3_8_flash_next/test_vlm.py +++ b/tests/unit/train/models/qwen3_8_flash_next/test_vlm.py @@ -1,7 +1,7 @@ import pytest import torch -from prime_rl.configs.trainer import ModelConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.model import resolve_auto_attn from prime_rl.trainer.models import custom_causal_lm_from_config from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head @@ -66,7 +66,7 @@ def get_vlm_config(): def get_model(config, device="cuda"): - runtime_config = ModelConfig() + runtime_config = TrainerModelConfig() resolve_auto_attn(runtime_config) with torch.device(device): model = custom_causal_lm_from_config(config, attn_implementation=runtime_config.attn, dtype=torch.bfloat16) diff --git a/tests/unit/train/models/test_checkpointing.py b/tests/unit/train/models/test_checkpointing.py index ccf49699d56..01a3082b1b5 100644 --- a/tests/unit/train/models/test_checkpointing.py +++ b/tests/unit/train/models/test_checkpointing.py @@ -7,7 +7,7 @@ from torch._dynamo.backends.common import aot_autograd from torch.utils.checkpoint import CheckpointPolicy, SelectiveCheckpointContext -from prime_rl.configs.trainer import ActivationCheckpointConfig +from prime_rl.configs.components.trainer.model import ActivationCheckpointConfig from prime_rl.trainer.activation_checkpointing import ( TokenChunkedCheckpointWrapper, _mandatory_checkpoint_policy, diff --git a/tests/unit/train/models/test_deepseek_v4.py b/tests/unit/train/models/test_deepseek_v4.py index 3daef394a29..05d072cf7d3 100644 --- a/tests/unit/train/models/test_deepseek_v4.py +++ b/tests/unit/train/models/test_deepseek_v4.py @@ -7,7 +7,7 @@ import torch.distributed as dist from torch import nn -from prime_rl.configs.trainer import ModelConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.model import load_dcp_from_hf from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention @@ -311,7 +311,7 @@ def fake_dcp_load(state_dict, storage_reader=None, process_group=None): monkeypatch.setattr("prime_rl.trainer.model.wait_for_master", lambda *args, **kwargs: None) monkeypatch.setattr("prime_rl.trainer.model.get_dcp_group", lambda: None) - load_dcp_from_hf(meta_model, ModelConfig(name=str(tmp_path))) + load_dcp_from_hf(meta_model, TrainerModelConfig(name=str(tmp_path))) torch.testing.assert_close(meta_model.model.layers[0].mlp.router.tid2eid, expected) diff --git a/tests/unit/train/models/test_moe.py b/tests/unit/train/models/test_moe.py index beb62091036..75da1110406 100644 --- a/tests/unit/train/models/test_moe.py +++ b/tests/unit/train/models/test_moe.py @@ -2,7 +2,7 @@ import torch import torch.nn.functional as F -from prime_rl.configs.trainer import ModelConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher from prime_rl.trainer.model import compute_expert_load_stats, is_tt_moe_model from prime_rl.trainer.models.fusions import fuse_gate_up_projections @@ -87,7 +87,7 @@ def test_unselected_moe_uses_bf16_without_loading_compute_backend(selection, com model = torch.nn.Module() model.model = torch.nn.Module() model.model.layers = torch.nn.ModuleList([torch.nn.Identity(), moe]) - config = ModelConfig.model_validate({"moe": {"compute": {**compute, "apply_to": selection}}}) + config = TrainerModelConfig.model_validate({"moe": {"compute": {**compute, "apply_to": selection}}}) dims = ParallelDims(dp_replicate=1, dp_shard=1, cp=1, pp=1, ep=1, world_size=1) configure_moe_runtime(model, config, dims) @@ -103,7 +103,7 @@ def test_mega_moe_dispatch_requires_expert_parallelism(): model = torch.nn.Module() model.model = torch.nn.Module() model.model.layers = torch.nn.ModuleList([moe]) - config = ModelConfig.model_validate({"moe": {"dispatch": {"type": "mega_moe"}}}) + config = TrainerModelConfig.model_validate({"moe": {"dispatch": {"type": "mega_moe"}}}) dims = ParallelDims(dp_replicate=1, dp_shard=1, cp=1, pp=1, ep=1, world_size=1) with pytest.raises(ValueError, match="expert-parallel group"): diff --git a/tests/unit/train/models/test_nemotron_h_kl.py b/tests/unit/train/models/test_nemotron_h_kl.py index acbacdda776..de43d1b7c6e 100644 --- a/tests/unit/train/models/test_nemotron_h_kl.py +++ b/tests/unit/train/models/test_nemotron_h_kl.py @@ -8,7 +8,7 @@ import pytest import torch -from prime_rl.configs.trainer import IPOLossConfig +from prime_rl.configs.components.trainer.loss import IPOLossConfig from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM from prime_rl.trainer.rl.loss import ( diff --git a/tests/unit/train/models/test_state_loading.py b/tests/unit/train/models/test_state_loading.py index 3741ca8948f..7b76f34e66e 100644 --- a/tests/unit/train/models/test_state_loading.py +++ b/tests/unit/train/models/test_state_loading.py @@ -1,7 +1,7 @@ import pytest import torch -from prime_rl.configs.trainer import ModelConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.model import load_dcp_from_hf from prime_rl.trainer.models.laguna.configuration_laguna import LagunaConfig from prime_rl.trainer.models.laguna.modeling_laguna import LagunaForCausalLM @@ -43,7 +43,7 @@ def fake_dcp_load(state_dict, storage_reader=None, process_group=None): monkeypatch.setattr("prime_rl.trainer.model.wait_for_master", lambda *args, **kwargs: None) monkeypatch.setattr("prime_rl.trainer.model.get_dcp_group", lambda: None) - load_dcp_from_hf(model, ModelConfig(name=str(tmp_path))) + load_dcp_from_hf(model, TrainerModelConfig(name=str(tmp_path))) selection_bias = model.model.layers[1].mlp.router.selection_bias torch.testing.assert_close(selection_bias.cpu(), expected.to(selection_bias.dtype)) diff --git a/tests/unit/train/models/test_vllm_parity.py b/tests/unit/train/models/test_vllm_parity.py index 95f7d1a323a..2f326adfb59 100644 --- a/tests/unit/train/models/test_vllm_parity.py +++ b/tests/unit/train/models/test_vllm_parity.py @@ -31,7 +31,7 @@ from vllm.inputs import TokensPrompt from vllm.plugins import load_general_plugins -from prime_rl.configs.trainer import ModelConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.inference.vllm.models.inkling2.configs import Inkling2LoopMMConfig, Inkling2MMConfig from prime_rl.inference.vllm.worker.weight_transfer import get_weight_model, load_weights_checkpoint_layerwise from prime_rl.trainer.model import forward, get_model, resolve_auto_attn @@ -105,7 +105,7 @@ class Case: mismatch_kl: float """Mean per-token mismatch KL allowed (the trainer's `mismatch_kl` metric), at least 2x the largest measured.""" model: dict = field(default_factory=dict) - """ModelConfig fields on top of the trainer defaults.""" + """TrainerModelConfig fields on top of the trainer defaults.""" engine: dict = field(default_factory=dict) """vLLM engine arguments on top of ENGINE_ARGS.""" post_init: Callable[[torch.nn.Module], None] | None = None @@ -632,7 +632,7 @@ def randomize(model: torch.nn.Module) -> None: def build_trainer_model(model_dir: Path, case: Case) -> torch.nn.Module: """The trainer's model, unsharded on one GPU, with fp32 master weights.""" - config = ModelConfig(name=model_dir.as_posix(), compile=None, ac=None, **case.model) + config = TrainerModelConfig(name=model_dir.as_posix(), compile=None, ac=None, **case.model) resolve_auto_attn(config) model = get_model(config, dtype=torch.float32) apply_model_fusions(model, config.fusions.enabled) diff --git a/tests/unit/train/pretrain/test_token_data.py b/tests/unit/train/pretrain/test_token_data.py index 4f3d5433c64..f802ded0b27 100644 --- a/tests/unit/train/pretrain/test_token_data.py +++ b/tests/unit/train/pretrain/test_token_data.py @@ -8,7 +8,7 @@ import torch import prime_rl.trainer.pretrain.data as pretrain_data -from prime_rl.configs.pretrain import PretrainDataConfig +from prime_rl.configs.components.trainer.data import PretrainDataConfig from prime_rl.trainer.data import setup_dataloader, with_workers from prime_rl.trainer.pretrain.data import ( TokenShards, diff --git a/tests/unit/train/rl/test_fused_lm_head.py b/tests/unit/train/rl/test_fused_lm_head.py index a17a0b70d15..1a0d1377f35 100644 --- a/tests/unit/train/rl/test_fused_lm_head.py +++ b/tests/unit/train/rl/test_fused_lm_head.py @@ -5,7 +5,7 @@ import torch from transformers.models.qwen3.configuration_qwen3 import Qwen3Config -from prime_rl.configs.trainer import IcePopLossConfig +from prime_rl.configs.components.trainer.loss import IcePopLossConfig from prime_rl.trainer.models import cast_float_and_contiguous from prime_rl.trainer.models.layers.lm_head import ( FusedOutputLinear, diff --git a/tests/unit/train/rl/test_loss.py b/tests/unit/train/rl/test_loss.py index af4de6e0635..1f09ef7a788 100644 --- a/tests/unit/train/rl/test_loss.py +++ b/tests/unit/train/rl/test_loss.py @@ -1,11 +1,7 @@ import pytest import torch -from prime_rl.configs.trainer import ( - CustomLossConfig, - IcePopLossConfig, - IPOLossConfig, -) +from prime_rl.configs.components.trainer.loss import CustomLossConfig, IcePopLossConfig, IPOLossConfig from prime_rl.trainer.models.layers.lm_head import TokenSupport from prime_rl.trainer.rl.loss import ( IcePopLoss, diff --git a/tests/unit/train/sft/test_dataloader.py b/tests/unit/train/sft/test_dataloader.py index c19321d6dd2..b03e5bc1888 100644 --- a/tests/unit/train/sft/test_dataloader.py +++ b/tests/unit/train/sft/test_dataloader.py @@ -5,7 +5,7 @@ import torch from datasets import Dataset -from prime_rl.configs.sft import SFTDataConfig +from prime_rl.configs.components.trainer.data import SFTDataConfig from prime_rl.trainer.data import get_dataset_progress, get_dataset_state, setup_dataloader, with_workers from prime_rl.trainer.sft.data import FakeSource, HFSource, SFTDataset diff --git a/tests/unit/train/sft/test_fake_dataset.py b/tests/unit/train/sft/test_fake_dataset.py index b4f16c7ca0a..f3290e09873 100644 --- a/tests/unit/train/sft/test_fake_dataset.py +++ b/tests/unit/train/sft/test_fake_dataset.py @@ -65,7 +65,7 @@ def make(data_rank: int) -> SFTDataset: def test_data_fake_replaces_the_sources_and_needs_no_renderer(): from types import SimpleNamespace - from prime_rl.configs.sft import SFTDataConfig + from prime_rl.configs.components.trainer.data import SFTDataConfig from prime_rl.trainer.sft.data import setup_sft_dataset config = SFTDataConfig(fake={"input_ids": "increasing"}, seq_len=16) diff --git a/tests/unit/train/sft/test_prime_monitor.py b/tests/unit/train/sft/test_prime_monitor.py index a555b20110b..ee4414798de 100644 --- a/tests/unit/train/sft/test_prime_monitor.py +++ b/tests/unit/train/sft/test_prime_monitor.py @@ -12,7 +12,7 @@ import pytest from prime_rl import monitors -from prime_rl.configs.sft import SFTConfig +from prime_rl.configs.entrypoints.sft import SFTConfig from prime_rl.monitors.prime import PrimeMonitor @@ -151,13 +151,12 @@ def test_online_evals_share_the_launchers_run(sdk_runs, tmp_path): """The sft launcher registers the run and makes its id the run identity; the trainer and the online-eval process attach to it and only flush. The launcher finishes the run once both exited.""" - from prime_rl.entrypoints.launcher import build_online_eval_config from prime_rl.monitors.prime import launch_run config = _sft_config( {"eval": {"interval": 50, "source": [{"name": "rev", "env": {"taskset": {"id": "harbor"}}}]}, "inference": {}} ) - eval_config = build_online_eval_config(config) + eval_config = config.online_eval_config() # Same run dir: dashboard visibility for the eval artifacts. assert eval_config.output_dir == config.run_dir @@ -196,12 +195,12 @@ def test_slurm_run_owner_fails_the_run_with_its_step(sdk_runs, tmp_path, monkeyp its id to the step, and finishes the run when the step succeeds or fails it when the step fails.""" from prime_rl.entrypoints import run_owner - from prime_rl.entrypoints.launcher import write_config + from prime_rl.utils.pathing import write_config monkeypatch.setenv("RUN_ID", "") monkeypatch.setattr(run_owner.signal, "signal", lambda *args: None) path = tmp_path / "sft.json" - write_config(_sft_config(), path) + write_config(path, _sft_config()) monkeypatch.setattr(run_owner.sys, "argv", ["prime", "sft", str(path), *command]) if code: diff --git a/tests/unit/train/sft/test_sft_dataset.py b/tests/unit/train/sft/test_sft_dataset.py index 7e084456bee..98baada187d 100644 --- a/tests/unit/train/sft/test_sft_dataset.py +++ b/tests/unit/train/sft/test_sft_dataset.py @@ -482,7 +482,7 @@ def custom_renderer_config(tmp_path): def test_source_renderer_kwargs_apply_to_that_source_only(custom_renderer_config): - from prime_rl.configs.sft import SFTDataConfig + from prime_rl.configs.components.trainer.data import SFTDataConfig config = SFTDataConfig( source=[ @@ -548,7 +548,7 @@ def test_renderer_resolver_rejects_renderer_columns_without_the_field(): def test_sft_dataset_reads_mapped_message_columns(dummy_renderer): - from prime_rl.configs.sft import SFTColumnsConfig + from prime_rl.configs.components.trainer.data import SFTColumnsConfig dataset = Dataset.from_list([{"conversation": [{"role": "assistant", "content": "a0"}]}]) @@ -565,7 +565,7 @@ def test_sft_dataset_reads_mapped_message_columns(dummy_renderer): def test_sft_dataset_passes_tools_through_from_the_mapped_column(dummy_renderer): - from prime_rl.configs.sft import SFTColumnsConfig + from prime_rl.configs.components.trainer.data import SFTColumnsConfig tools = [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}] dataset = Dataset.from_list( @@ -592,7 +592,7 @@ def get_stop_token_ids(self): @pytest.mark.parametrize("column", ["message_loss_mask", "selection"]) @pytest.mark.parametrize("mask", [None, [True, True, True, True], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]]) def test_sft_message_selection(model, layout, column, mask): - from prime_rl.configs.sft import SFTColumnsConfig + from prime_rl.configs.components.trainer.data import SFTColumnsConfig tokenizer = AutoTokenizer.from_pretrained(model) renderer = create_renderer(tokenizer) diff --git a/tests/unit/train/test_ckpt.py b/tests/unit/train/test_ckpt.py index 26bec6de98b..67b23e48f39 100644 --- a/tests/unit/train/test_ckpt.py +++ b/tests/unit/train/test_ckpt.py @@ -7,7 +7,8 @@ import torch import torch.distributed as dist -from prime_rl.configs.trainer import CheckpointConfig, LinearSchedulerConfig, SchedulerConfig +from prime_rl.configs.components.trainer.ckpt import TrainerCheckpointConfig +from prime_rl.configs.components.trainer.optim import LinearSchedulerConfig, SchedulerConfig from prime_rl.trainer.ckpt import CheckpointManager, ModelFiles, Progress from prime_rl.trainer.scheduler import setup_scheduler from prime_rl.trainer.utils import get_dcp_group @@ -25,7 +26,7 @@ def test_keep_last_ignores_a_step_cut_off_mid_write(tmp_path): for step in (1, 2): (get_step_path(ckpt_dir, step) / "trainer" / ".metadata").touch() - manager = CheckpointManager(tmp_path, CheckpointConfig(keep_last=1), Mock(spec=ModelFiles)) + manager = CheckpointManager(tmp_path, TrainerCheckpointConfig(keep_last=1), Mock(spec=ModelFiles)) manager.maybe_clean() assert manager.ckpt_steps == [2] @@ -111,8 +112,8 @@ def test_resume_trains_with_the_config(tmp_path, process_group, saved, resumed, """A resume trains with the hyperparameters and the schedule of its config, as a run with that config set up at the resume step does, and warns of the changed param group values when it loads the optimizer state.""" model_files = Mock(spec=ModelFiles, config=None) - train(saved, None, CheckpointManager(tmp_path, CheckpointConfig(), model_files)) - manager = CheckpointManager(tmp_path, CheckpointConfig(skip_optimizer=skip_optimizer), model_files) + train(saved, None, CheckpointManager(tmp_path, TrainerCheckpointConfig(), model_files)) + manager = CheckpointManager(tmp_path, TrainerCheckpointConfig(skip_optimizer=skip_optimizer), model_files) result = train(resumed, RESUME_STEP, manager) expected = train(resumed, RESUME_STEP) assert result["groups"] == expected["groups"] @@ -137,8 +138,8 @@ def test_resume_rejects_optimizer_state_of_other_param_groups(tmp_path, process_ """A resume that loads the optimizer state raises when the param groups changed in number or algorithm; with ckpt.skip_optimizer it trains.""" model_files = Mock(spec=ModelFiles, config=None) - train(saved, None, CheckpointManager(tmp_path, CheckpointConfig(), model_files)) + train(saved, None, CheckpointManager(tmp_path, TrainerCheckpointConfig(), model_files)) with pytest.raises(ValueError, match=error): - train(resumed, RESUME_STEP, CheckpointManager(tmp_path, CheckpointConfig(), model_files)) - manager = CheckpointManager(tmp_path, CheckpointConfig(skip_optimizer=True), model_files) + train(resumed, RESUME_STEP, CheckpointManager(tmp_path, TrainerCheckpointConfig(), model_files)) + manager = CheckpointManager(tmp_path, TrainerCheckpointConfig(skip_optimizer=True), model_files) assert train(resumed, RESUME_STEP, manager)["lrs"] == train(resumed, RESUME_STEP)["lrs"] diff --git a/tests/unit/train/test_ckpt_remote.py b/tests/unit/train/test_ckpt_remote.py index ab5d5b9e1d4..ff0d545c202 100644 --- a/tests/unit/train/test_ckpt_remote.py +++ b/tests/unit/train/test_ckpt_remote.py @@ -9,8 +9,8 @@ from obstore.store import LocalStore from torch import nn -from prime_rl.configs.shared import ResumeConfig -from prime_rl.configs.trainer import CheckpointConfig, RemoteCheckpointConfig +from prime_rl.configs.blocks.ckpt import ResumeConfig +from prime_rl.configs.components.trainer.ckpt import RemoteCheckpointConfig, TrainerCheckpointConfig from prime_rl.entrypoints.rl import validate_remote_resume from prime_rl.trainer.ckpt import CheckpointManager, ModelFiles, Progress from prime_rl.trainer.ckpt_sync import get_remote_steps @@ -35,11 +35,13 @@ def remote_dir(tmp_path: Path) -> Path: @pytest.fixture -def config(remote_dir: Path) -> CheckpointConfig: - return CheckpointConfig(remote=RemoteCheckpointConfig(dir=f"file://{remote_dir}")) +def config(remote_dir: Path) -> TrainerCheckpointConfig: + return TrainerCheckpointConfig(remote=RemoteCheckpointConfig(dir=f"file://{remote_dir}")) -def make_manager(output_dir: Path, config: CheckpointConfig, resume: ResumeConfig | None = None) -> CheckpointManager: +def make_manager( + output_dir: Path, config: TrainerCheckpointConfig, resume: ResumeConfig | None = None +) -> CheckpointManager: return CheckpointManager(output_dir, config, Mock(spec=ModelFiles, config=None), resume) @@ -62,7 +64,7 @@ def save(manager: CheckpointManager, *steps: int, clean: bool = False) -> None: manager.close() -def test_resumes_from_remote_when_disk_is_empty(tmp_path: Path, config: CheckpointConfig) -> None: +def test_resumes_from_remote_when_disk_is_empty(tmp_path: Path, config: TrainerCheckpointConfig) -> None: model, optimizer = make_trained(seed=0) save(make_manager(tmp_path / "run", config), 3) manager = make_manager(tmp_path / "fresh", config, ResumeConfig()) @@ -76,7 +78,7 @@ def test_resumes_from_remote_when_disk_is_empty(tmp_path: Path, config: Checkpoi assert all(torch.equal(a, b) for a, b in zip(model.state_dict().values(), resumed_model.state_dict().values())) -def test_save_raises_once_the_sync_process_died(tmp_path: Path, config: CheckpointConfig) -> None: +def test_save_raises_once_the_sync_process_died(tmp_path: Path, config: TrainerCheckpointConfig) -> None: manager = make_manager(tmp_path / "run", config) manager.sync.kill() manager.sync.wait() @@ -85,16 +87,18 @@ def test_save_raises_once_the_sync_process_died(tmp_path: Path, config: Checkpoi save(manager, 3) -def test_fresh_run_refuses_a_remote_with_steps(tmp_path: Path, config: CheckpointConfig) -> None: +def test_fresh_run_refuses_a_remote_with_steps(tmp_path: Path, config: TrainerCheckpointConfig) -> None: save(make_manager(tmp_path / "run", config), 3) with pytest.raises(FileExistsError, match="--resume"): make_manager(tmp_path / "other", config) -def test_disk_and_remote_keep_their_own_last_steps(tmp_path: Path, config: CheckpointConfig, remote_dir: Path) -> None: +def test_disk_and_remote_keep_their_own_last_steps( + tmp_path: Path, config: TrainerCheckpointConfig, remote_dir: Path +) -> None: # Step 10 was saved before the remote was turned on, so it is only on disk - save(make_manager(tmp_path / "run", CheckpointConfig()), 10) + save(make_manager(tmp_path / "run", TrainerCheckpointConfig()), 10) config.keep_last, config.remote.keep_last = 1, 2 save(make_manager(tmp_path / "run", config, ResumeConfig()), 20, 30, 40, clean=True) @@ -104,7 +108,7 @@ def test_disk_and_remote_keep_their_own_last_steps(tmp_path: Path, config: Check def test_remote_steps_past_the_resume_step_take_no_keep_last_slot( - tmp_path: Path, config: CheckpointConfig, remote_dir: Path + tmp_path: Path, config: TrainerCheckpointConfig, remote_dir: Path ) -> None: save(make_manager(tmp_path / "run", config), 3, 5) config.remote.keep_last = 1 @@ -114,7 +118,9 @@ def test_remote_steps_past_the_resume_step_take_no_keep_last_slot( assert get_remote_steps(LocalStore(remote_dir))[1] == {4, 5} -def test_resume_takes_the_later_of_the_disk_step_and_the_remote(tmp_path: Path, config: CheckpointConfig) -> None: +def test_resume_takes_the_later_of_the_disk_step_and_the_remote( + tmp_path: Path, config: TrainerCheckpointConfig +) -> None: save(make_manager(tmp_path / "run", config), 3) manager = make_manager(tmp_path / "run", config, ResumeConfig()) @@ -129,7 +135,7 @@ def test_resume_takes_the_later_of_the_disk_step_and_the_remote(tmp_path: Path, [(None, pytest.raises(ValueError)), (2, pytest.raises(ValueError)), (3, nullcontext())], ) def test_rl_resume_fails_fast_when_remote_is_ahead_of_disk( - tmp_path: Path, config: CheckpointConfig, disk_step: int | None, expectation + tmp_path: Path, config: TrainerCheckpointConfig, disk_step: int | None, expectation ) -> None: save(make_manager(tmp_path / "run", config), 3) diff --git a/tests/unit/train/test_compile.py b/tests/unit/train/test_compile.py index 16a8006b5a7..02d52312b82 100644 --- a/tests/unit/train/test_compile.py +++ b/tests/unit/train/test_compile.py @@ -42,7 +42,8 @@ from torch._dynamo.utils import clear_compilation_metrics, counters, get_compilation_metrics import prime_rl._compat # noqa: F401 -from prime_rl.configs.trainer import ModelConfig, TokenizerConfig +from prime_rl.configs.blocks.model import TokenizerConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.model import setup_model, setup_tokenizer from prime_rl.trainer.parallel_dims import ParallelDims, get_parallel_dims from prime_rl.trainer.rl.warmup import warmup_routed_experts @@ -184,7 +185,7 @@ def num_layer_graphs(model: torch.nn.Module) -> int: def run_step( - config: ModelConfig, parallel_dims: ParallelDims, rows: list[dict], router_replay: bool, progress: dict + config: TrainerModelConfig, parallel_dims: ParallelDims, rows: list[dict], router_replay: bool, progress: dict ) -> dict: """One forward and backward of this rank's row through the trainer's model, with its summed loss and grad norm. `progress` holds the stage reached and the number of graphs the decoder layers compile to, also when the step @@ -222,7 +223,9 @@ def failures(result: dict) -> list[str]: return found -def compile_case(config: ModelConfig, parallel_dims: ParallelDims, rows: list[dict], router_replay: bool) -> dict: +def compile_case( + config: TrainerModelConfig, parallel_dims: ParallelDims, rows: list[dict], router_replay: bool +) -> dict: torch._dynamo.reset() counters.clear() clear_compilation_metrics() diff --git a/tests/unit/train/test_distributed_invariance.py b/tests/unit/train/test_distributed_invariance.py index 987fcc4da8a..6fffecc5df9 100644 --- a/tests/unit/train/test_distributed_invariance.py +++ b/tests/unit/train/test_distributed_invariance.py @@ -36,7 +36,8 @@ from tiny_models import TOKENIZER, Case, compute_loss, load_rows, model_config, save_tiny_model from torch.distributed.tensor import DTensor -from prime_rl.configs.trainer import ModelConfig, TokenizerConfig +from prime_rl.configs.blocks.model import TokenizerConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.model import get_model, load_dcp_from_hf, setup_model, setup_tokenizer from prime_rl.trainer.models.fusions import apply_model_fusions from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head @@ -135,7 +136,7 @@ def unwrapped_name(name: str) -> str: return name.replace("_checkpoint_wrapped_module.", "") -def run_reference(config: ModelConfig, rows: list[dict]) -> dict: +def run_reference(config: TrainerModelConfig, rows: list[dict]) -> dict: """All rows through an unsharded model in bf16 (FSDP's compute dtype), accumulating gradients in fp32. Parameters that get no gradient, like the indexers, which reach the loss only through top-k indices, have no entry. Also returns the experts each row routed to, which the cases replay.""" @@ -170,7 +171,7 @@ def run_reference(config: ModelConfig, rows: list[dict]) -> dict: return {"loss": loss_sum / num_tokens, "grad_norm": grad_norm.item(), "grads": grads, "routes": routes} -def run_case(config: ModelConfig, parallel_dims, rows: list[dict], routes: list[torch.Tensor | None]) -> dict: +def run_case(config: TrainerModelConfig, parallel_dims, rows: list[dict], routes: list[torch.Tensor | None]) -> dict: """One SFT trainer step up to the optimizer: forward and backward over this rank's rows, then the gradient scaling and norm of the trainer loop. MoE models replay the reference's routing of each row.""" model = setup_model(config, parallel_dims) diff --git a/tests/unit/train/test_model.py b/tests/unit/train/test_model.py index d671588290b..3e63de51fc7 100644 --- a/tests/unit/train/test_model.py +++ b/tests/unit/train/test_model.py @@ -2,7 +2,7 @@ import torch import torch.distributed as dist -from prime_rl.configs.trainer import AttnImplementation, DebugModelConfig, ModelConfig +from prime_rl.configs.components.trainer.model import AttnImplementation, DebugModelConfig, TrainerModelConfig from prime_rl.trainer.model import get_model, load_dcp_from_hf from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head from prime_rl.utils.utils import get_free_port @@ -26,7 +26,7 @@ def process_group(): dist.destroy_process_group() -def load_model(config: ModelConfig) -> torch.nn.Module: +def load_model(config: TrainerModelConfig) -> torch.nn.Module: """Build on the meta device and load the checkpoint, as the trainer does.""" model = get_model(config) # Mirror setup_model: the custom Qwen3 forward calls lm_head with @@ -55,7 +55,7 @@ def attn(request) -> AttnImplementation: @pytest.fixture def model(attn): - return load_model(ModelConfig(name="Qwen/Qwen3-0.6B", attn=attn)) + return load_model(TrainerModelConfig(name="Qwen/Qwen3-0.6B", attn=attn)) def test_model_to_gpu(model): @@ -89,7 +89,7 @@ def test_model_with_position_ids(model): def test_moe_custom_impl(): - model = get_model(ModelConfig(name="PrimeIntellect/GLM-0.5B", attn="flash_attention_2")) + model = get_model(TrainerModelConfig(name="PrimeIntellect/GLM-0.5B", attn="flash_attention_2")) inject_prime_lm_head(model, chunk_size=None) model.to_empty(device="cuda") model.tie_weights() diff --git a/tests/unit/train/test_model_sources.py b/tests/unit/train/test_model_sources.py index c0468a1b547..0049afd6b12 100644 --- a/tests/unit/train/test_model_sources.py +++ b/tests/unit/train/test_model_sources.py @@ -1,7 +1,8 @@ import pytest from transformers import AutoTokenizer, Qwen3Config -from prime_rl.configs.trainer import ModelConfig, TokenizerConfig +from prime_rl.configs.blocks.model import TokenizerConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.model import check_ckpt_dir, setup_tokenizer, use_resumed_model_files from prime_rl.utils.pathing import is_checkpoint_step_dir @@ -13,9 +14,9 @@ def test_a_checkpoint_step_dir_is_recognized_and_needs_a_config_json(tmp_path): assert is_checkpoint_step_dir(step_dir) assert not is_checkpoint_step_dir(tmp_path / "hf") and not is_checkpoint_step_dir("Qwen/Qwen3-0.6B") with pytest.raises(FileNotFoundError, match="has no config.json"): - check_ckpt_dir(ModelConfig(name=str(step_dir))) + check_ckpt_dir(TrainerModelConfig(name=str(step_dir))) Qwen3Config().save_pretrained(step_dir) - check_ckpt_dir(ModelConfig(name=str(step_dir))) + check_ckpt_dir(TrainerModelConfig(name=str(step_dir))) def test_a_model_name_without_a_tokenizer_asks_for_tokenizer_name(tmp_path): @@ -28,7 +29,7 @@ def test_a_model_name_without_a_tokenizer_asks_for_tokenizer_name(tmp_path): def test_a_run_from_a_checkpoint_resumes_with_the_files_of_its_own_checkpoint(tmp_path): source, step_dir = tmp_path / "source" / "step_5", tmp_path / "run" / "step_2" - model = ModelConfig(name=str(source)) + model = TrainerModelConfig(name=str(source)) tokenizer = TokenizerConfig(name=str(source)) use_resumed_model_files(model, tokenizer, step_dir) # a checkpoint without config.json assert model.name == tokenizer.name == str(source) diff --git a/tests/unit/train/test_offload_checkpoint.py b/tests/unit/train/test_offload_checkpoint.py index c9485b65a99..9def12b86c1 100644 --- a/tests/unit/train/test_offload_checkpoint.py +++ b/tests/unit/train/test_offload_checkpoint.py @@ -45,17 +45,15 @@ from torch.distributed.checkpoint.state_dict import get_model_state_dict from torch.distributed.tensor import DTensor -from prime_rl.configs.trainer import ( - ActivationOffloadingConfig, +from prime_rl.configs.blocks.model import TokenizerConfig +from prime_rl.configs.components.trainer.ckpt import TrainerCheckpointConfig +from prime_rl.configs.components.trainer.model import ActivationOffloadingConfig, OffloadMode, TrainerModelConfig +from prime_rl.configs.components.trainer.optim import ( AdamWConfig, - CheckpointConfig, ConstantSchedulerConfig, CosineSchedulerConfig, - ModelConfig, MuonConfig, - OffloadMode, SignSGDConfig, - TokenizerConfig, ) from prime_rl.trainer.ckpt import AppState, CheckpointManager, Progress, setup_model_files from prime_rl.trainer.micro_batches import run_micro_batches @@ -105,8 +103,8 @@ class Setup: freeze_moe_router: bool = False async_save: bool = False - def model_config(self, models_dir: Path) -> ModelConfig: - config = ModelConfig( + def model_config(self, models_dir: Path) -> TrainerModelConfig: + config = TrainerModelConfig( name=(models_dir / self.model).as_posix(), cp=self.cp, ep=self.ep, @@ -258,7 +256,7 @@ def prepare(self, models: set[str]) -> None: compute_loss(model, row, cp_rank=0, cp_size=1) self.rows[name].append({**row, "routed_experts": routing()}) - def parallel_dims(self, config: ModelConfig) -> ParallelDims: + def parallel_dims(self, config: TrainerModelConfig) -> ParallelDims: # Device meshes are made once per layout, as in a trainer process if (config.cp, config.ep) not in self.layouts: self.layouts[config.cp, config.ep] = get_parallel_dims(config) @@ -285,7 +283,9 @@ def ckpt_dir(self, setup: Setup) -> Path: def ckpt_manager(self, setup: Setup) -> CheckpointManager: model_files = setup_model_files(setup.model_config(self.models_dir), self.tokenizer, processor=None) - return CheckpointManager(self.ckpt_dir(setup), CheckpointConfig(async_save=setup.async_save), model_files) + return CheckpointManager( + self.ckpt_dir(setup), TrainerCheckpointConfig(async_save=setup.async_save), model_files + ) def save(self, run: "Run", until: int) -> tuple[CheckpointManager, dict]: """Train `run` up to step `until`, saving after SAVE_STEP. Returns the checkpoint and the hashed state it saved, diff --git a/tests/unit/train/test_scheduler.py b/tests/unit/train/test_scheduler.py index fc35ab2d745..c8ca29c54c2 100644 --- a/tests/unit/train/test_scheduler.py +++ b/tests/unit/train/test_scheduler.py @@ -3,7 +3,7 @@ import pytest import torch -from prime_rl.configs.trainer import ( +from prime_rl.configs.components.trainer.optim import ( ConstantSchedulerConfig, CosineSchedulerConfig, LinearSchedulerConfig, diff --git a/tests/unit/train/test_state_offload.py b/tests/unit/train/test_state_offload.py index 509d7a013e4..cc355a00df2 100644 --- a/tests/unit/train/test_state_offload.py +++ b/tests/unit/train/test_state_offload.py @@ -10,7 +10,7 @@ from torch.distributed.checkpoint import save as dcp_save from torch.optim import Optimizer -from prime_rl.configs.trainer import CheckpointConfig +from prime_rl.configs.components.trainer.ckpt import TrainerCheckpointConfig from prime_rl.trainer.ckpt import AppState, CheckpointManager, ModelFiles, PinnedStager, Progress from prime_rl.trainer.optim.muon import Muon from prime_rl.trainer.optim.state_offload import CPUOffloadOptimizer @@ -166,7 +166,7 @@ def test_offloaded_async_save_writes_after_it_returned(tmp_path) -> None: model = make_model(0) optimizer = CPUOffloadOptimizer(torch.optim.AdamW(model.parameters(), lr=1e-2)) run_steps(model, optimizer, num_steps=1, seed=1) - manager = CheckpointManager(tmp_path, CheckpointConfig(async_save=True), Mock(spec=ModelFiles)) + manager = CheckpointManager(tmp_path, TrainerCheckpointConfig(async_save=True), Mock(spec=ModelFiles)) manager.stager = PinnedStager() manager.write_group = dist.new_group(backend="gloo") manager.writer = ThreadPoolExecutor(max_workers=1) diff --git a/tests/unit/train/test_val.py b/tests/unit/train/test_val.py index 10aa38be4b5..000fb119744 100644 --- a/tests/unit/train/test_val.py +++ b/tests/unit/train/test_val.py @@ -4,7 +4,7 @@ import pytest from transformers import AutoTokenizer -from prime_rl.configs.supervised import DocumentsValSetConfig +from prime_rl.configs.components.trainer.data import DocumentsValSetConfig from prime_rl.trainer.models.layers.lm_head import IGNORE_INDEX from prime_rl.trainer.val import documents_set, rank_rows, token_byte_lengths diff --git a/tests/unit/train/tiny_models.py b/tests/unit/train/tiny_models.py index 93973d6e88d..fc5b9bc09fd 100644 --- a/tests/unit/train/tiny_models.py +++ b/tests/unit/train/tiny_models.py @@ -8,8 +8,8 @@ from renderers import AutoRendererConfig from transformers import AutoModelForCausalLM, Glm4MoeConfig, LlamaConfig, PretrainedConfig, Qwen3Config, Qwen3MoeConfig -from prime_rl.configs.sft import SFTDataConfig -from prime_rl.configs.trainer import CompileConfig, ModelConfig +from prime_rl.configs.components.trainer.data import SFTDataConfig +from prime_rl.configs.components.trainer.model import CompileConfig, TrainerModelConfig from prime_rl.trainer.data import setup_dataloader from prime_rl.trainer.model import forward, resolve_auto_attn from prime_rl.trainer.models import get_custom_causal_lm_cls @@ -329,14 +329,14 @@ class Case: """torch.compile costs seconds per case, so few cases turn it on.""" fullgraph: bool = False overrides: dict = field(default_factory=dict) - """ModelConfig fields on top of the trainer defaults (full AC with activation offloading, fusions).""" + """TrainerModelConfig fields on top of the trainer defaults (full AC with activation offloading, fusions).""" tolerances: dict = field(default_factory=dict) """Tolerances on top of the invariance test's defaults, each measured for this case.""" -def model_config(case: Case, models_dir: Path) -> ModelConfig: - # SFT does not freeze the router, and the ModelConfig default "auto" is resolved by the trainer config - config = ModelConfig( +def model_config(case: Case, models_dir: Path) -> TrainerModelConfig: + # SFT does not freeze the router, and the TrainerModelConfig default "auto" is resolved by the trainer config + config = TrainerModelConfig( name=(models_dir / case.model).as_posix(), cp=case.cp, ep=case.ep, diff --git a/tests/unit/transports/test_batch_transport.py b/tests/unit/transports/test_batch_transport.py index 5a5024334e9..33d3a135011 100644 --- a/tests/unit/transports/test_batch_transport.py +++ b/tests/unit/transports/test_batch_transport.py @@ -2,7 +2,7 @@ import time from pathlib import Path -from prime_rl.configs.shared import ZMQTransportConfig +from prime_rl.configs.blocks.transport import ZMQTransportConfig from prime_rl.transports.batch import BatchReceiver, BatchSender from prime_rl.transports.batch.types import SampleRef, StepBatch from prime_rl.utils.utils import get_free_port diff --git a/tests/unit/utils/test_dcp_export.py b/tests/unit/utils/test_dcp_export.py index dfa7fb6e046..97ef210111c 100644 --- a/tests/unit/utils/test_dcp_export.py +++ b/tests/unit/utils/test_dcp_export.py @@ -15,7 +15,8 @@ from torch.distributed.checkpoint.metadata import ChunkStorageMetadata, MetadataIndex, TensorStorageMetadata from transformers import PretrainedConfig, PreTrainedTokenizerFast -from prime_rl.configs.trainer import ModelConfig, TokenizerConfig +from prime_rl.configs.blocks.model import TokenizerConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.model import get_model from prime_rl.trainer.models.layers.ngram import LAYOUT_BUFFERS from prime_rl.trainer.models.qwen3_8_flash_next import Qwen3_8FlashNextForCausalLM, Qwen3_8FlashNextTextConfig @@ -307,7 +308,7 @@ def test_model_assets_carry_the_source_generation_config(tmp_path, exporter, sou (model_dir / "generation_config.json").write_text(json.dumps({"eos_token_id": [0, 1], "top_p": 0.95})) tokenizer = Tokenizer(WordLevel({"": 0, "a": 1}, unk_token="")) PreTrainedTokenizerFast(tokenizer_object=tokenizer, eos_token="").save_pretrained(model_dir) - model_config = ModelConfig(name=str(model_dir), attn="flash_attention_2") + model_config = TrainerModelConfig(name=str(model_dir), attn="flash_attention_2") model = get_model(model_config, dtype=torch.float32) output = tmp_path / "export" exporter.save_model_assets(model, model_config, TokenizerConfig(), output) @@ -358,7 +359,7 @@ def test_convert_exports_a_run_checkpoint_end_to_end(tmp_path, exporter, monkeyp run_config = {"model": {"name": str(model_dir)}, "tokenizer": {}} (config_dir / "trainer.json").write_text(json.dumps(run_config)) # The run config keeps attn=auto, which the exporter must resolve without a GPU. - model_config = ModelConfig(**run_config["model"], attn="flash_attention_2") + model_config = TrainerModelConfig(**run_config["model"], attn="flash_attention_2") model = get_model(model_config, dtype=torch.float32) state = { name: torch.randn(tensor.shape) if tensor.is_floating_point() else torch.zeros(tensor.shape, dtype=tensor.dtype) diff --git a/tests/unit/utils/test_links.py b/tests/unit/utils/test_links.py index 132f7d5e978..af09baf9785 100644 --- a/tests/unit/utils/test_links.py +++ b/tests/unit/utils/test_links.py @@ -4,7 +4,7 @@ import pytest -from prime_rl.configs.monitors import PrimeMonitorConfig, WandbMonitorConfig +from prime_rl.configs.blocks.monitors import PrimeMonitorConfig, WandbMonitorConfig from prime_rl.monitors.prime import PrimeMonitor from prime_rl.monitors.wandb.monitor import WandbMonitor from prime_rl.utils.links import ATTEMPT_VAR, publish_link, register_links, wait_for_links diff --git a/tools/convert_bf16_to_fp8.py b/tools/convert_bf16_to_fp8.py index 2d91c805abb..b9ce414bc9c 100644 --- a/tools/convert_bf16_to_fp8.py +++ b/tools/convert_bf16_to_fp8.py @@ -26,7 +26,7 @@ # Module-name substrings that stay unquantized: norms, embeddings, output head, # MoE router gates, GatedDeltaNet low-rank projections, MTP/indexer projections, # vision tower. Mirrors the trainer's _DEFAULT_FP8_IGNORE_PATTERNS -# (configs/trainer.py), adapted to HF checkpoint names. +# (configs/components/trainer.py), adapted to HF checkpoint names. SKIP_SUBSTRINGS = ( "norm", "embed", diff --git a/tools/convert_dcp_to_bf16.py b/tools/convert_dcp_to_bf16.py index 2f8b6dcf7ca..878688e83d2 100644 --- a/tools/convert_dcp_to_bf16.py +++ b/tools/convert_dcp_to_bf16.py @@ -22,7 +22,8 @@ from transformers import PretrainedConfig from transformers.utils import SAFE_WEIGHTS_INDEX_NAME -from prime_rl.configs.trainer import ModelConfig, TokenizerConfig +from prime_rl.configs.blocks.model import TokenizerConfig +from prime_rl.configs.components.trainer.model import TrainerModelConfig from prime_rl.trainer.ckpt import load_generation_config from prime_rl.trainer.model import get_model, setup_tokenizer from prime_rl.trainer.models.base import PreTrainedModelPrimeRL @@ -47,7 +48,7 @@ def resolve_dcp_dir(ckpt_dir: Path) -> Path: raise FileNotFoundError(f"No DCP checkpoint found at {ckpt_dir}") -def resolve_run_configs(step_dir: Path) -> tuple[ModelConfig, TokenizerConfig]: +def resolve_run_configs(step_dir: Path) -> tuple[TrainerModelConfig, TokenizerConfig]: logger = get_logger() config_dir = get_config_dir(step_dir.parent.parent) for name in RUN_CONFIG_NAMES: @@ -67,11 +68,11 @@ def resolve_run_configs(step_dir: Path) -> tuple[ModelConfig, TokenizerConfig]: for key in ("init", "init_from"): model.pop(key, None) model.get("debug", {}).pop("random_init", None) - return ModelConfig(**model), TokenizerConfig(**tokenizer) + return TrainerModelConfig(**model), TokenizerConfig(**tokenizer) raise FileNotFoundError(f"No resolved run config ({' or '.join(RUN_CONFIG_NAMES)}) found under {config_dir}") -def check_not_lora(model_config: ModelConfig, metadata: Metadata) -> None: +def check_not_lora(model_config: TrainerModelConfig, metadata: Metadata) -> None: if model_config.lora is not None: raise ValueError("LoRA checkpoints are not supported - CPU export supports full fine-tunes only") lora_keys = [ @@ -86,7 +87,7 @@ class Checkpoint: dcp_dir: Path metadata: Metadata model: nn.Module - model_config: ModelConfig + model_config: TrainerModelConfig tokenizer_config: TokenizerConfig @@ -264,7 +265,7 @@ def _export_config(config: PretrainedConfig) -> None: def save_model_assets( - model: nn.Module, model_config: ModelConfig, tokenizer_config: TokenizerConfig, output_dir: Path + model: nn.Module, model_config: TrainerModelConfig, tokenizer_config: TokenizerConfig, output_dir: Path ) -> None: """Save model config, generation config, processor and tokenizer next to the weights.""" _export_config(model.config)