Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f537d187b | ||
|
|
f6fc1f7adc | ||
|
|
716d1cfac8 | ||
|
|
87766fda3c | ||
|
|
73c4736352 |
@@ -325,6 +325,8 @@ type = "grpo"
|
||||
type = "linear"
|
||||
```
|
||||
|
||||
A **length-weighted baseline** (`length_weighted_baseline = true` on the `grpo`-family algorithms) replaces the plain group mean with $b = \sum_i L_i s_i / \sum_i L_i$, where $L_i$ is the number of trainable (policy-sampled, loss-masked) tokens of rollout $i$, summed across all its turns; it applies after the length penalty. With token-level loss normalization, long rollouts carry more gradient weight, so this baseline makes the per-token advantage zero-mean across the group's tokens rather than across rollouts.
|
||||
|
||||
### Hierarchical GRPO
|
||||
|
||||
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
|
||||
|
||||
@@ -280,6 +280,7 @@ Pulled from the console log and mirrored to W&B.
|
||||
- `optim/grad_norm` — spikes precede divergence.
|
||||
- `optim/lr` — LR schedule.
|
||||
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
|
||||
- For MoE: `expert_load/{cv,max_mean,cold_frac}/{mean,max}` — expert load per layer over the whole step, from token counts summed across all ranks, as the mean and max over MoE layers. `cv` is std/mean of the per-expert token counts, `max_mean` the busiest expert's count over the mean, and `cold_frac` the fraction of experts receiving under 0.1x the mean. A trainable router that drifts shows up as a rising `cv`/`cold_frac` (MiMo-V2.6 §5.4).
|
||||
|
||||
**Performance:**
|
||||
|
||||
|
||||
@@ -208,6 +208,9 @@ class GRPOAlgoConfig(BaseAlgoConfig):
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Linear length penalty subtracted from each reward before the GRPO baseline (see ``LinearLengthPenaltyConfig``): a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max for that quantity. None disables it."""
|
||||
|
||||
length_weighted_baseline: bool = False
|
||||
"""Use the token-length-weighted group mean reward ``sum_i(L_i * r_i) / sum_i(L_i)`` as the baseline instead of the plain mean, where ``L_i`` is the number of trainable (mask-True, policy-sampled) tokens of rollout ``i`` summed across all its turns."""
|
||||
|
||||
|
||||
class EchoAlgoConfig(GRPOAlgoConfig):
|
||||
type: Literal["echo"] = "echo" # type: ignore[assignment]
|
||||
|
||||
@@ -6,8 +6,7 @@ from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig, WeightBroadcastConfig
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
|
||||
|
||||
|
||||
@@ -14,13 +14,14 @@ from prime_rl.configs.algorithm import (
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
BaseWeightBroadcastConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
ResumeConfig,
|
||||
TransportConfig,
|
||||
WeightBroadcastConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
@@ -484,47 +485,6 @@ class CheckpointConfig(BaseConfig):
|
||||
"""Skip loading the progress from checkpoint."""
|
||||
|
||||
|
||||
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."""
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class ConcurrencyConfig(BaseConfig):
|
||||
"""Adaptive in-flight concurrency control. The orchestrator sizes the
|
||||
in-flight episode cap from engine KV capacity and learned per-env episode
|
||||
|
||||
@@ -8,34 +8,17 @@ from pydantic import Field, model_validator
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeTrainMonitorConfig
|
||||
from prime_rl.configs.orchestrator import (
|
||||
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
NIXLWeightBroadcastConfig as OrchestratorNIXLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
ResumeConfig,
|
||||
RunConfig,
|
||||
SlurmConfig,
|
||||
TransportConfig,
|
||||
VLMConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
NIXLWeightBroadcastConfig as TrainerNIXLWeightBroadcastConfig,
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
TokenizerConfig,
|
||||
@@ -50,7 +33,6 @@ from prime_rl.utils.validation import (
|
||||
validate_shared_seq_len,
|
||||
validate_shared_tokenizer,
|
||||
validate_shared_wandb_config,
|
||||
validate_shared_weight_broadcast,
|
||||
)
|
||||
|
||||
|
||||
@@ -128,50 +110,6 @@ class SharedModelConfig(BaseConfig):
|
||||
"""VLM configuration. Set this to enable vision-language model support."""
|
||||
|
||||
|
||||
class SharedInMemoryWeightBroadcastConfig(BaseConfig):
|
||||
host: str = "localhost"
|
||||
"""Weight transfer host."""
|
||||
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for the broadcast handshake and transfer."""
|
||||
|
||||
|
||||
class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
port: int = 29501
|
||||
"""Port for NCCL weight broadcast."""
|
||||
|
||||
|
||||
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for the broadcast handshake and transfer."""
|
||||
|
||||
|
||||
SharedWeightBroadcastConfig: TypeAlias = Annotated[
|
||||
SharedFileSystemWeightBroadcastConfig | SharedNCCLWeightBroadcastConfig | SharedNIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
@@ -290,7 +228,7 @@ class RLConfig(BaseConfig):
|
||||
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."""
|
||||
|
||||
weight_broadcast: SharedWeightBroadcastConfig | None = None
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
|
||||
rollout_transport: TransportConfig | None = None
|
||||
|
||||
@@ -446,52 +384,28 @@ class RLConfig(BaseConfig):
|
||||
"""
|
||||
if self.weight_broadcast is None:
|
||||
if self.trainer.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = SharedFileSystemWeightBroadcastConfig()
|
||||
self.weight_broadcast = FileSystemWeightBroadcastConfig()
|
||||
else:
|
||||
self.weight_broadcast = SharedNCCLWeightBroadcastConfig()
|
||||
self.weight_broadcast = NCCLWeightBroadcastConfig()
|
||||
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 "
|
||||
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
|
||||
"have no disk artifact to load from."
|
||||
)
|
||||
if self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
inference_world_size = (
|
||||
if "inference_world_size" in self.weight_broadcast.model_fields_set:
|
||||
raise ValueError("weight_broadcast.inference_world_size is set automatically by rl; remove it.")
|
||||
update = {}
|
||||
if self.weight_broadcast.type != "filesystem":
|
||||
update["inference_world_size"] = (
|
||||
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
|
||||
if self.inference
|
||||
else 1
|
||||
)
|
||||
common_config = dict(
|
||||
host=self.weight_broadcast.host,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
transport_config = {}
|
||||
trainer_config_type = TrainerNCCLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
|
||||
else:
|
||||
transport_config = dict(
|
||||
session_id=self.weight_broadcast.session_id,
|
||||
overlap_transfer_and_replay=self.weight_broadcast.overlap_transfer_and_replay,
|
||||
)
|
||||
trainer_config_type = TrainerNIXLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNIXLWeightBroadcastConfig
|
||||
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
|
||||
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig(
|
||||
timeout=self.weight_broadcast.timeout
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
|
||||
timeout=self.weight_broadcast.timeout
|
||||
)
|
||||
self.trainer.weight_broadcast = self.weight_broadcast.model_copy(update=update)
|
||||
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy(update=update)
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -10,27 +10,28 @@ from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
ResumeConfig,
|
||||
RunConfig,
|
||||
SlurmConfig,
|
||||
TrainerLogConfig,
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
AdamWConfig,
|
||||
CheckpointConfig,
|
||||
ConstantSchedulerConfig,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
GCConfig,
|
||||
ModelConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
OptimizerConfig,
|
||||
SchedulerConfig,
|
||||
TokenizerConfig,
|
||||
WeightBroadcastConfig,
|
||||
validate_scheduler,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
@@ -456,7 +457,7 @@ class SFTConfig(BaseConfig):
|
||||
self.weight_broadcast.inference_world_size = (
|
||||
self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
)
|
||||
self.inference.weight_broadcast.type = self.weight_broadcast.type
|
||||
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, "
|
||||
@@ -507,7 +508,7 @@ class SFTConfig(BaseConfig):
|
||||
vllm.api_server_count = vllm.data_parallel_size
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size
|
||||
self.inference.weight_broadcast.type = self.weight_broadcast.type
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
host = self.inference.server.host or "localhost"
|
||||
client = self.eval.client
|
||||
|
||||
@@ -43,6 +43,48 @@ class BaseWeightBroadcastConfig(BaseConfig):
|
||||
fails the run when no consumer acknowledges an offered version in time."""
|
||||
|
||||
|
||||
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 NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
"""Weight transfer from trainer to inference. ``rl`` copies its ``[weight_broadcast]`` to the trainer and orchestrator."""
|
||||
|
||||
|
||||
class RunConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Run name. Auto-generated as ``<envs>--<model>--<short-id>`` 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."""
|
||||
|
||||
@@ -8,13 +8,14 @@ from pydantic import BeforeValidator, Field, field_validator, model_validator
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
BaseWeightBroadcastConfig,
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
MetricsServerConfig,
|
||||
ResumeConfig,
|
||||
TrainerLogConfig,
|
||||
TransportConfig,
|
||||
WeightBroadcastConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
@@ -659,48 +660,6 @@ class DataLoaderConfig(BaseConfig):
|
||||
"""Use a fake data loader sampling random micro-batches (for debugging)."""
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
host: str = "localhost"
|
||||
"""Weight transfer host."""
|
||||
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
# TODO: Should not be configurable, but auto-inferred
|
||||
inference_world_size: int = 1
|
||||
"""Number of inference workers."""
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two staging arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
|
||||
@@ -302,18 +302,3 @@ def validate_shared_tokenizer(
|
||||
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
|
||||
f"Use the shared [tokenizer] config to set chat_template for all components."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_weight_broadcast(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
if trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
|
||||
raise ValueError(
|
||||
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
|
||||
)
|
||||
if inference is not None and inference.weight_broadcast.type != trainer.weight_broadcast.type:
|
||||
raise ValueError(
|
||||
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
|
||||
)
|
||||
|
||||
+62
-216
@@ -1,13 +1,9 @@
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
@@ -35,11 +31,10 @@ from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
cleanup_processes,
|
||||
cleanup_threads,
|
||||
get_physical_gpu_ids,
|
||||
monitor_process,
|
||||
ProcessGroup,
|
||||
partition_gpus,
|
||||
set_proc_title,
|
||||
torchrun_cmd,
|
||||
)
|
||||
|
||||
RL_CONFIG = "rl.json"
|
||||
@@ -141,25 +136,9 @@ def rl_local(config: RLConfig):
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs from deployment config
|
||||
gpu_offset = 0
|
||||
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
|
||||
infer_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
|
||||
gpu_offset += num_infer_gpus
|
||||
trainer_local_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
|
||||
|
||||
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
|
||||
physical_gpu_ids = get_physical_gpu_ids()
|
||||
if total_requested_gpus > len(physical_gpu_ids):
|
||||
raise ValueError(
|
||||
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
|
||||
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
|
||||
)
|
||||
physical_gpu_mapping = {local_id: physical_gpu_ids[local_id] for local_id in range(total_requested_gpus)}
|
||||
logger.info(f"Using local->physical GPU mapping: {physical_gpu_mapping}")
|
||||
|
||||
infer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in infer_local_gpu_ids]
|
||||
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
|
||||
infer_gpu_ids, trainer_gpu_ids = partition_gpus(num_infer_gpus, config.deployment.num_train_gpus)
|
||||
logger.info(f"Using local->physical GPU mapping: {dict(enumerate(infer_gpu_ids + trainer_gpu_ids))}")
|
||||
|
||||
start_command = sys.argv
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
@@ -185,53 +164,22 @@ def rl_local(config: RLConfig):
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
|
||||
# Start processes
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
error_queue: list[Exception] = []
|
||||
stop_events: dict[str, Event] = {}
|
||||
|
||||
def sigterm_handler(signum, frame):
|
||||
logger.warning("Received SIGTERM, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
|
||||
try:
|
||||
# Optionally, start inference process
|
||||
with ProcessGroup() as processes:
|
||||
if config.inference:
|
||||
inference_cmd = ["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()]
|
||||
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
|
||||
# If we don't log stdout, the server hangs
|
||||
with open(log_dir / "inference.log", "w") as log_file:
|
||||
inference_process = Popen(
|
||||
inference_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(inference_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["inference"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(inference_process, stop_event, error_queue, "inference"),
|
||||
daemon=True,
|
||||
processes.start(
|
||||
"inference",
|
||||
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
log_path=log_dir / "inference.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
else:
|
||||
logger.warning(
|
||||
"No [inference] block configured - the policy inference server will not be started here. "
|
||||
@@ -259,167 +207,65 @@ def rl_local(config: RLConfig):
|
||||
# orchestrator start in parallel.
|
||||
for split, source in env_servers(config):
|
||||
name = source.resolved_name
|
||||
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
|
||||
logger.info(f"Starting {name} server")
|
||||
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
|
||||
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
|
||||
env_server_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(env_server_log, "w") as log_file:
|
||||
env_server_process = Popen(
|
||||
env_server_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(env_server_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events[f"env/{split}/{name}"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(env_server_process, stop_event, error_queue, f"{split} env server {name}"),
|
||||
daemon=True,
|
||||
processes.start(
|
||||
f"{split} env server {name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars, **config.orchestrator.env_vars},
|
||||
log_path=log_dir / ENVS_DIR / split / f"{name}.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
|
||||
logger.info("Starting orchestrator")
|
||||
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
|
||||
with open(log_dir / "orchestrator.log", "w") as log_file:
|
||||
orchestrator_process = Popen(
|
||||
orchestrator_cmd,
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "orchestrator",
|
||||
},
|
||||
)
|
||||
processes.append(orchestrator_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["orchestrator"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
|
||||
daemon=True,
|
||||
processes.start(
|
||||
"orchestrator",
|
||||
["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "orchestrator",
|
||||
},
|
||||
log_path=log_dir / "orchestrator.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Start training process
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
trainer_cmd = [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
# Pipe all logs to file, and only master rank logs to stdout
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, config.trainer.log.ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={len(trainer_gpu_ids)}",
|
||||
"-m",
|
||||
"prime_rl.trainer.rl.train",
|
||||
"@",
|
||||
(config_dir / TRAINER_CONFIG).as_posix(),
|
||||
]
|
||||
logger.info(f"Starting trainer on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
|
||||
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
|
||||
with open(log_dir / "trainer.log", "w") as log_file:
|
||||
trainer_process = Popen(
|
||||
trainer_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.trainer.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "trainer",
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(trainer_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["trainer"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
|
||||
processes.start(
|
||||
"trainer",
|
||||
torchrun_cmd(
|
||||
"prime_rl.trainer.rl.train",
|
||||
config_dir / TRAINER_CONFIG,
|
||||
len(trainer_gpu_ids),
|
||||
log_dir,
|
||||
config.trainer.log.ranks_filter,
|
||||
),
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.trainer.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "trainer",
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
|
||||
},
|
||||
log_path=log_dir / "trainer.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Trainer and orchestrator completion is the successful stop condition.
|
||||
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
|
||||
while not all(event.is_set() for event in completion_events):
|
||||
if error_queue:
|
||||
error = error_queue[0]
|
||||
logger.error(f"Error: {error}")
|
||||
logger.error("Terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
# Small delay to avoid busy waiting
|
||||
time.sleep(1)
|
||||
|
||||
# Check if any critical process failed
|
||||
if orchestrator_process.returncode != 0:
|
||||
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
if trainer_process.returncode != 0:
|
||||
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
processes.wait("trainer", "orchestrator")
|
||||
logger.success("Training finished!")
|
||||
|
||||
# Cleanup threads and processes
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.warning("Received interrupt signal, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Error occurred: {e}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
raise
|
||||
|
||||
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
|
||||
+25
-101
@@ -1,12 +1,9 @@
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig, TrainMonitorsConfig
|
||||
@@ -34,11 +31,10 @@ from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
cleanup_processes,
|
||||
cleanup_threads,
|
||||
get_physical_gpu_ids,
|
||||
monitor_process,
|
||||
ProcessGroup,
|
||||
partition_gpus,
|
||||
set_proc_title,
|
||||
torchrun_cmd,
|
||||
)
|
||||
|
||||
SFT_CONFIG = "sft.json"
|
||||
@@ -333,21 +329,14 @@ def sft_local(config: SFTConfig):
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
|
||||
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
|
||||
# Partition GPUs (inference first, then the trainer) only when the launcher must split
|
||||
# them between processes; plain SFT leaves them to torchrun.
|
||||
infer_gpu_ids: list[int] = []
|
||||
trainer_gpu_ids: list[int] = []
|
||||
if config.inference is not None:
|
||||
num_infer_gpus = config.deployment.num_infer_gpus
|
||||
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
|
||||
physical_gpu_ids = get_physical_gpu_ids()
|
||||
if total_requested_gpus > len(physical_gpu_ids):
|
||||
raise ValueError(
|
||||
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
|
||||
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
|
||||
)
|
||||
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
|
||||
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
|
||||
infer_gpu_ids, trainer_gpu_ids = partition_gpus(
|
||||
config.deployment.num_infer_gpus, config.deployment.num_train_gpus
|
||||
)
|
||||
|
||||
# Trainer and online-eval log to a single shared W&B run whose id ($WANDB_RUN_ID)
|
||||
# equals $PRL_RUN_ID, one label per process.
|
||||
@@ -364,37 +353,11 @@ def sft_local(config: SFTConfig):
|
||||
"WANDB_ARGS": json.dumps(sys.argv),
|
||||
}
|
||||
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
error_queue: list[Exception] = []
|
||||
stop_events: dict[str, Event] = {}
|
||||
|
||||
def sigterm_handler(signum, frame):
|
||||
logger.warning("Received SIGTERM, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
|
||||
def start_process(name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> Popen:
|
||||
logger.debug(f"{name.capitalize()} command: {' '.join(cmd)}")
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(log_path, "w") as log_file:
|
||||
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
|
||||
processes.append(process)
|
||||
stop_event = Event()
|
||||
stop_events[name] = stop_event
|
||||
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, error_queue, name), daemon=True)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
return process
|
||||
|
||||
try:
|
||||
with ProcessGroup() as processes:
|
||||
# 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))}")
|
||||
start_process(
|
||||
processes.start(
|
||||
"inference",
|
||||
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
|
||||
env={
|
||||
@@ -413,7 +376,7 @@ def sft_local(config: SFTConfig):
|
||||
for source in eval_env_servers(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} server")
|
||||
start_process(
|
||||
processes.start(
|
||||
f"env/eval/{name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
|
||||
@@ -422,7 +385,7 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting online evals")
|
||||
start_process(
|
||||
processes.start(
|
||||
"online-eval",
|
||||
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
|
||||
env={
|
||||
@@ -439,23 +402,6 @@ def sft_local(config: SFTConfig):
|
||||
log_path=log_dir / "eval.log",
|
||||
)
|
||||
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
trainer_cmd = [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={config.deployment.num_train_gpus}",
|
||||
"-m",
|
||||
"prime_rl.trainer.sft.train",
|
||||
"@",
|
||||
config_path.as_posix(),
|
||||
]
|
||||
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
|
||||
logger.info(f"Starting SFT trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
|
||||
trainer_env = {
|
||||
@@ -470,48 +416,26 @@ def sft_local(config: SFTConfig):
|
||||
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
|
||||
if trainer_gpu_ids:
|
||||
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
|
||||
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
|
||||
processes.start(
|
||||
"trainer",
|
||||
torchrun_cmd(
|
||||
"prime_rl.trainer.sft.train",
|
||||
config_path,
|
||||
config.deployment.num_train_gpus,
|
||||
log_dir,
|
||||
config.log.ranks_filter,
|
||||
),
|
||||
env=trainer_env,
|
||||
log_path=log_dir / "trainer.log",
|
||||
)
|
||||
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Wait for the trainer (and the online-eval process, which drains its final evals
|
||||
# after the trainer's last checkpoint) while surfacing any process failure.
|
||||
terminal_events = [stop_events["trainer"]]
|
||||
if "online-eval" in stop_events:
|
||||
terminal_events.append(stop_events["online-eval"])
|
||||
while True:
|
||||
pending = [event for event in terminal_events if not event.is_set()]
|
||||
if error_queue:
|
||||
logger.error(f"Error: {error_queue[0]}")
|
||||
logger.error("Terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
if not pending:
|
||||
break
|
||||
pending[0].wait(timeout=1)
|
||||
|
||||
if trainer_process.returncode != 0:
|
||||
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
processes.wait("trainer", *(["online-eval"] if config.eval is not None else []))
|
||||
logger.success("SFT training finished!")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.warning("Received interrupt signal, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Error occurred: {e}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
raise
|
||||
|
||||
|
||||
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
|
||||
|
||||
@@ -18,7 +18,7 @@ import os
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.configs.shared import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.eval.runner import POLL_INTERVAL_S, EvalRunner
|
||||
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
|
||||
@@ -6,7 +6,7 @@ import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import GRPOAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages, trainable_nodes
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
@@ -20,6 +20,7 @@ class GRPOAlgorithm(Algorithm):
|
||||
def __init__(self, config: GRPOAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.length_penalty = config.length_penalty
|
||||
self.length_weighted_baseline = config.length_weighted_baseline
|
||||
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
import torch # only the trainer-side extras ship torch; an eval process never scores a group
|
||||
@@ -28,7 +29,7 @@ class GRPOAlgorithm(Algorithm):
|
||||
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
|
||||
length_penalty = self.length_penalty
|
||||
if length_penalty is None:
|
||||
advantages = rewards - rewards.mean()
|
||||
shaped_rewards = rewards
|
||||
else:
|
||||
output = torch.tensor([trace.num_output_tokens for trace in traces], dtype=rewards.dtype)
|
||||
total = torch.tensor([trace.num_total_tokens for trace in traces], dtype=rewards.dtype)
|
||||
@@ -41,6 +42,12 @@ class GRPOAlgorithm(Algorithm):
|
||||
)
|
||||
penalty = rewards.mean() * penalty_frac
|
||||
shaped_rewards = rewards - penalty
|
||||
advantages = shaped_rewards - shaped_rewards.mean()
|
||||
baseline = shaped_rewards.mean()
|
||||
if self.length_weighted_baseline:
|
||||
lengths = torch.tensor(
|
||||
[sum(sum(node.mask) for node in trainable_nodes(trace)) for trace in traces], dtype=rewards.dtype
|
||||
)
|
||||
baseline = (lengths * shaped_rewards).sum() / lengths.sum()
|
||||
advantages = shaped_rewards - baseline
|
||||
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
|
||||
assign_advantages(trace, advantage)
|
||||
|
||||
@@ -8,10 +8,15 @@ from prime_rl.configs.algorithm import ActionLossType
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
|
||||
|
||||
def trainable_nodes(trace: vf.Trace) -> list[vf.MessageNode]:
|
||||
"""Nodes with sampled (mask-True) tokens on the trace's trainable branches, in graph order."""
|
||||
on_trainable_branch = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
|
||||
return [node for node in trace.nodes if id(node) in on_trainable_branch and any(node.mask)]
|
||||
|
||||
|
||||
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
|
||||
"""Assign credit in compact sampled-token order across trainable graph paths."""
|
||||
trainable_nodes = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
|
||||
nodes = [node for node in trace.nodes if id(node) in trainable_nodes and any(node.mask)]
|
||||
nodes = trainable_nodes(trace)
|
||||
for node in nodes:
|
||||
if len(node.mask) != len(node.token_ids):
|
||||
raise ValueError(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from transformers import AutoConfig
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
|
||||
from prime_rl.orchestrator.batch import build_bin_cost, prepare_batch
|
||||
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
max_num = -1
|
||||
for key in state_dict:
|
||||
if not key.startswith(layer_prefix):
|
||||
continue
|
||||
layer_num_str = key[len(layer_prefix) :].split(".")[0]
|
||||
if layer_num_str.isdigit():
|
||||
max_num = max(max_num, int(layer_num_str))
|
||||
return max_num + 1
|
||||
@@ -252,7 +252,10 @@ def get_load_balance_stats(
|
||||
model: nn.Module,
|
||||
group: dist.ProcessGroup | None = None,
|
||||
) -> dict[str, Tensor | None]:
|
||||
"""Compute routing stats after summing raw counts across the group, if given."""
|
||||
"""Compute routing stats after summing raw counts across the group, if given.
|
||||
|
||||
Also returns this rank's raw per-layer expert counts (`[num_moe_layers, num_experts]`) for step-level stats.
|
||||
"""
|
||||
per_layer_max_vio = []
|
||||
per_layer_routing_confidence = []
|
||||
language_model = get_language_model(model)
|
||||
@@ -263,8 +266,9 @@ def get_load_balance_stats(
|
||||
if block_mlp is not None and hasattr(block_mlp, "tokens_per_expert"):
|
||||
block_mlps.append(block_mlp)
|
||||
if not block_mlps:
|
||||
return {"max_vio": None, "routing_confidence": None}
|
||||
return {"max_vio": None, "routing_confidence": None, "tokens_per_expert": torch.empty(0, 0)}
|
||||
|
||||
local_tokens_per_expert = torch.stack([block_mlp.tokens_per_expert for block_mlp in block_mlps])
|
||||
layer_stats = [(block_mlp.tokens_per_expert, block_mlp.routing_confidence_sum) for block_mlp in block_mlps]
|
||||
if group is not None:
|
||||
sizes = [tokens_per_expert.numel() + 1 for tokens_per_expert, _ in layer_stats]
|
||||
@@ -289,6 +293,7 @@ def get_load_balance_stats(
|
||||
return {
|
||||
"max_vio": torch.stack(per_layer_max_vio),
|
||||
"routing_confidence": torch.stack(per_layer_routing_confidence),
|
||||
"tokens_per_expert": local_tokens_per_expert,
|
||||
}
|
||||
|
||||
|
||||
@@ -296,10 +301,15 @@ def get_global_moe_stats(
|
||||
model: nn.Module,
|
||||
ep_group: dist.ProcessGroup | None,
|
||||
dp_cp_group: dist.ProcessGroup,
|
||||
) -> dict[str, Tensor]:
|
||||
"""Reduce one microstep's routing stats across EP, then DP and CP ranks."""
|
||||
) -> tuple[dict[str, Tensor], Tensor]:
|
||||
"""Reduce one microstep's routing stats across EP, then DP and CP ranks.
|
||||
|
||||
Also returns this rank's unreduced per-layer expert counts, to accumulate over the step for `get_expert_load_stats`.
|
||||
"""
|
||||
stats = {}
|
||||
for name, values in get_load_balance_stats(model, group=ep_group).items():
|
||||
load_balance_stats = get_load_balance_stats(model, group=ep_group)
|
||||
tokens_per_expert = load_balance_stats.pop("tokens_per_expert")
|
||||
for name, values in load_balance_stats.items():
|
||||
if values is None:
|
||||
continue
|
||||
value = values.max() if name == "max_vio" else values.mean()
|
||||
@@ -309,9 +319,36 @@ def get_global_moe_stats(
|
||||
dist.all_reduce(value, op=dist.ReduceOp.SUM, group=dp_cp_group)
|
||||
value /= dist.get_world_size(dp_cp_group)
|
||||
stats[name] = value.to("cpu")
|
||||
return stats, tokens_per_expert
|
||||
|
||||
|
||||
def compute_expert_load_stats(tokens_per_expert: Tensor) -> dict[str, Tensor]:
|
||||
"""Per-layer expert-load balance from `[num_moe_layers, num_experts]` token counts, as mean and max over layers.
|
||||
|
||||
`cv` is std/mean of the expert loads, `max_mean` the busiest expert's load over the mean load, and `cold_frac`
|
||||
the fraction of experts receiving under 0.1x the mean load (the MiMo-V2.6 definition).
|
||||
"""
|
||||
mean_load = tokens_per_expert.mean(dim=1)
|
||||
per_layer = {
|
||||
"cv": tokens_per_expert.std(dim=1, correction=0) / mean_load,
|
||||
"max_mean": tokens_per_expert.amax(dim=1) / mean_load,
|
||||
"cold_frac": (tokens_per_expert < 0.1 * mean_load[:, None]).float().mean(dim=1),
|
||||
}
|
||||
stats = {}
|
||||
for name, values in per_layer.items():
|
||||
stats[f"expert_load/{name}/mean"] = values.mean()
|
||||
stats[f"expert_load/{name}/max"] = values.max()
|
||||
return stats
|
||||
|
||||
|
||||
def get_expert_load_stats(tokens_per_expert: Tensor, group: dist.ProcessGroup) -> dict[str, float]:
|
||||
"""Sum a step's per-layer expert counts across the group (every rank routes distinct tokens) and compute load stats."""
|
||||
if tokens_per_expert.numel() == 0: # MoE model without prime-rl MoE layers (HF impl)
|
||||
return {}
|
||||
dist.all_reduce(tokens_per_expert, op=dist.ReduceOp.SUM, group=group)
|
||||
return {name: value.item() for name, value in compute_expert_load_stats(tokens_per_expert).items()}
|
||||
|
||||
|
||||
def get_model(
|
||||
config: ModelConfig, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.bfloat16
|
||||
) -> nn.Module:
|
||||
|
||||
@@ -42,6 +42,7 @@ from prime_rl.trainer.rl.annotations import AnnotationWriter
|
||||
from prime_rl.trainer.model import (
|
||||
forward,
|
||||
get_full_offload_dtype_policy,
|
||||
get_expert_load_stats,
|
||||
get_global_moe_stats,
|
||||
is_tt_moe_model,
|
||||
setup_model,
|
||||
@@ -344,6 +345,7 @@ def train(config: TrainerConfig):
|
||||
cp_group = parallel_dims.world_mesh["cp"].get_group() if cp_enabled else None
|
||||
cp_size = parallel_dims.cp
|
||||
|
||||
step_tokens_per_expert = 0
|
||||
for micro_step, micro_batch in enumerate(micro_batches):
|
||||
input_ids = micro_batch["input_ids"].to("cuda")
|
||||
position_ids = micro_batch["position_ids"].to("cuda")
|
||||
@@ -559,8 +561,10 @@ def train(config: TrainerConfig):
|
||||
annotation_writer.export(micro_batch, out)
|
||||
|
||||
if is_moe_model:
|
||||
for name, value in get_global_moe_stats(model, ep_group, dp_cp_group).items():
|
||||
moe_stats, tokens_per_expert = get_global_moe_stats(model, ep_group, dp_cp_group)
|
||||
for name, value in moe_stats.items():
|
||||
tensors[name].append(value.reshape(1))
|
||||
step_tokens_per_expert += tokens_per_expert
|
||||
|
||||
# Add loss tensors to tensor dict for logging purposes
|
||||
for key, loss_tensor in loss_tensors.items():
|
||||
@@ -634,6 +638,8 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Synchronize the tensor metrics across all steps and ranks
|
||||
tensor_stats = tensors.compute_stats()
|
||||
if is_moe_model:
|
||||
tensor_stats.update(get_expert_load_stats(step_tokens_per_expert, dp_cp_group))
|
||||
|
||||
# Compute step metrics
|
||||
num_local_tokens = seq_len * batch_size
|
||||
|
||||
@@ -27,6 +27,7 @@ from prime_rl.trainer.scheduler import setup_scheduler
|
||||
from prime_rl.trainer.model import (
|
||||
forward,
|
||||
get_full_offload_dtype_policy,
|
||||
get_expert_load_stats,
|
||||
get_global_moe_stats,
|
||||
get_load_balance_stats,
|
||||
is_tt_moe_model,
|
||||
@@ -450,6 +451,7 @@ def train(config: SFTConfig):
|
||||
overlap_optimizer=not run_validation_this_step,
|
||||
)
|
||||
|
||||
step_tokens_per_expert = 0
|
||||
for micro_step, micro_batch in enumerate(micro_batches):
|
||||
if config.log.log_data:
|
||||
print_sample(
|
||||
@@ -476,12 +478,15 @@ def train(config: SFTConfig):
|
||||
finish_backward(gradient_manager)
|
||||
|
||||
if is_moe_model:
|
||||
for name, value in get_global_moe_stats(model, ep_group, dp_cp_group).items():
|
||||
micro_moe_stats, tokens_per_expert = get_global_moe_stats(model, ep_group, dp_cp_group)
|
||||
for name, value in micro_moe_stats.items():
|
||||
moe_stats[f"{name}/mean"] += value / grad_accum_steps
|
||||
if name == "max_vio":
|
||||
moe_stats["max_vio/max"] = torch.maximum(moe_stats["max_vio/max"], value)
|
||||
step_tokens_per_expert += tokens_per_expert
|
||||
|
||||
forward_backward_time = time.perf_counter() - forward_backward_start_time
|
||||
expert_load_stats = get_expert_load_stats(step_tokens_per_expert, dp_cp_group) if is_moe_model else {}
|
||||
|
||||
if gradient_manager is None:
|
||||
global_step_token_count = step_local_token_count.clone()
|
||||
@@ -646,7 +651,7 @@ def train(config: SFTConfig):
|
||||
disk_metrics["step"] = progress.step
|
||||
asyncio.run(monitors.log(disk_metrics, step=progress.step))
|
||||
|
||||
moe_log_metrics = {name: value.item() for name, value in moe_stats.items()}
|
||||
moe_log_metrics = {name: value.item() for name, value in moe_stats.items()} | expert_load_stats
|
||||
if moe_log_metrics:
|
||||
asyncio.run(monitors.log({**moe_log_metrics, "step": progress.step}, step=progress.step))
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.trainer import LoRAConfig, WeightBroadcastConfig
|
||||
from prime_rl.configs.shared import WeightBroadcastConfig
|
||||
from prime_rl.configs.trainer import LoRAConfig
|
||||
from prime_rl.orchestrator.clients import AdminPlane
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.transports.weights.base import WeightReceiver, WeightSender, prune_broadcasts_beyond
|
||||
|
||||
@@ -8,7 +8,7 @@ from typing import final
|
||||
|
||||
import torch.nn as nn
|
||||
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.configs.shared import WeightBroadcastConfig
|
||||
from prime_rl.orchestrator.clients import AdminPlane
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -4,7 +4,8 @@ import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig, LoRAConfig
|
||||
from prime_rl.configs.shared import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.configs.trainer 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 FINISHED_MARKER, WeightReceiver, WeightSender
|
||||
|
||||
@@ -10,8 +10,7 @@ from torch.distributed.tensor import DTensor
|
||||
from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
from vllm.distributed.utils import StatelessProcessGroup
|
||||
|
||||
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
from prime_rl.configs.shared import NCCLWeightBroadcastConfig
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.utils import get_world
|
||||
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
|
||||
@@ -21,6 +20,18 @@ from prime_rl.utils.vlm import get_layer_prefix
|
||||
from prime_rl.utils.weights import resolve_wire_dtype
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
max_num = -1
|
||||
for key in state_dict:
|
||||
if not key.startswith(layer_prefix):
|
||||
continue
|
||||
layer_num_str = key[len(layer_prefix) :].split(".")[0]
|
||||
if layer_num_str.isdigit():
|
||||
max_num = max(max_num, int(layer_num_str))
|
||||
return max_num + 1
|
||||
|
||||
|
||||
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
|
||||
"""Broadcast an integer to a process group using NCCL communicator."""
|
||||
integer_tensor = torch.tensor([integer], dtype=torch.long).cuda()
|
||||
|
||||
@@ -19,7 +19,7 @@ from modelexpress.client import MxClient
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
|
||||
|
||||
from prime_rl.configs.trainer import NIXLWeightBroadcastConfig
|
||||
from prime_rl.configs.shared import NIXLWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.clients import init_nixl_broadcast
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
|
||||
@@ -2,6 +2,9 @@ import contextlib
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
@@ -44,6 +47,41 @@ def get_physical_gpu_ids() -> list[int]:
|
||||
return [int(token.strip()) for token in raw_visible.split(",") if token.strip()]
|
||||
|
||||
|
||||
def partition_gpus(num_infer: int, num_train: int) -> tuple[list[int], list[int]]:
|
||||
"""Split the launcher's physical GPUs into inference GPUs followed by trainer GPUs."""
|
||||
physical_gpu_ids = get_physical_gpu_ids()
|
||||
if num_infer + num_train > len(physical_gpu_ids):
|
||||
raise ValueError(
|
||||
f"Requested {num_infer + num_train} GPUs via deployment settings, but only "
|
||||
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
|
||||
)
|
||||
return physical_gpu_ids[:num_infer], physical_gpu_ids[num_infer : num_infer + num_train]
|
||||
|
||||
|
||||
def torchrun_cmd(
|
||||
module: str, config_path: Path, nproc_per_node: int, log_dir: Path, ranks_filter: list[int]
|
||||
) -> list[str]:
|
||||
"""Single-node torchrun command for a trainer module."""
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
return [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
# Pipe all logs to file, and only master rank logs to stdout
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={nproc_per_node}",
|
||||
"-m",
|
||||
module,
|
||||
"@",
|
||||
config_path.as_posix(),
|
||||
]
|
||||
|
||||
|
||||
def set_proc_title(name: str) -> None:
|
||||
"""Set the process title for visibility in tools like ``ps`` and ``htop``.
|
||||
|
||||
@@ -103,3 +141,65 @@ def monitor_process(process: Popen, stop_event: Event, error_queue: list, proces
|
||||
err_msg += f"\n{process.stderr.read().decode('utf-8')}"
|
||||
error_queue.append(RuntimeError(err_msg))
|
||||
stop_event.set()
|
||||
|
||||
|
||||
class ProcessGroup:
|
||||
"""Launcher subprocesses, each logging to its own file and watched by a monitor thread.
|
||||
|
||||
As a context manager, SIGTERM, Ctrl-C, errors and normal exit all terminate every
|
||||
started process."""
|
||||
|
||||
def __init__(self):
|
||||
self.processes: list[Popen] = []
|
||||
self.monitor_threads: list[Thread] = []
|
||||
self.error_queue: list[Exception] = []
|
||||
self.stop_events: dict[str, Event] = {}
|
||||
|
||||
def __enter__(self) -> "ProcessGroup":
|
||||
signal.signal(signal.SIGTERM, self._sigterm_handler)
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> None:
|
||||
if exc_type is KeyboardInterrupt:
|
||||
get_logger().warning("Received interrupt signal, terminating all processes...")
|
||||
elif isinstance(exc, Exception):
|
||||
get_logger().error(f"Error occurred: {exc}")
|
||||
self.cleanup()
|
||||
if exc_type is KeyboardInterrupt:
|
||||
sys.exit(1)
|
||||
|
||||
def _sigterm_handler(self, signum, frame):
|
||||
get_logger().warning("Received SIGTERM, terminating all processes...")
|
||||
# Clean up here too: a SIGTERM during __exit__'s cleanup would otherwise leave orphans.
|
||||
self.cleanup()
|
||||
sys.exit(1)
|
||||
|
||||
def cleanup(self) -> None:
|
||||
cleanup_threads(self.monitor_threads)
|
||||
cleanup_processes(self.processes)
|
||||
|
||||
def start(self, name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> None:
|
||||
get_logger().debug(f"{name[:1].upper() + name[1:]} command: {' '.join(cmd)}")
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# If we don't log stdout, the inference server hangs
|
||||
with open(log_path, "w") as log_file:
|
||||
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
|
||||
self.processes.append(process)
|
||||
stop_event = Event()
|
||||
self.stop_events[name] = stop_event
|
||||
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, self.error_queue, name), daemon=True)
|
||||
monitor_thread.start()
|
||||
self.monitor_threads.append(monitor_thread)
|
||||
|
||||
def wait(self, *names: str) -> None:
|
||||
"""Block until the named processes exit; exit with code 1 as soon as any started process fails."""
|
||||
events = [self.stop_events[name] for name in names]
|
||||
while True:
|
||||
pending = [event for event in events if not event.is_set()]
|
||||
if self.error_queue:
|
||||
get_logger().error(f"Error: {self.error_queue[0]}")
|
||||
get_logger().error("Terminating all processes...")
|
||||
sys.exit(1)
|
||||
if not pending:
|
||||
return
|
||||
pending[0].wait(timeout=1)
|
||||
|
||||
@@ -151,9 +151,11 @@ def _scalar(episode: vf.Episode) -> float:
|
||||
raise AssertionError("episode has no trainable token")
|
||||
|
||||
|
||||
def _grpo(group: list[vf.Episode], length_penalty=None) -> list[float]:
|
||||
def _grpo(group: list[vf.Episode], length_penalty=None, length_weighted_baseline=False) -> list[float]:
|
||||
"""Drive ``GRPOAlgorithm.score_group`` and read back each per-rollout scalar."""
|
||||
algo = GRPOAlgorithm(GRPOAlgoConfig(length_penalty=length_penalty), clients=None)
|
||||
algo = GRPOAlgorithm(
|
||||
GRPOAlgoConfig(length_penalty=length_penalty, length_weighted_baseline=length_weighted_baseline), clients=None
|
||||
)
|
||||
asyncio.run(algo.score_group(group))
|
||||
return [_scalar(episode) for episode in group]
|
||||
|
||||
@@ -181,6 +183,27 @@ def test_grpo_singleton_group_is_zero():
|
||||
assert _grpo([_build_episode(0.7, sampled_lengths=[2])]) == pytest.approx([0.0], abs=1e-6)
|
||||
|
||||
|
||||
def test_grpo_length_weighted_baseline():
|
||||
# L = [10 + 20 (two turns, observation excluded), 10]: b = (30 * 1 + 10 * 0) / 40 = 0.75
|
||||
group = [
|
||||
_build_episode(1.0, sampled_lengths=[10, 20], obs_lengths=[5]),
|
||||
_build_episode(0.0, sampled_lengths=[10]),
|
||||
]
|
||||
advs = _grpo(group, length_weighted_baseline=True)
|
||||
assert advs == pytest.approx([0.25, -0.75])
|
||||
# per-token advantage is zero-mean across the group's trainable tokens
|
||||
assert 30 * advs[0] + 10 * advs[1] == pytest.approx(0.0, abs=1e-6)
|
||||
# with a length penalty, the weighted baseline applies to the shaped rewards:
|
||||
# penalty = mean(r) * 0.5 * L / max(L) = [0.25, 1/12], shaped = [0.75, -1/12], b = (30 * 0.75 - 10 / 12) / 40
|
||||
cfg = LinearLengthPenaltyConfig(num_output_tokens_weight=0.5, num_input_tokens_weight=0.0, num_turns_weight=0.0)
|
||||
group = [
|
||||
_build_episode(1.0, sampled_lengths=[10, 20], obs_lengths=[5]),
|
||||
_build_episode(0.0, sampled_lengths=[10]),
|
||||
]
|
||||
advs = _grpo(group, length_penalty=cfg, length_weighted_baseline=True)
|
||||
assert advs == pytest.approx([0.75 - 65 / 120, -1 / 12 - 65 / 120])
|
||||
|
||||
|
||||
def test_max_rl_mean_normalized():
|
||||
# mean 0.25: the success gets (1 - 0.25)/0.25 = 3, failures (0 - 0.25)/0.25 = -1
|
||||
assert _max_rl(_make_group(rewards=[1.0, 0.0, 0.0, 0.0])) == pytest.approx([3.0, -1.0, -1.0, -1.0])
|
||||
|
||||
@@ -3,7 +3,13 @@ from types import SimpleNamespace
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from prime_rl.trainer.batch import _is_multimodal_sample, build_bin_cost, pad_micro_batch, prepare_batch, prepare_sample
|
||||
from prime_rl.orchestrator.batch import (
|
||||
_is_multimodal_sample,
|
||||
build_bin_cost,
|
||||
pad_micro_batch,
|
||||
prepare_batch,
|
||||
prepare_sample,
|
||||
)
|
||||
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, TrainingSample
|
||||
|
||||
|
||||
|
||||
@@ -8,13 +8,14 @@ from torch import nn
|
||||
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.trainer.model import load_dcp_from_hf
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM, eager_reference
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM
|
||||
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
|
||||
from prime_rl.trainer.models.layers import norms
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
from tests.unit.train.models import deepseek_v4_eager_reference as eager_reference
|
||||
|
||||
# Every layer is built through `DeepseekV4Attention.__init__`, which refuses to construct without
|
||||
# the kernel it would dispatch to, so the whole file needs tilelang even though nothing here calls it.
|
||||
|
||||
@@ -8,20 +8,21 @@ import torch
|
||||
from torch import nn
|
||||
from torch.utils._python_dispatch import TorchDispatchMode
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, eager_reference
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
|
||||
from prime_rl.trainer.models.deepseek_v4.eager_reference import (
|
||||
apply_rotary_pos_emb_interleaved,
|
||||
dense_mask_from_indices,
|
||||
eager_attention_with_sinks,
|
||||
)
|
||||
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection, DeepseekV4UnweightedRMSNorm
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT, dsv4_mhc
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_rope import dsv4_q_norm_rope, dsv4_rope
|
||||
from prime_rl.utils.cp import CPContext
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
from tests.unit.train.models import deepseek_v4_eager_reference as eager_reference
|
||||
from tests.unit.train.models.deepseek_v4_eager_reference import (
|
||||
apply_rotary_pos_emb_interleaved,
|
||||
dense_mask_from_indices,
|
||||
eager_attention_with_sinks,
|
||||
)
|
||||
|
||||
try:
|
||||
import tilelang
|
||||
|
||||
@@ -4,7 +4,7 @@ import torch.nn.functional as F
|
||||
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher
|
||||
from prime_rl.trainer.model import is_tt_moe_model
|
||||
from prime_rl.trainer.model import compute_expert_load_stats, is_tt_moe_model
|
||||
from prime_rl.trainer.models.deepseek_v4.moe import DeepseekV4Experts
|
||||
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch
|
||||
@@ -235,3 +235,20 @@ def test_expert_type_and_activation_are_independent(expert_type, activation):
|
||||
assert moe.experts.activation is ActivationDispatch[activation]
|
||||
assert (moe.shared_expert.gate_proj is not None) == has_gate
|
||||
assert moe.shared_expert.activation is ActivationDispatch[activation]
|
||||
|
||||
|
||||
def test_expert_load_stats():
|
||||
# Layer 0 is balanced; layer 1 sends 8 of 16 tokens to one expert and leaves one expert cold (< 0.1x mean).
|
||||
tokens_per_expert = torch.tensor([[4.0, 4.0, 4.0, 4.0], [8.0, 4.0, 4.0, 0.0]])
|
||||
stats = compute_expert_load_stats(tokens_per_expert)
|
||||
expected = {
|
||||
"expert_load/cv/mean": 2**0.5 / 4,
|
||||
"expert_load/cv/max": 2**0.5 / 2,
|
||||
"expert_load/max_mean/mean": 1.5,
|
||||
"expert_load/max_mean/max": 2.0,
|
||||
"expert_load/cold_frac/mean": 0.125,
|
||||
"expert_load/cold_frac/max": 0.25,
|
||||
}
|
||||
assert stats.keys() == expected.keys()
|
||||
for name, value in expected.items():
|
||||
assert stats[name].item() == pytest.approx(value)
|
||||
|
||||
Reference in New Issue
Block a user