Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3309613436 | ||
|
|
8793c37118 | ||
|
|
ae28fb70c5 | ||
|
|
2ff7f53d47 | ||
|
|
c13a7ec75b | ||
|
|
ee058677f2 | ||
|
|
9fff742eae | ||
|
|
73140dec35 | ||
|
|
0936378085 | ||
|
|
41a8ed0190 | ||
|
|
9cde4d74f5 | ||
|
|
32c48f5d9a | ||
|
|
8b2eb329e1 | ||
|
|
be89bbdaa1 | ||
|
|
a1e0edbb4f | ||
|
|
8493109b7d |
@@ -9,10 +9,9 @@
|
||||
# `dist_timeout_seconds = 14400` is needed on any run that has to build the HF -> prime-rl
|
||||
# conversion cache, which takes far longer than the 3600s default.
|
||||
#
|
||||
# To buy memory back for quicker testing on fewer nodes, set `full_offload = true` under `[model]`,
|
||||
# which keeps the fp32 masters, moments and gradients in CPU RAM and needs `optim_cpu_offload =
|
||||
# false` and `optim.max_norm = "None"` set alongside it; the lighter `optim_cpu_offload = true` is
|
||||
# already the default here.
|
||||
# To buy memory back for quicker testing on fewer nodes, set `offload = "full"` under `[model]`,
|
||||
# which keeps the fp32 masters, moments and gradients in CPU RAM and disables gradient clipping;
|
||||
# the lighter `offload = "optimizer"` is already the default here.
|
||||
#
|
||||
# There is no `[ckpt]` block. The trainer saves unconditionally at the last step, and a 43-layer
|
||||
# checkpoint (fp32 master weights plus two fp32 AdamW moments) is ~3 TiB. Add one with
|
||||
|
||||
@@ -13,6 +13,7 @@ num_infer_nodes = 12
|
||||
|
||||
[slurm]
|
||||
job_name = "swe-minimax"
|
||||
partition = "all"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
@@ -22,10 +22,6 @@ num_infer_replicas = 4
|
||||
project = "nemotron-3-super"
|
||||
name = "nemotron-3-super-swe"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
|
||||
@@ -9,8 +9,7 @@ step = 5
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
offload = "full"
|
||||
|
||||
[optim]
|
||||
lr = 0.0
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@ Backend shape checks and token alignment apply only to the selected compute path
|
||||
|
||||
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
|
||||
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed.
|
||||
|
||||
### Expert Parallelism Backends
|
||||
|
||||
|
||||
+4
-4
@@ -86,9 +86,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
|
||||
|---|---|
|
||||
| `trainer.model.dp_replicate` | Number of dimensions to **replicate** instead of shard. Set to 2 to run 2-way DP replication × FSDP sharding within each replica — useful for very large clusters where pure FSDP communication dominates. |
|
||||
| `trainer.model.reshard_after_forward` | If `true` (default), parameters are resharded after the forward pass to free memory; the backward pass re-gathers. Set `false` to keep params resident — faster but more memory. |
|
||||
| `trainer.model.fsdp_cpu_offload` | Offload params + grads + optimizer state to CPU. Big memory win, large throughput hit. |
|
||||
| `trainer.model.optim_cpu_offload` | Offload optimizer state to CPU between steps. Enabled by default. |
|
||||
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run the optimizer (AdamW or SignSGD) on CPU during backward. Disabled by default. |
|
||||
| `trainer.model.offload` | CPU offloading: `optimizer` (default) offloads optimizer state between steps; `full` offloads gradients, FP32 masters, and optimizer state and runs the optimizer (AdamW or SignSGD) on CPU during backward; `none` disables offloading. |
|
||||
|
||||
### Expert Parallelism
|
||||
|
||||
@@ -143,7 +141,7 @@ Activation offloading still applies to tensors saved by autograd, but tensors re
|
||||
|
||||
### Optimizer Offloading
|
||||
|
||||
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
|
||||
State-only optimizer offload is enabled by default (`model.offload = "optimizer"`). For full offload, set `model.offload = "full"`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
|
||||
|
||||
### LM Head Chunking
|
||||
|
||||
@@ -181,6 +179,8 @@ The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]
|
||||
|
||||
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras --all-packages` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
|
||||
|
||||
Compile and JIT caches are node-local by default: the launcher sets `TRITON_CACHE_DIR=/tmp/triton-<uid>` for every component, and `VLLM_CACHE_ROOT=/tmp/.vllm-cache-<uid>` and `FLASHINFER_WORKSPACE_BASE=/tmp/.flashinfer-cache-<uid>` for inference. Ranks writing one cache on a shared filesystem can crash or hang. Override them in `[env_vars]` or a component's `env_vars`.
|
||||
|
||||
### Activation
|
||||
|
||||
A SLURM config is usually a thin overlay that adds `[slurm]` (and `[deployment]` for multi-node) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [Configuration § TOML Composition](configuration.md#toml-composition):
|
||||
|
||||
@@ -21,10 +21,6 @@ num_infer_replicas = 4
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
@@ -163,11 +159,6 @@ env.taskset.task.judge.model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -34,10 +34,6 @@ num_infer_nodes = 1
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
@@ -56,8 +52,7 @@ name = "zai-org/GLM-4.5-Air"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
offload = "full"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
@@ -95,11 +90,6 @@ thinking_retention = "all"
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -35,10 +35,6 @@ num_infer_replicas = 4
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
@@ -112,11 +108,6 @@ env.agent.timeout.rollout = 3600
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.85
|
||||
max_model_len = 131072
|
||||
|
||||
@@ -22,10 +22,6 @@ num_infer_replicas = 4
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
@@ -158,11 +154,6 @@ env.taskset.id = "terminal-bench-2"
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
[model]
|
||||
cp = 1
|
||||
optim_cpu_offload = false
|
||||
offload = "none"
|
||||
ac_offloading = "None"
|
||||
|
||||
[model.compile]
|
||||
|
||||
@@ -8,7 +8,7 @@ name = "zai-org/GLM-5.3-BF16"
|
||||
attn = "flash_attention_2"
|
||||
cp = 8
|
||||
ep = 8
|
||||
optim_cpu_offload = true
|
||||
offload = "optimizer"
|
||||
dsa_backend = "cudnn_flashmla"
|
||||
|
||||
[model.ac]
|
||||
|
||||
@@ -13,6 +13,7 @@ num_infer_nodes = 12
|
||||
|
||||
[slurm]
|
||||
job_name = "swe-qwen30b"
|
||||
partition = "all"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
@@ -13,6 +13,7 @@ num_infer_nodes = 2
|
||||
|
||||
[slurm]
|
||||
job_name = "math-qwen30b"
|
||||
partition = "all"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
@@ -13,6 +13,7 @@ num_infer_nodes = 2
|
||||
|
||||
[slurm]
|
||||
job_name = "swe-qwen30b"
|
||||
partition = "all"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
@@ -3,6 +3,7 @@ seq_len = 32768
|
||||
|
||||
[slurm]
|
||||
job_name = "general-agent-qwen3-30b-a3b-rlm"
|
||||
partition = "all"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
|
||||
@@ -28,10 +28,11 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
"""Adaptive in-flight episode concurrency, sized by the same controller as
|
||||
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
|
||||
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on episode dispatch, in tasks per minute. Use it for
|
||||
sandbox-backed environments to pace provisioning during autoscaling. None disables
|
||||
rate limiting."""
|
||||
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."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat for the run: pinged by landed episodes — the first
|
||||
|
||||
@@ -29,15 +29,6 @@ class ServerConfig(BaseConfig):
|
||||
# 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)
|
||||
|
||||
# vLLM all2all backend options for expert-parallel deployments.
|
||||
All2AllBackend = Literal[
|
||||
"allgather_reducescatter",
|
||||
"deepep_high_throughput",
|
||||
"deepep_low_latency",
|
||||
"flashinfer_nvlink_one_sided",
|
||||
"flashinfer_nvlink_two_sided",
|
||||
]
|
||||
|
||||
QuantizationType = Literal["fp8_per_block"]
|
||||
|
||||
|
||||
@@ -59,18 +50,9 @@ class VllmConfig(BaseConfig):
|
||||
model: str = "Qwen/Qwen3-0.6B"
|
||||
"""HF model name or local path."""
|
||||
|
||||
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
|
||||
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models."""
|
||||
|
||||
max_model_len: int | None = None
|
||||
"""Maximum model context length. If None, uses the model config's value."""
|
||||
|
||||
enforce_eager: bool = False
|
||||
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance."""
|
||||
|
||||
trust_remote_code: bool = False
|
||||
"""Trust remote code when loading the model."""
|
||||
|
||||
chat_template: str | None = None
|
||||
"""Chat template — a Jinja2 template string or path to a template file. If None, uses the model's default."""
|
||||
|
||||
@@ -98,9 +80,6 @@ class VllmConfig(BaseConfig):
|
||||
api_server_count: int = Field(1, ge=0)
|
||||
"""API servers to run. Set to 0 for headless mode."""
|
||||
|
||||
seed: int = 0
|
||||
"""Seed the inference components."""
|
||||
|
||||
gpu_memory_utilization: float = 0.9
|
||||
"""GPU memory utilization."""
|
||||
|
||||
@@ -113,10 +92,6 @@ class VllmConfig(BaseConfig):
|
||||
enable_lora: bool = False
|
||||
"""Enable LoRA."""
|
||||
|
||||
max_loras: int = 1
|
||||
"""Maximum number of concurrently served LoRAs. prime-rl serves one adapter and reloads
|
||||
it in place every policy version (same name, same lora_int_id), so one slot suffices."""
|
||||
|
||||
max_lora_rank: int | None = None
|
||||
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
|
||||
|
||||
@@ -126,9 +101,6 @@ class VllmConfig(BaseConfig):
|
||||
enable_expert_parallel: bool = False
|
||||
"""Enable expert parallelism for MoE models."""
|
||||
|
||||
all2all_backend: All2AllBackend = "allgather_reducescatter"
|
||||
"""All-to-all backend for expert-parallel communication."""
|
||||
|
||||
enable_eplb: bool = False
|
||||
"""Enable expert parallel load balancer (EPLB)."""
|
||||
|
||||
@@ -138,9 +110,6 @@ class VllmConfig(BaseConfig):
|
||||
expert parallelism is disabled, or under EPLB (redundant expert slots need all
|
||||
logical expert weights)."""
|
||||
|
||||
enable_dbo: bool = False
|
||||
"""Enable dual batch overlap (DBO)."""
|
||||
|
||||
enable_return_routed_experts: bool = False
|
||||
"""Return routed experts in responses."""
|
||||
|
||||
@@ -565,6 +534,8 @@ class InferenceConfig(BaseConfig):
|
||||
|
||||
@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:
|
||||
|
||||
@@ -426,9 +426,6 @@ class CheckpointConfig(BaseConfig):
|
||||
interval: int | None = Field(None, ge=1)
|
||||
"""Step interval at which to save the orchestrator checkpoint."""
|
||||
|
||||
wait_for_weights_timeout: int | None = Field(None, ge=1)
|
||||
"""Wait up to this many seconds for the startup weight directory to appear (the trainer broadcasts the incoming policy — v0 from scratch, the resumed step's version on resume — before the first step). If None, fall back to a default timeout. Raise this for large models on slow shared filesystems."""
|
||||
|
||||
|
||||
class ConcurrencyConfig(BaseConfig):
|
||||
"""Adaptive in-flight concurrency control. The orchestrator sizes the
|
||||
@@ -498,10 +495,10 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""Role for each policy admin client when collecting P/D inference metrics."""
|
||||
|
||||
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."""
|
||||
"""Checkpoint configuration."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
|
||||
"""Transport used to receive updated weights from the trainer."""
|
||||
@@ -512,8 +509,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
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``."""
|
||||
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
|
||||
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: int = Field(128, ge=1)
|
||||
"""Samples to train on per step."""
|
||||
|
||||
@@ -360,6 +360,13 @@ class RLConfig(BaseConfig):
|
||||
# The orchestrator queries the inference server it is paired with; without one, it
|
||||
# must match the trainer whose weights the external server receives.
|
||||
if inference is not None:
|
||||
require_equal(
|
||||
"deployment.gpus_per_node",
|
||||
{
|
||||
"deployment.gpus_per_node": self.deployment.gpus_per_node,
|
||||
"inference.deployment.gpus_per_node": inference.deployment.gpus_per_node,
|
||||
},
|
||||
)
|
||||
require_equal(
|
||||
"model.name",
|
||||
{"inference.vllm.model": inference.vllm.model, "orchestrator.model.name": orchestrator.model.name},
|
||||
@@ -774,6 +781,8 @@ class RLConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
|
||||
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:
|
||||
|
||||
@@ -388,13 +388,13 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def full_optimizer_offload_requires_supported_optimizer(self):
|
||||
if self.model.full_offload and self.optim.type not in ("adamw", "sign_sgd"):
|
||||
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.full_offload and self.optim.max_norm is not None:
|
||||
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).",
|
||||
@@ -442,8 +442,6 @@ class SFTConfig(BaseConfig):
|
||||
"LoRA training is not yet supported with in-memory weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
if self.eval.retrigger_on_resume:
|
||||
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
|
||||
|
||||
if self.deployment.type == "multi_node":
|
||||
# Dedicated nodes in the SFT allocation run the inference pool, router,
|
||||
@@ -621,12 +619,6 @@ class SFTConfig(BaseConfig):
|
||||
validate_scheduler(self.scheduler, self.max_steps)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_opt_and_fsdp_offload(self):
|
||||
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
|
||||
raise ValueError("Muon optimizer does not support FSDP CPU offload")
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -651,6 +643,8 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@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:
|
||||
|
||||
@@ -39,9 +39,10 @@ EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_e
|
||||
|
||||
|
||||
class BaseWeightBroadcastConfig(BaseConfig):
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for the broadcast handshake and transfer. The trainer
|
||||
fails the run when no consumer acknowledges an offered version in time."""
|
||||
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):
|
||||
@@ -122,8 +123,8 @@ class ResumeConfig(BaseConfig):
|
||||
|
||||
|
||||
class SlurmConfig(BaseConfig):
|
||||
job_name: str = "prime-rl"
|
||||
"""SLURM job name."""
|
||||
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."""
|
||||
@@ -131,8 +132,8 @@ class SlurmConfig(BaseConfig):
|
||||
template_path: Path | None = None
|
||||
"""SLURM template file. If None, uses the bundled single-node or multi-node template."""
|
||||
|
||||
partition: str = "cluster"
|
||||
"""SLURM partition (#SBATCH --partition)."""
|
||||
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)."""
|
||||
@@ -153,7 +154,7 @@ class SlurmConfig(BaseConfig):
|
||||
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
|
||||
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
|
||||
"""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."""
|
||||
|
||||
@@ -3,7 +3,7 @@ import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import BeforeValidator, Field, field_validator, model_validator
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
@@ -49,34 +49,7 @@ class ActivationOffloadingConfig(BaseConfig):
|
||||
"""Max activations kept in flight while offloading. More activations smooth overlap at the cost of GPU memory."""
|
||||
|
||||
|
||||
class OptimizerInBackwardOffloadConfig(BaseConfig):
|
||||
"""Full CPU optimizer offload: FP32 masters, optimizer state (AdamW moments; SignSGD is
|
||||
stateless), and accumulated gradients live in CPU RAM, each optimizer chunk runs on CPU as
|
||||
soon as its last gradient arrives, and the refreshed BF16 weights stream back while backward
|
||||
is still executing.
|
||||
|
||||
Gradient numerics: gradients are reduced across ranks in FP32 (``reduce_dtype``) but FSDP2
|
||||
materializes them in the sharded parameter's dtype, which is BF16 for the offload compute
|
||||
model — so each gradient is rounded to BF16 once before the FP32 CPU update. Masters,
|
||||
moments, accumulation, and optimizer arithmetic remain FP32. For gradient numerics
|
||||
bit-faithful to that path, disable offloading.
|
||||
"""
|
||||
|
||||
numa_bind: bool = True
|
||||
"""Pin each rank's CPUs to its GPU's NUMA node. Disable when the launcher already manages CPU affinity or GPU sysfs topology is unavailable."""
|
||||
|
||||
|
||||
def _normalize_optimizer_in_backward_offload(value: Any) -> Any:
|
||||
if value is True:
|
||||
return {}
|
||||
if value is False:
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
OptimizerInBackwardOffload = Annotated[
|
||||
OptimizerInBackwardOffloadConfig | None, BeforeValidator(_normalize_optimizer_in_backward_offload)
|
||||
]
|
||||
OffloadMode: TypeAlias = Literal["none", "optimizer", "full"]
|
||||
|
||||
|
||||
class CompileConfig(BaseConfig):
|
||||
@@ -95,14 +68,6 @@ class FusionsConfig(BaseConfig):
|
||||
"""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 IndexCacheConfig(BaseConfig):
|
||||
topk_freq: int = Field(1, ge=1)
|
||||
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
|
||||
|
||||
topk_pattern: str | None = None
|
||||
"""Optional per-layer schedule that overrides ``topk_freq``. ``'F'`` computes fresh indices for that layer; ``'S'`` reuses the previously cached indices. Length should match the number of decoder layers."""
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
rank: int = Field(16, ge=1)
|
||||
"""Rank of the low-rank decomposition matrices."""
|
||||
@@ -288,14 +253,8 @@ class ModelConfig(BaseModelConfig):
|
||||
ac_offloading: ActivationOffloadingConfig | None = ActivationOffloadingConfig()
|
||||
"""Activation offloading configuration. If None, activation offloading is disabled."""
|
||||
|
||||
fsdp_cpu_offload: bool = False
|
||||
"""Enable FSDP CPU offloading for parameters, gradients, and optimizer states. Uses pinned memory for efficient CPU↔GPU transfers."""
|
||||
|
||||
optim_cpu_offload: bool = True
|
||||
"""Offload only optimizer states (momentum, variance) to CPU, keeping weights on GPU. Avoids the H2D all-gather overhead of FSDP CPU offload while still saving GPU memory."""
|
||||
|
||||
full_offload: OptimizerInBackwardOffload = None
|
||||
"""Full CPU optimizer offload: FP32 masters, moments, and gradients live in CPU RAM and the optimizer runs on CPU, overlapped with backward. Enable with ``true`` or a ``[model.full_offload]`` section; disabled by default."""
|
||||
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."""
|
||||
@@ -329,9 +288,6 @@ class ModelConfig(BaseModelConfig):
|
||||
dsa_backend: DSABackend = "tilelang"
|
||||
"""Kernels for the DSA sparse MLA attention (``glm_moe_dsa``, e.g. GLM-5). ``tilelang`` runs the TileLang forward and backward. ``cudnn_flashmla`` runs the FlashMLA sparse prefill forward with the cuDNN frontend CuTe-DSL backward; it needs the ``flash-mla`` extra and an SM90 GPU (SM100/SM103 are wired up but untested)."""
|
||||
|
||||
index_cache: IndexCacheConfig | None = None
|
||||
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
|
||||
|
||||
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."""
|
||||
|
||||
@@ -358,20 +314,9 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ac_offloading_requires_ac(self):
|
||||
"""Automatically enable activation checkpointing when activation offloading is enabled."""
|
||||
if self.ac_offloading is not None and self.ac is None:
|
||||
self.ac = ActivationCheckpointConfig()
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def cpu_offload_mutual_exclusion(self):
|
||||
if self.fsdp_cpu_offload and (self.optim_cpu_offload or self.full_offload):
|
||||
raise ValueError("Cannot combine fsdp_cpu_offload with optimizer CPU offloading.")
|
||||
if self.optim_cpu_offload and self.full_offload:
|
||||
raise ValueError(
|
||||
"Cannot enable both optim_cpu_offload and full_offload. "
|
||||
"Set optim_cpu_offload=false when enabling full optimizer offload."
|
||||
)
|
||||
"""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")
|
||||
@@ -612,7 +557,7 @@ class DataLoaderConfig(BaseConfig):
|
||||
fake: FakeDataLoaderConfig | None = None
|
||||
"""Use a fake data loader sampling random micro-batches (for debugging)."""
|
||||
|
||||
num_workers: int = Field(0, ge=0)
|
||||
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."""
|
||||
|
||||
|
||||
@@ -711,13 +656,13 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def full_optimizer_offload_requires_supported_optimizer(self):
|
||||
if self.model.full_offload and self.optim.type not in ("adamw", "sign_sgd"):
|
||||
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.full_offload and self.optim.max_norm is not None:
|
||||
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).",
|
||||
@@ -751,12 +696,6 @@ class TrainerConfig(BaseConfig):
|
||||
validate_scheduler(self.scheduler, self.max_steps)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_opt_and_fsdp_offload(self):
|
||||
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
|
||||
raise ValueError("Muon optimizer does not support FSDP CPU offload")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
|
||||
@@ -133,6 +133,10 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
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
|
||||
|
||||
@@ -42,7 +42,7 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
|
||||
|
||||
**Sources are one block** — inside a `[[...source]]` entry, write nested sub-configs as dotted keys in the same block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`), not one subsection header per nested config. Nested arrays of tables (e.g. `[[orchestrator.train.source.env.taskset.task.judges]]`) keep full-path headers — they attach to the preceding `[[...source]]` entry.
|
||||
|
||||
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
|
||||
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enable_prefix_caching = true`).
|
||||
|
||||
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--vllm.max-model-len None`.
|
||||
|
||||
|
||||
@@ -26,12 +26,11 @@ SLURM launches write generated scripts and coordination files under `<run_dir>/l
|
||||
- Validation aliases let renamed fields keep working; legacy keys can be remapped in a `model_validator(mode="before")`.
|
||||
- Auto-generated `--help` panels from `Field(description=...)` or PEP 224 docstrings.
|
||||
- Friendly errors: required-field boxes, validator errors point at the offending flag, unknown flags get a "did you mean" hint.
|
||||
- State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`.
|
||||
- State-only optimizer offload is enabled by default (`model.offload = "optimizer"`).
|
||||
- For gradients, FP32 masters, optimizer state, and optimizer-in-backward CPU execution, set
|
||||
`model.optim_cpu_offload = false` and `model.full_offload = true`. This mode uses the native
|
||||
CPU optimizer kernel, only supports AdamW and SignSGD (SignSGD is stateless and
|
||||
halves the host RAM footprint), and disables gradient clipping. Use a
|
||||
`[model.full_offload]` table only to disable NUMA binding.
|
||||
`model.offload = "full"`. This mode uses the native CPU optimizer kernel, only supports
|
||||
AdamW and SignSGD (SignSGD is stateless and halves the host RAM footprint), disables
|
||||
gradient clipping, and pins each rank's CPUs to its GPU's NUMA node.
|
||||
|
||||
## `rl` — RL training
|
||||
|
||||
|
||||
@@ -320,6 +320,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
"modelexpress_redis_port": 6380 if nixl_broadcast is not None and nixl_broadcast.port == 6379 else 6379,
|
||||
}
|
||||
|
||||
ckpt_dir = get_ckpt_dir(config.trainer.ckpt.output_dir or config.run_dir) if config.trainer.ckpt else None
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
@@ -342,6 +344,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
config_dir=config_dir,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
ckpt_dir=ckpt_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
@@ -387,6 +390,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
ckpt_dir=ckpt_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
|
||||
@@ -118,7 +118,7 @@ class EvalRunner:
|
||||
progress=None,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.concurrency.max_inflight,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
dispatch_per_minute=config.dispatch_per_minute,
|
||||
max_off_policy_steps=0,
|
||||
run_id=self.run_id,
|
||||
run_name=self.run_name,
|
||||
|
||||
@@ -12,24 +12,16 @@ def serialize_routed_experts(routed_experts: Any, start: int = 0) -> dict[str, A
|
||||
if routed_experts is None:
|
||||
return None
|
||||
|
||||
array = np.asarray(routed_experts)
|
||||
assert array.ndim == 3
|
||||
assert np.issubdtype(array.dtype, np.integer)
|
||||
dtype = np.uint8
|
||||
if array.size:
|
||||
assert array.min() >= 0
|
||||
if array.max() > np.iinfo(np.uint8).max:
|
||||
# Models with >256 experts (e.g. NemotronH Super/Ultra: 512) need wider
|
||||
# indices. The payload self-describes via "dtype" so consumers pick it up.
|
||||
assert array.max() <= np.iinfo(np.uint16).max
|
||||
dtype = np.uint16
|
||||
|
||||
compact = np.ascontiguousarray(array.astype(dtype, copy=False))
|
||||
# vLLM's capturer picks uint8 or uint16 from the model's expert count, so every request of a
|
||||
# model has the same dtype and the orchestrator can pack them into one micro batch.
|
||||
compact = np.ascontiguousarray(routed_experts)
|
||||
assert compact.ndim == 3
|
||||
assert compact.dtype in (np.uint8, np.uint16), compact.dtype
|
||||
return {
|
||||
"data": pybase64.b64encode(memoryview(compact)).decode("ascii"),
|
||||
"shape": list(compact.shape),
|
||||
"start": start,
|
||||
"dtype": np.dtype(dtype).name,
|
||||
"dtype": compact.dtype.name,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
the concurrency controller moves it via ``set_limit``; refills are
|
||||
burst-capped so a raised (or drained) cap never lands all its prefills at
|
||||
once.
|
||||
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
|
||||
- Optional rate limiting via ``AsyncLimiter(dispatch_per_minute, 60)``, one token per episode.
|
||||
- Every dispatched attempt reaches ``out_q`` exactly once: as the native
|
||||
episode returned by the environment, as a ``DispatchFailure`` when no
|
||||
episode was produced, or under the group's ``GroupCancellation`` when the
|
||||
@@ -139,7 +139,7 @@ class Dispatcher:
|
||||
progress: Progress | None,
|
||||
initial_max_inflight: int,
|
||||
max_inflight_ceiling: int | None,
|
||||
tasks_per_minute: float | None,
|
||||
dispatch_per_minute: float | None,
|
||||
max_off_policy_steps: int,
|
||||
run_id: str,
|
||||
run_name: str | None,
|
||||
@@ -168,7 +168,7 @@ class Dispatcher:
|
||||
self.max_inflight = initial_max_inflight
|
||||
self.current_inflight = 0
|
||||
self.rate_limiter: AsyncLimiter | None = (
|
||||
AsyncLimiter(tasks_per_minute, time_period=60) if tasks_per_minute else None
|
||||
AsyncLimiter(dispatch_per_minute, time_period=60) if dispatch_per_minute else None
|
||||
)
|
||||
# Admission smoothing: the pool may only GROW by ``burst_cap`` per
|
||||
# window. Replacing a completed episode is always free (each natural
|
||||
|
||||
@@ -86,11 +86,6 @@ SHUTDOWN_TIMEOUT_S = 300
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# Default wait for the trainer's startup weight broadcast when no ckpt block
|
||||
# configures ``wait_for_weights_timeout`` (e.g. a from-scratch run). The
|
||||
# broadcast is always coming, so wait rather than fail immediately.
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
# Set in ``__init__``
|
||||
@@ -302,9 +297,6 @@ class Orchestrator:
|
||||
# scratch). The startup broadcast is always coming, so wait for it rather
|
||||
# than failing immediately when it is not there yet.
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
)
|
||||
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
@@ -330,7 +322,7 @@ class Orchestrator:
|
||||
progress=self.progress,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.concurrency.max_inflight,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
dispatch_per_minute=config.dispatch_per_minute,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
run_id=self.run_id,
|
||||
run_name=self.run_name,
|
||||
@@ -383,7 +375,7 @@ class Orchestrator:
|
||||
|
||||
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
|
||||
t0 = time.perf_counter()
|
||||
await self.watcher.sync_startup(sync_version, timeout=wait_timeout)
|
||||
await self.watcher.sync_startup(sync_version, timeout=config.weight_broadcast.timeout)
|
||||
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
async def start(self) -> None:
|
||||
@@ -412,16 +404,20 @@ class Orchestrator:
|
||||
# CancelledError, KeyboardInterrupt, or a real error), so the teardown
|
||||
# logs a forced-cleanup warning instead of a clean-exit success.
|
||||
clean_exit = False
|
||||
loop_done = False
|
||||
try:
|
||||
await self.main_loop()
|
||||
loop_done = True
|
||||
await self.wait_for_final_broadcast()
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
# ``progress.step`` points at the next (unshipped) step; the last finished step is
|
||||
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
|
||||
# first ship). Saved before finalize, which tells the launcher the run is done.
|
||||
if self.config.ckpt is not None and self.progress.step > 1:
|
||||
# first ship). Saved before finalize, which tells the launcher the run is done. Only once the
|
||||
# step loop finished (the last step is fully shipped); a crash mid-loop leaves no consistent
|
||||
# state for that step, and the trainer has no checkpoint for it.
|
||||
if loop_done and self.config.ckpt is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
|
||||
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
|
||||
@@ -438,7 +434,7 @@ class Orchestrator:
|
||||
await monitors.finalize()
|
||||
else:
|
||||
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
|
||||
await self.stop()
|
||||
await self.stop(clean_exit)
|
||||
if clean_exit:
|
||||
get_logger().success("Orchestrator finished")
|
||||
else:
|
||||
@@ -991,7 +987,7 @@ class Orchestrator:
|
||||
self.update_dispatch_gate()
|
||||
self.version_advanced.set()
|
||||
|
||||
async def stop(self) -> None:
|
||||
async def stop(self, clean_exit: bool) -> None:
|
||||
"""Bounded best-effort teardown of all components. Has a global
|
||||
timeout so a wedged peer can't keep the process alive forever —
|
||||
training artifacts are already persisted before this is reached."""
|
||||
@@ -1034,7 +1030,7 @@ class Orchestrator:
|
||||
f"Orchestrator shutdown did not complete within {SHUTDOWN_TIMEOUT_S}s; "
|
||||
"forcing process exit. Training artifacts are already persisted."
|
||||
)
|
||||
os._exit(0)
|
||||
os._exit(0 if clean_exit else 1)
|
||||
await task
|
||||
get_logger().debug(f"Stopped orchestrator components in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
#SBATCH --nodes={{ num_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
{%- if partition %}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- endif %}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
{%- if partition %}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- endif %}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
@@ -599,17 +601,25 @@ while true; do
|
||||
done
|
||||
|
||||
REMAINING_PIDS=$(jobs -p)
|
||||
{%- if cleanup_grace_period %}
|
||||
{%- if cleanup_grace_period and ckpt_dir %}
|
||||
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
|
||||
# tasks only once a task *exits* non-zero. So on a non-zero exit (crash, SIGTERM,
|
||||
# wall-time) we stay alive for the grace period and signal nothing: this lets an
|
||||
# in-flight trainer checkpoint on this node finish, and — because the task has
|
||||
# not exited yet — keeps --kill-on-bad-exit from reaping checkpointing trainers
|
||||
# on peer nodes. We then propagate the exit code so the allocation tears down. A
|
||||
# clean (zero) exit cannot trip --kill-on-bad-exit, so we tear down immediately.
|
||||
# wall-time) we stay alive and signal nothing while the newest trainer checkpoint
|
||||
# is still being written (no DCP `.metadata` yet), up to the grace period: this lets
|
||||
# it finish on this node, and — because the task has not exited yet — keeps
|
||||
# --kill-on-bad-exit from reaping checkpointing trainers on peer nodes. We then
|
||||
# propagate the exit code so the allocation tears down. A clean (zero) exit cannot
|
||||
# trip --kill-on-bad-exit, so we tear down immediately.
|
||||
if [ "$EXIT_CODE" -ne 0 ]; then
|
||||
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for in-flight checkpoints to flush before teardown"
|
||||
sleep {{ cleanup_grace_period }}
|
||||
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for an in-flight trainer checkpoint to finish before teardown"
|
||||
GRACE_DEADLINE=$((SECONDS + {{ cleanup_grace_period }}))
|
||||
while [ "$SECONDS" -lt "$GRACE_DEADLINE" ]; do
|
||||
LATEST_CKPT=$(ls -d {{ ckpt_dir }}/step_*/trainer 2>/dev/null | sort -V | tail -n 1)
|
||||
if [ -z "$LATEST_CKPT" ] || [ -f "$LATEST_CKPT/.metadata" ]; then
|
||||
break
|
||||
fi
|
||||
sleep 10
|
||||
done
|
||||
fi
|
||||
{%- endif %}
|
||||
echo "[$(hostname)] tearing down (exit code $EXIT_CODE) - terminating remaining processes"
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
{%- if partition %}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- endif %}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --exclusive
|
||||
{%- if partition %}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- endif %}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --exclusive
|
||||
{%- if partition %}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- endif %}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
|
||||
@@ -19,7 +19,7 @@ from torch import Tensor
|
||||
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointWrapper
|
||||
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
from torch.distributed.fsdp import FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
from torch.distributed.fsdp._fully_shard._fsdp_common import FSDPMeshInfo, ShardPlacementResult
|
||||
from torch.distributed.fsdp._fully_shard._fsdp_init import _get_mesh_info
|
||||
from torch.distributed.tensor import Shard
|
||||
@@ -353,22 +353,15 @@ def get_model(
|
||||
if subconfig is not None and hasattr(subconfig, "use_cache"):
|
||||
subconfig.use_cache = False
|
||||
model_config.dsa_backend = config.dsa_backend
|
||||
if config.index_cache is not None:
|
||||
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
|
||||
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
|
||||
indexer_types = getattr(model_config, "indexer_types", None)
|
||||
if indexer_types and any(t == "shared" for t in indexer_types):
|
||||
model_config.use_index_cache = True
|
||||
model_config.index_topk_freq = config.index_cache.topk_freq
|
||||
model_config.index_topk_pattern = config.index_cache.topk_pattern
|
||||
# Explicit override supersedes the model's native IndexShare schedule.
|
||||
model_config.indexer_types = None
|
||||
else:
|
||||
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
|
||||
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
|
||||
indexer_types = getattr(model_config, "indexer_types", None)
|
||||
if indexer_types and any(t == "shared" for t in indexer_types):
|
||||
model_config.use_index_cache = True
|
||||
logger.info(
|
||||
f"Auto-enabled IndexShare from indexer_types schedule "
|
||||
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
|
||||
)
|
||||
logger.info(
|
||||
f"Auto-enabled IndexShare from indexer_types schedule "
|
||||
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
|
||||
)
|
||||
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
|
||||
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
|
||||
@@ -509,7 +502,7 @@ def _expert_shard_placement_fn(
|
||||
|
||||
def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
|
||||
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=DTYPE_MAP[config.reduce_dtype])
|
||||
offload_policy: OffloadPolicy = CPUOffloadPolicy(pin_memory=True) if config.fsdp_cpu_offload else OffloadPolicy()
|
||||
offload_policy: OffloadPolicy = OffloadPolicy()
|
||||
|
||||
fused_shard_placement_fn = get_fsdp_shard_placement_fn(model) if config.fusions.shard_fused_on_dim1 else None
|
||||
hsdp_mesh = parallel_dims.get_mesh("hsdp")
|
||||
@@ -695,7 +688,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
|
||||
|
||||
def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
|
||||
device = "cpu" if config.fsdp_cpu_offload else "cuda"
|
||||
device = "cuda"
|
||||
model.to_empty(device=device)
|
||||
torch.distributed.barrier()
|
||||
|
||||
@@ -705,7 +698,6 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
logger = get_logger()
|
||||
if config.debug.random_init:
|
||||
logger.warning("Randomly initializing model. Skipping loading weights from HF.")
|
||||
_move_buffers_to_cuda(model, config)
|
||||
return
|
||||
|
||||
if not Path(config.name).exists():
|
||||
@@ -775,7 +767,6 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
storage_reader=HuggingFaceStorageReader(path=snapshot_path.as_posix()),
|
||||
)
|
||||
write_back_loaded_packed_parameters(model, state_dict)
|
||||
_move_buffers_to_cuda(model, config)
|
||||
|
||||
lora_modules = [m for m in model.modules() if hasattr(m, "_init_lora_parameters")]
|
||||
if lora_modules:
|
||||
@@ -891,15 +882,6 @@ def configure_trainable_parameters(model: nn.Module, config: ModelConfig) -> nn.
|
||||
return frozen_vision_encoder
|
||||
|
||||
|
||||
def _move_buffers_to_cuda(model: nn.Module, config: ModelConfig) -> None:
|
||||
"""FSDP CPU offloading only manages parameters, not buffers. Move buffers to CUDA."""
|
||||
if not config.fsdp_cpu_offload:
|
||||
return
|
||||
for _, buffer in model.named_buffers():
|
||||
if buffer.device.type == "cpu":
|
||||
buffer.data = buffer.data.to("cuda")
|
||||
|
||||
|
||||
def _reset_runtime_moe_buffers(model: nn.Module) -> None:
|
||||
for module in model.modules():
|
||||
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
|
||||
@@ -1024,11 +1006,10 @@ def setup_model(
|
||||
logger.warning(
|
||||
"Skipping loading weights. Initializing an empty model on device, loading from checkpoint later."
|
||||
)
|
||||
device = "cpu" if config.fsdp_cpu_offload else "cuda"
|
||||
device = "cuda"
|
||||
model.to_empty(device=device)
|
||||
torch.distributed.barrier()
|
||||
model.init_buffers_post_meta()
|
||||
_move_buffers_to_cuda(model, config)
|
||||
else:
|
||||
load_dcp_from_hf(model, config, parallel_dims)
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ from prime_rl.utils.cp import CPContext
|
||||
# FLA's stacked output buffer. Keep CP convolution eager until this is fixed:
|
||||
# https://github.com/pytorch/pytorch/issues/155632
|
||||
causal_conv1d_with_context_parallelism = torch.compiler.disable(causal_conv1d)
|
||||
# CP setup searchsorts tensor-valued sequence boundaries; keep it outside the compiled graph.
|
||||
build_cp_context_eager = torch.compiler.disable(build_cp_context)
|
||||
|
||||
|
||||
class Qwen3_5GatedDeltaNet(nn.Module):
|
||||
@@ -65,7 +67,7 @@ class Qwen3_5GatedDeltaNet(nn.Module):
|
||||
|
||||
context = None
|
||||
if self.cp_context.cp_enabled:
|
||||
context = build_cp_context(
|
||||
context = build_cp_context_eager(
|
||||
cu_seqlens=cu_seqlens.to(device=hidden_states.device, dtype=torch.int32),
|
||||
group=self.cp_context.cp_group,
|
||||
conv1d_kernel_size=self.conv_kernel_size,
|
||||
|
||||
@@ -5,7 +5,7 @@ from torch import nn
|
||||
from torch.distributed.device_mesh import DeviceMesh
|
||||
from torch.optim import AdamW, Optimizer
|
||||
|
||||
from prime_rl.configs.trainer import OptimizerConfig, OptimizerInBackwardOffloadConfig
|
||||
from prime_rl.configs.trainer import OffloadMode, OptimizerConfig
|
||||
from prime_rl.trainer.models.fusions import get_model_packed_parameters
|
||||
from prime_rl.trainer.optim.base import OffloadOptimizer as OffloadOptimizer
|
||||
from prime_rl.trainer.optim.base import OptimizerLike
|
||||
@@ -51,21 +51,20 @@ def setup_optimizer(
|
||||
config: OptimizerConfig,
|
||||
named_params: list[tuple[str, nn.Parameter]],
|
||||
parallel_dims: ParallelDims,
|
||||
cpu_offload: bool = False,
|
||||
full_offload_config: OptimizerInBackwardOffloadConfig | None = None,
|
||||
offload: OffloadMode = "none",
|
||||
model: nn.Module | None = None,
|
||||
full_offload_dtype_policy: dict[int, tuple[torch.dtype, torch.dtype]] | None = None,
|
||||
) -> tuple[OptimizerLike, GradientOffloadManager | None]:
|
||||
if cpu_offload and full_offload_config is not None:
|
||||
raise ValueError("State-only and full optimizer CPU offload cannot both be enabled")
|
||||
if full_offload_config is not None and config.type not in ("adamw", "sign_sgd"):
|
||||
cpu_offload = offload == "optimizer"
|
||||
full_offload = offload == "full"
|
||||
if full_offload and config.type not in ("adamw", "sign_sgd"):
|
||||
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
|
||||
if full_offload_config is not None and config.max_norm is not None:
|
||||
if full_offload and config.max_norm is not None:
|
||||
get_logger().warning("Disabling gradient clipping because CPU optimizer offload updates during backward")
|
||||
config.max_norm = None
|
||||
optimizer_named_params = named_params
|
||||
master_weights = None
|
||||
if full_offload_config is not None:
|
||||
if full_offload:
|
||||
if model is None:
|
||||
raise ValueError("CPU optimizer offload requires the model")
|
||||
if full_offload_dtype_policy is None:
|
||||
@@ -82,12 +81,11 @@ def setup_optimizer(
|
||||
model=model,
|
||||
)
|
||||
|
||||
if full_offload_config is not None:
|
||||
if full_offload:
|
||||
assert master_weights is not None
|
||||
get_logger().info("Using CPU offload for gradients and the optimizer step")
|
||||
optimizer = FullCPUOffloadOptimizer(
|
||||
optimizer,
|
||||
offload_config=full_offload_config,
|
||||
master_weights=master_weights,
|
||||
dp_replicate=parallel_dims.dp_replicate,
|
||||
)
|
||||
|
||||
@@ -14,7 +14,6 @@ from torch import nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.optim import AdamW, Optimizer
|
||||
|
||||
from prime_rl.configs.trainer import OptimizerInBackwardOffloadConfig
|
||||
from prime_rl.trainer.optim.base import OffloadOptimizer
|
||||
from prime_rl.trainer.optim.cpu_adam import adamw_step as native_cpu_adamw_step
|
||||
from prime_rl.trainer.optim.cpu_adam import copy_or_add_bfloat16_multi_ as native_copy_or_add_bfloat16_multi_
|
||||
@@ -714,12 +713,10 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
||||
def __init__(
|
||||
self,
|
||||
optimizer: Optimizer,
|
||||
offload_config: OptimizerInBackwardOffloadConfig,
|
||||
master_weights: dict[int, _MasterWeight],
|
||||
dp_replicate: int = 1,
|
||||
):
|
||||
self.optimizer = optimizer
|
||||
self.offload_config = offload_config
|
||||
self._initialized = False
|
||||
self._master_weights = master_weights
|
||||
self._chunks = self._build_chunks()
|
||||
|
||||
@@ -106,10 +106,10 @@ def train(config: TrainerConfig):
|
||||
# Set precision
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds),
|
||||
enable_gloo=config.model.fsdp_cpu_offload or config.model.full_offload is not None,
|
||||
enable_gloo=config.model.offload == "full",
|
||||
)
|
||||
if config.model.full_offload is not None:
|
||||
setup_full_cpu_optimizer_offload(config.model.full_offload)
|
||||
if config.model.offload == "full":
|
||||
setup_full_cpu_optimizer_offload()
|
||||
# Configurable to support ROCm/AMD GPUs where reduced precision
|
||||
# matmul corrupts softmax over large vocabularies. Override via config
|
||||
# (e.g. matmul_precision = "highest") on ROCm.
|
||||
@@ -165,11 +165,10 @@ def train(config: TrainerConfig):
|
||||
config.optim,
|
||||
list(model.named_parameters()),
|
||||
parallel_dims,
|
||||
cpu_offload=config.model.optim_cpu_offload,
|
||||
full_offload_config=config.model.full_offload,
|
||||
offload=config.model.offload,
|
||||
model=model,
|
||||
full_offload_dtype_policy=(
|
||||
get_full_offload_dtype_policy(model, config.model) if config.model.full_offload is not None else None
|
||||
get_full_offload_dtype_policy(model, config.model) if config.model.offload == "full" else None
|
||||
),
|
||||
)
|
||||
logger.debug(f"Initialized optimizer in {format_time(time.perf_counter() - t0)}")
|
||||
@@ -508,7 +507,9 @@ def train(config: TrainerConfig):
|
||||
# Add relevant tensors to tensor dict for logging purposes
|
||||
entropy = out["entropy"][loss_mask].detach().to("cpu")
|
||||
tensors["entropy/all"].append(entropy)
|
||||
tensors["loss"].append(loss.detach().to("cpu").unsqueeze(0))
|
||||
# Every CP rank computes the whole sequence's loss, and the global normalizers count each
|
||||
# sequence once per CP rank (gradients still sum correctly), so undo that for the logged value.
|
||||
tensors["loss"].append((loss.detach() * cp_size).to("cpu").unsqueeze(0))
|
||||
|
||||
env_names = micro_batch["env_names"]
|
||||
masked_env_names = [env_name for env_name, keep in zip(env_names, loss_mask.flatten().tolist()) if keep]
|
||||
|
||||
@@ -100,10 +100,10 @@ def train(config: SFTConfig):
|
||||
# Set precision
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds),
|
||||
enable_gloo=config.model.fsdp_cpu_offload or config.model.full_offload is not None,
|
||||
enable_gloo=config.model.offload == "full",
|
||||
)
|
||||
if config.model.full_offload is not None:
|
||||
setup_full_cpu_optimizer_offload(config.model.full_offload)
|
||||
if config.model.offload == "full":
|
||||
setup_full_cpu_optimizer_offload()
|
||||
# Configurable to support ROCm/AMD GPUs where reduced precision
|
||||
# matmul corrupts softmax over large vocabularies. Override via config
|
||||
# (e.g. matmul_precision = "highest") on ROCm.
|
||||
@@ -162,11 +162,10 @@ def train(config: SFTConfig):
|
||||
config.optim,
|
||||
list(model.named_parameters()),
|
||||
parallel_dims,
|
||||
cpu_offload=config.model.optim_cpu_offload,
|
||||
full_offload_config=config.model.full_offload,
|
||||
offload=config.model.offload,
|
||||
model=model,
|
||||
full_offload_dtype_policy=(
|
||||
get_full_offload_dtype_policy(model, config.model) if config.model.full_offload is not None else None
|
||||
get_full_offload_dtype_policy(model, config.model) if config.model.offload == "full" else None
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_ckpt_dir
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.trainer import OptimizerInBackwardOffloadConfig
|
||||
from prime_rl.trainer.optim import GradientOffloadManager
|
||||
|
||||
DEFAULT_TIMEOUT = timedelta(seconds=600)
|
||||
@@ -176,9 +175,8 @@ def configure_cpu_optimizer_threads() -> None:
|
||||
)
|
||||
|
||||
|
||||
def setup_full_cpu_optimizer_offload(config: "OptimizerInBackwardOffloadConfig") -> None:
|
||||
if config.numa_bind:
|
||||
bind_process_to_gpu_numa_node()
|
||||
def setup_full_cpu_optimizer_offload() -> None:
|
||||
bind_process_to_gpu_numa_node()
|
||||
configure_cpu_optimizer_threads()
|
||||
|
||||
|
||||
|
||||
@@ -35,6 +35,10 @@ DEFAULT_INFERENCE_ENV_VARS: dict[str, str] = {
|
||||
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:False",
|
||||
"VLLM_ENGINE_READY_TIMEOUT_S": "4200",
|
||||
"UCX_TLS": "all",
|
||||
# vLLM's AOT compile cache and FlashInfer's JIT cache default to $HOME; a partial cache shared across
|
||||
# nodes makes TP ranks load different compiled artifacts and hang.
|
||||
"VLLM_CACHE_ROOT": f"/tmp/.vllm-cache-{os.getuid()}",
|
||||
"FLASHINFER_WORKSPACE_BASE": f"/tmp/.flashinfer-cache-{os.getuid()}",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ from prime_rl.inference.vllm.serving_tokens import (
|
||||
def _decode_routed_experts(encoded: dict) -> np.ndarray:
|
||||
return np.frombuffer(
|
||||
pybase64.b64decode_as_bytearray(encoded["data"]),
|
||||
dtype=np.uint8,
|
||||
dtype=encoded["dtype"],
|
||||
).reshape(encoded["shape"])
|
||||
|
||||
|
||||
@@ -45,20 +45,21 @@ def test_subclass_overrides_serve_tokens_full_generator():
|
||||
assert PrimeRlServingTokens.serve_tokens_full_generator is not upstream.serve_tokens_full_generator
|
||||
|
||||
|
||||
def test_serialize_routed_experts_uses_compact_raw_payload():
|
||||
def test_serialize_routed_experts_keeps_the_capture_dtype():
|
||||
# A >256-expert model captures uint16 even when every id of a request is below 256.
|
||||
routed_experts = np.array(
|
||||
[
|
||||
[[1, 2], [3, 4]],
|
||||
[[5, 6], [7, 8]],
|
||||
],
|
||||
dtype=np.int64,
|
||||
dtype=np.uint16,
|
||||
)
|
||||
|
||||
encoded = serialize_routed_experts(routed_experts)
|
||||
assert encoded is not None
|
||||
|
||||
decoded = _decode_routed_experts(encoded)
|
||||
assert decoded.dtype == np.uint8
|
||||
assert decoded.dtype == np.uint16
|
||||
np.testing.assert_array_equal(decoded, routed_experts)
|
||||
|
||||
|
||||
|
||||
@@ -331,8 +331,7 @@ def test_removed_moe_runtime_fields_are_rejected(removed):
|
||||
def test_optimizer_state_offload_keeps_legacy_default(config_cls):
|
||||
config = config_cls.model_validate({})
|
||||
|
||||
assert config.model.optim_cpu_offload is True
|
||||
assert config.model.full_offload is None
|
||||
assert config.model.offload == "optimizer"
|
||||
|
||||
|
||||
def test_moe_router_dtype_auto_resolves_per_trainer():
|
||||
@@ -360,7 +359,7 @@ def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
|
||||
with pytest.warns(UserWarning, match="Gradient clipping prevents optimizer-in-backward"):
|
||||
config = config_cls.model_validate(
|
||||
{
|
||||
"model": {"optim_cpu_offload": False, "full_offload": True},
|
||||
"model": {"offload": "full"},
|
||||
"optim": {"max_norm": 1.0},
|
||||
}
|
||||
)
|
||||
@@ -373,7 +372,7 @@ def test_full_optimizer_offload_requires_supported_optimizer(config_cls):
|
||||
with pytest.raises(ValidationError, match="Full optimizer offload only supports AdamW and SignSGD"):
|
||||
config_cls.model_validate(
|
||||
{
|
||||
"model": {"optim_cpu_offload": False, "full_offload": True},
|
||||
"model": {"offload": "full"},
|
||||
"optim": {"type": "muon", "max_norm": None},
|
||||
}
|
||||
)
|
||||
@@ -383,11 +382,11 @@ def test_full_optimizer_offload_requires_supported_optimizer(config_cls):
|
||||
def test_full_optimizer_offload_accepts_sign_sgd(config_cls):
|
||||
config = config_cls.model_validate(
|
||||
{
|
||||
"model": {"optim_cpu_offload": False, "full_offload": True},
|
||||
"model": {"offload": "full"},
|
||||
"optim": {"type": "sign_sgd", "max_norm": None},
|
||||
}
|
||||
)
|
||||
assert config.model.full_offload is not None
|
||||
assert config.model.offload == "full"
|
||||
assert config.optim.type == "sign_sgd"
|
||||
|
||||
|
||||
@@ -714,6 +713,24 @@ def test_multi_node_auto_inference_parallelism():
|
||||
assert config.inference.vllm.data_parallel_size == 2
|
||||
|
||||
|
||||
def test_disaggregated_inference_inherits_deployment_gpus_per_node():
|
||||
config = {
|
||||
"trainer": {},
|
||||
"orchestrator": {},
|
||||
"inference": {"vllm": {"tensor_parallel_size": 2}, "deployment": {"type": "disaggregated"}},
|
||||
"deployment": {"type": "multi_node", "gpus_per_node": 4, "num_train_nodes": 1},
|
||||
"slurm": {},
|
||||
}
|
||||
resolved = RLConfig.model_validate(config)
|
||||
assert resolved.inference.deployment.gpus_per_node == 4
|
||||
assert resolved.inference.vllm.data_parallel_size_local == 2
|
||||
|
||||
config["deployment"].pop("gpus_per_node")
|
||||
config["inference"]["deployment"]["gpus_per_node"] = 4
|
||||
with pytest.raises(ValidationError, match="gpus_per_node must match"):
|
||||
RLConfig.model_validate(config)
|
||||
|
||||
|
||||
def test_orchestrator_vlm_requires_renderer():
|
||||
with pytest.raises(ValidationError, match="renderer"):
|
||||
OrchestratorConfig.model_validate(
|
||||
@@ -761,6 +778,12 @@ def test_trainer_rejects_vlm_cp_with_ring():
|
||||
TrainerConfig.model_validate(config)
|
||||
|
||||
|
||||
def test_ac_none_disables_ac_offloading():
|
||||
config = TrainerModelConfig.model_validate({"ac": None})
|
||||
assert config.ac is None
|
||||
assert config.ac_offloading is None
|
||||
|
||||
|
||||
def test_shared_model_name_propagates_to_subconfigs():
|
||||
model_name = "PrimeIntellect/test-model"
|
||||
config = RLConfig.model_validate(
|
||||
|
||||
Reference in New Issue
Block a user